Compare commits

..

38 Commits

Author SHA1 Message Date
firestar5683 adca218266 Supply pinned OpenCV to custom pytest jobs 2026-11-28 01:31:21 -06:00
firestar5683 92e09398e8 Cover relative lead speed in the StarPort layout test 2026-11-28 00:38:43 -06:00
firestar5683 19d1cab0b3 Qualify default controller replay expectations 2026-11-28 00:21:42 -06:00
firestar5683 c6f6f64e77 Qualify Panda safety checks and restore fresh-install defaults 2026-11-28 00:18:40 -06:00
firestar5683 50e07e8eef Repair vehicle and Galaxy regression contracts 2026-11-28 00:14:41 -06:00
firestar5683 b7953cf4a0 Restore replay execution and align CI fixtures with current settings 2026-11-27 23:56:18 -06:00
firestar5683 df7d67c39f Restore Kona ccNC steering and smooth enhanced stops 2026-11-27 23:32:19 -06:00
firestar5683 439ac2274e Use camera brake hold on Corolla TSS2 hybrids 2026-11-27 23:13:04 -06:00
firestar5683 1066c1e0f2 Restore legacy Sportage lane warning display 2026-11-27 23:10:24 -06:00
natehuby76 76b76080f5 allow saving searched places 2026-11-27 23:56:04 -05:00
firestar5683 64fdc72c1e Honor LKAS wheel action assignments across vehicles 2026-11-27 22:55:28 -06:00
firestar5683 3831031635 Recover Sportage lane display after camera steering release 2026-11-27 22:51:31 -06:00
firestar5683 27aeb44b41 Damp rapid highway steering feedforward on ninth-generation Accord 2026-11-27 22:47:57 -06:00
firestar5683 988217726f Smooth Palisade steering corrections at mid speeds 2026-11-27 22:45:44 -06:00
firestar5683 954edb60af Damp large Tucson steering corrections at city speeds 2026-11-27 22:44:50 -06:00
firestar5683 20bef284c6 Honor Palisade LKAS wheel action assignments 2026-11-27 22:44:26 -06:00
firestar5683 c194a0c092 Build steering torque earlier into curves on the Yukon XL 2026-11-27 22:43:54 -06:00
Danny 54fa1a1875 Build 2026-11-27 18:58:46 -08:00
Danny a46a504450 Galaxy: Reuse the ready pill and test phone internet states 2026-11-27 18:54:58 -08:00
Danny d47bf5e636 Restore Android Network Sharing 2026-11-27 18:54:58 -08:00
Danny 8aa143deb0 Galaxy: Accept phone internet when the phone starts sharing
The Galaxy web card that turned phone internet on is gone, and the Android app now offers the switch in its own connection options. A heartbeat from a phone on the Galaxy hotspot now turns sharing on, so the comma accepts the phone without a separate setting. The phone's own opt-in, with its disclosure, is the consent. LAN, remote and second-phone heartbeats are still refused.
2026-11-27 18:54:58 -08:00
Danny 3d6d69b70d Build 2026-11-27 18:49:21 -08:00
Danny a43597aefe MDNS: Add to Comma Menu and Galaxy 2026-11-27 17:44:45 -08:00
Danny 6d5d6c249f Galaxy: Open by galaxy.local on Every Network, Including the Hotspot 2026-11-27 17:44:45 -08:00
Danny de8f420d95 Galaxy: Hold Connection Slots Only While a Request Runs 2026-11-27 17:44:45 -08:00
firestar5683 37f9e1a9d5 Retain Hyundai classic AOL intent through stock cruise off lag 2026-11-27 15:36:55 -06:00
firestar5683 27a4566309 Retry EPS firmware discovery for manually selected Honda Accord 2026-11-27 15:12:35 -06:00
firestar5683 f60c2147c0 Restore Kona standby cruise display and soften final stops 2026-11-27 15:10:27 -06:00
firestar5683 240edccfd6 Release confirmed stopped lead departures through turns 2026-11-27 15:02:17 -06:00
firestar5683 26e0f927bd Ease Elantra cruise corrections near set speed 2026-11-27 15:01:10 -06:00
firestar5683 4bf630534f Damp Tucson highway wobble and honor Hyundai LKAS wheel mappings 2026-11-27 15:00:39 -06:00
firestar5683 6db575bded Retain Mazda AOL through the first EPS block frame 2026-11-27 14:57:08 -06:00
firestar5683 b7d2723bf0 Recognize Sportage camera warnings across one frame of timing skew 2026-11-27 14:54:13 -06:00
firestar5683 9b545fa585 Keep Mazda AOL armed while steering permission is pending 2026-11-27 14:49:19 -06:00
firestar5683 d0904dfaaf Match higher speed limits on Redneck Cruise SET 2026-11-27 14:47:42 -06:00
firestar5683 6938b22db9 Damp Camry Hybrid highway corrections near lane center 2026-11-27 14:44:49 -06:00
firestarsdog b56e624681 Drop unused lead distance and stop-light color from Aethergauge 2026-11-27 13:11:25 -05:00
firestarsdog 48717d2b08 Remove Aethergauge unused transitions 2026-11-27 13:05:51 -05:00
185 changed files with 3025 additions and 2095 deletions
+1
View File
@@ -75,6 +75,7 @@ jobs:
run: | run: |
tools/op.sh test \ tools/op.sh test \
openpilot/starpilot/flm/tests/test_offroad_backend.py \ openpilot/starpilot/flm/tests/test_offroad_backend.py \
openpilot/starpilot/flm/tests/test_offroad_report.py \
openpilot/starpilot/flm/tests/test_offroad_coordinate_policy.py \ openpilot/starpilot/flm/tests/test_offroad_coordinate_policy.py \
openpilot/starpilot/flm/tests/test_offroad_retained_trials.py \ openpilot/starpilot/flm/tests/test_offroad_retained_trials.py \
openpilot/starpilot/flm/tests/test_offroad_process_lifecycle.py \ openpilot/starpilot/flm/tests/test_offroad_process_lifecycle.py \
+5
View File
@@ -343,6 +343,11 @@ jobs:
run: | run: |
uv pip install --python .venv/bin/python --only-binary av av==19.0.1 uv pip install --python .venv/bin/python --only-binary av av==19.0.1
.venv/bin/python -c "import av; assert 'libx264' in av.codecs_available" .venv/bin/python -c "import av; assert 'libx264' in av.codecs_available"
- name: Provide pinned OpenCV DNN for vision contract tests
if: ${{ !cancelled() && steps.build.outcome == 'success' }}
run: |
uv pip install --python .venv/bin/python --no-deps --only-binary :all: opencv-python-headless==4.11.0.86
.venv/bin/python -c "import cv2; assert cv2.__version__ == '4.11.0'; assert callable(cv2.dnn.readNetFromONNX); assert callable(cv2.dnn.NMSBoxes)"
- name: Provide Mesa software graphics for pixel-level tests - name: Provide Mesa software graphics for pixel-level tests
if: ${{ !cancelled() && steps.build.outcome == 'success' }} if: ${{ !cancelled() && steps.build.outcome == 'success' }}
run: sudo apt-get update && sudo apt-get install -y libegl1 libgles-dev libgl1-mesa-dri run: sudo apt-get update && sudo apt-get install -y libegl1 libgles-dev libgl1-mesa-dri
+13 -7
View File
@@ -120,7 +120,7 @@ def _tesla_fw_uses_normal_bus0() -> bool:
# **** for use live only **** # **** for use live only ****
def fingerprint(can_recv: CanRecvCallable, can_send: CanSendCallable, set_obd_multiplexing: ObdCallback, def fingerprint(can_recv: CanRecvCallable, can_send: CanSendCallable, set_obd_multiplexing: ObdCallback,
cached_params: CarParamsT | None, *, known_gm_bus0: bool = False, known_ford_bus0: bool = False, cached_params: CarParamsT | None, *, known_gm_bus0: bool = False, known_ford_bus0: bool = False,
known_tesla_bus0: bool = False known_tesla_bus0: bool = False, known_honda_accord: bool = False
) -> tuple[str | None, dict, str, list[CarParams.CarFw], CarParams.FingerprintSource, bool]: ) -> tuple[str | None, dict, str, list[CarParams.CarFw], CarParams.FingerprintSource, bool]:
if known_ford_bus0 and (known_gm_bus0 or not ford_normal_bus0_queries()): if known_ford_bus0 and (known_gm_bus0 or not ford_normal_bus0_queries()):
raise ValueError('Ford discovery topology no longer uses normal bus 0') raise ValueError('Ford discovery topology no longer uses normal bus 0')
@@ -218,12 +218,15 @@ def fingerprint(can_recv: CanRecvCallable, can_send: CanSendCallable, set_obd_mu
else: else:
car_fw = get_fw_versions(can_recv, can_send, set_obd_multiplexing, car_fw = get_fw_versions(can_recv, can_send, set_obd_multiplexing,
query_brand=normal_brand, normal_bus_only=True) 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): if normal_brand == 'honda':
# Read this car's VIN and EPS through the OBD port, as the generic path below does. Without the VIN candidates = ({HONDA.HONDA_ACCORD} if known_honda_accord or fixed_fingerprint == HONDA.HONDA_ACCORD
# the result is never cached, so every start would repeat the query. else match_fw_to_car(car_fw, vin)[1])
set_obd_multiplexing(True) if honda_eps_needs_obd(candidates, car_fw):
vin_rx_addr, vin_rx_bus, vin = get_vin(can_recv, can_send, (0, 1)) # The model can be selected manually even when radar and camera firmware alone don't identify it.
car_fw = get_fw_versions(can_recv, can_send, set_obd_multiplexing, query_brand='honda') # Read the EPS over OBD before deciding which steering protocol to use.
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} ecu_rx_addrs = {(fw.responseAddress, fw.subAddress or None, fw.bus) for fw in car_fw if fw.responseAddress > 0}
else: else:
full_scan = True full_scan = True
@@ -320,6 +323,9 @@ def get_car(can_recv: CanRecvCallable, can_send: CanSendCallable, set_obd_multip
elif known_tesla_bus0: elif known_tesla_bus0:
candidate, fingerprints, vin, car_fw, source, exact_match = fingerprint( candidate, fingerprints, vin, car_fw, source, exact_match = fingerprint(
can_recv, can_send, set_obd_multiplexing, cached_params, known_tesla_bus0=True) can_recv, can_send, set_obd_multiplexing, cached_params, known_tesla_bus0=True)
elif forced_candidate == HONDA.HONDA_ACCORD:
candidate, fingerprints, vin, car_fw, source, exact_match = fingerprint(
can_recv, can_send, set_obd_multiplexing, cached_params, known_honda_accord=True)
else: else:
candidate, fingerprints, vin, car_fw, source, exact_match = fingerprint(can_recv, can_send, set_obd_multiplexing, cached_params) candidate, fingerprints, vin, car_fw, source, exact_match = fingerprint(can_recv, can_send, set_obd_multiplexing, cached_params)
@@ -5,8 +5,9 @@ import unittest
from unittest.mock import patch from unittest.mock import patch
from opendbc.car.can_definitions import CanData from opendbc.car.can_definitions import CanData
from opendbc.car.car_helpers import fingerprint from opendbc.car.car_helpers import fingerprint, get_car
from opendbc.car import fw_versions from opendbc.car import fw_versions, structs
from opendbc.car.honda.values import CAR, HondaFlags
from opendbc.car.vin import VIN_UNKNOWN from opendbc.car.vin import VIN_UNKNOWN
@@ -35,7 +36,6 @@ class TestHondaNormalDiscovery(unittest.TestCase):
self.assertIsNone(actual[0]) self.assertIsNone(actual[0])
def _accord_discovery(self, normal_read, obd_read): def _accord_discovery(self, normal_read, obd_read):
from opendbc.car.honda.values import CAR
switches = [] switches = []
with patch('opendbc.car.car_helpers.get_vin', return_value=(-1, -1, VIN_UNKNOWN)) as vin, \ 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.get_fw_versions', side_effect=[normal_read, obd_read]) as query, \
@@ -60,6 +60,30 @@ class TestHondaNormalDiscovery(unittest.TestCase):
self.assertFalse(any(switches)) self.assertFalse(any(switches))
query.assert_called_once() query.assert_called_once()
def test_manually_selected_accord_queries_eps_when_radar_and_camera_cannot_identify_it(self):
radar = structs.CarParams.CarFw.new_message(ecu="fwdRadar", address=0x18DAB0F1, fwVersion=b"36802-TVA-A190\x00\x00", brand="honda")
camera = structs.CarParams.CarFw.new_message(ecu="fwdCamera", address=0x18DAB5F1, fwVersion=b"36161-TVA-A060\x00\x00", brand="honda")
normal_fw = [radar, camera]
self.assertNotIn(CAR.HONDA_ACCORD, fw_versions.match_fw_to_car(normal_fw, VIN_UNKNOWN)[1])
for version, angle in ((b"39990-TVA-A160\x00\x00", False), (b"39990-TVA,A16C\x00\x00", True), (None, False)):
with self.subTest(version=version):
switches = []
obd_fw = normal_fw.copy()
if version is not None:
obd_fw.append(structs.CarParams.CarFw.new_message(ecu="eps", address=0x18DA30F1, fwVersion=version, brand="honda"))
with patch('opendbc.car.car_helpers.get_vin', return_value=(-1, -1, VIN_UNKNOWN)), \
patch('opendbc.car.car_helpers.get_fw_versions', side_effect=[normal_fw, obd_fw]) as query, \
patch('opendbc.car.car_helpers.can_fingerprint', return_value=(None, {0: {}, 1: {}, 2: {}})):
interface = get_car(lambda wait_for_one=False: [recorded_frames()], lambda frames: None, switches.append,
False, False, forced_candidate=CAR.HONDA_ACCORD)
self.assertEqual(switches, [False, True, False])
self.assertEqual([call.kwargs for call in query.call_args_list],
[{'query_brand': 'honda', 'normal_bus_only': True}, {'query_brand': 'honda'}])
self.assertEqual(interface.CP.fingerprintSource, structs.CarParams.FingerprintSource.fixed)
self.assertEqual(interface.CP.steerControlType == structs.CarParams.SteerControlType.angle, angle)
self.assertEqual(bool(interface.CP.flags & HondaFlags.EPS_FW_UNREAD), version is None)
def test_incomplete_or_invalid_traffic_cannot_select_honda(self): def test_incomplete_or_invalid_traffic_cannot_select_honda(self):
from opendbc.car.honda.discovery import normal_bus_topology from opendbc.car.honda.discovery import normal_bus_topology
frames = recorded_frames() frames = recorded_frames()
@@ -301,8 +301,9 @@ def test_starting_during_active_engagement_requires_a_fresh_disabled_epoch():
assert intent.allowed_latch assert intent.allowed_latch
def test_actual_card_active_observation_requires_fresh_selfdrive_state(monkeypatch): def test_actual_card_active_observation_requires_fresh_selfdrive_state(monkeypatch, tmp_path):
from openpilot.cereal import log from openpilot.cereal import log
from openpilot.common.params import Params
from openpilot.selfdrive.car import card as card_module from openpilot.selfdrive.car import card as card_module
from openpilot.selfdrive.car.card import Car from openpilot.selfdrive.car.card import Car
from openpilot.starpilot.aol.intent import AolCardIntent from openpilot.starpilot.aol.intent import AolCardIntent
@@ -329,6 +330,7 @@ def test_actual_card_active_observation_requires_fresh_selfdrive_state(monkeypat
host = Car.__new__(Car) host = Car.__new__(Car)
host.CP, host.aol_card_intent = cp, intent host.CP, host.aol_card_intent = cp, intent
host.aol_settings = intent.settings host.aol_settings = intent.settings
host.params = Params(str(tmp_path))
host.CI = SimpleNamespace(update=lambda _: cs, CS=SimpleNamespace(), host.CI = SimpleNamespace(update=lambda _: cs, CS=SimpleNamespace(),
can_parsers=CarInterface.CarState(cp).get_can_parsers(cp)) can_parsers=CarInterface.CarState(cp).get_can_parsers(cp))
host.RI = SimpleNamespace(update=lambda _: None) host.RI = SimpleNamespace(update=lambda _: None)
@@ -46,8 +46,10 @@ class CANFDLfaStatus:
LENGTH = 16 LENGTH = 16
MAX_AGE_NS = MAX_AGE_NS MAX_AGE_NS = MAX_AGE_NS
def __init__(self, bus): def __init__(self, bus, *, eps_response_margin_ns=0, track_camera_release=False):
self.bus = bus self.bus = bus
self.eps_response_margin_ns = eps_response_margin_ns
self.track_camera_release = track_camera_release
self.last_packet_ns = 0 self.last_packet_ns = 0
self.counter = None self.counter = None
self.body = None self.body = None
@@ -61,6 +63,7 @@ class CANFDLfaStatus:
self.camera_integrity = False self.camera_integrity = False
self.camera_healthy_ns = 0 self.camera_healthy_ns = 0
self.camera_fault_since_ns = 0 self.camera_fault_since_ns = 0
self.camera_release_ns = 0
self.camera_fault_same_batch_healthy = False self.camera_fault_same_batch_healthy = False
self.request_active = False self.request_active = False
self.request_since_ns = 0 self.request_since_ns = 0
@@ -103,30 +106,46 @@ class CANFDLfaStatus:
continue continue
if address == self.ADDRESS and bus == self.bus and len(data) != self.LENGTH: if address == self.ADDRESS and bus == self.bus and len(data) != self.LENGTH:
self.camera_integrity = False self.camera_integrity = False
if self.track_camera_release:
self.camera_healthy_ns = 0
if address != self.ADDRESS or bus != self.bus or len(data) != self.LENGTH: if address != self.ADDRESS or bus != self.bus or len(data) != self.LENGTH:
continue continue
self.last_packet_ns = stamp self.last_packet_ns = stamp
if int.from_bytes(data[:2], 'little') != hkg_can_fd_checksum(address, None, bytearray(data)): if int.from_bytes(data[:2], 'little') != hkg_can_fd_checksum(address, None, bytearray(data)):
self.camera_integrity = False self.camera_integrity = False
if self.track_camera_release:
self.camera_healthy_ns = 0
continue continue
counter = data[2] counter = data[2]
advancing = self.counter is None or counter == (self.counter + 1) % 256 advancing = self.counter is None or counter == (self.counter + 1) % 256
self.counter = counter self.counter = counter
if not advancing: if not advancing:
self.camera_integrity = False self.camera_integrity = False
if self.track_camera_release:
self.camera_healthy_ns = 0
continue continue
self.camera_integrity = True self.camera_integrity = True
body = bytes(data) body = bytes(data)
if self._ownership_warning(body): camera_request = (body[6] >> 4) & 3
camera_warning = self._system_fail(body)
if self._ownership_warning(body) or (self.track_camera_release and camera_warning and camera_request == 1):
if not self.camera_fault_since_ns: if not self.camera_fault_since_ns:
self.camera_fault_same_batch_healthy = (self.camera_healthy_ns == stamp and self.observed_ns == stamp and self.camera_fault_same_batch_healthy = (self.camera_healthy_ns == stamp and self.observed_ns == stamp and
self.body is not None and self.body[2] == (counter - 1) % 256) self.body is not None and self.body[2] == (counter - 1) % 256)
self.camera_fault_since_ns = stamp self.camera_fault_since_ns = stamp
if camera_request:
self.camera_release_ns = 0
elif not self.camera_release_ns:
self.camera_release_ns = stamp
else: else:
self.camera_fault_since_ns = 0 self.camera_fault_since_ns = self.camera_release_ns = 0
self.camera_fault_same_batch_healthy = False self.camera_fault_same_batch_healthy = False
indication = (body[4] >> 6) | ((body[5] & 1) << 2) indication = (body[4] >> 6) | ((body[5] & 1) << 2)
self.camera_healthy_ns = stamp if indication < 4 and not (body[6] & 0xF0 or body[7] >> 4 == 15) else 0 normal = indication < 4 and not (body[6] & 0xC0 or body[7] >> 4 == 15)
if normal and camera_request == 0:
self.camera_healthy_ns = stamp
elif not (self.track_camera_release and normal and camera_request == 1):
self.camera_healthy_ns = 0
self.body, self.observed_ns = body, stamp self.body, self.observed_ns = body, stamp
def current(self, now_ns): def current(self, now_ns):
@@ -135,10 +154,31 @@ class CANFDLfaStatus:
return None return None
@staticmethod
def _system_fail(body):
return (((body[4] >> 6) | ((body[5] & 1) << 2)) == 4 and body[7] >> 4 == 15 and not body[6] & 0xC0)
@staticmethod @staticmethod
def _ownership_warning(body): def _ownership_warning(body):
return (((body[4] >> 6) | ((body[5] & 1) << 2)) == 4 and body[7] >> 4 == 15 and return CANFDLfaStatus._system_fail(body) and not body[6] & 0x30
not body[6] & 0xF0)
def steering_active_current(self, now_ns):
return (self.eps_active and self.eps_healthy and
0 < self.eps_observed_ns <= now_ns <= self.eps_observed_ns + MAX_AGE_NS)
def sportage_legacy_display(self, cp, now_ns, *, healthy):
if not (healthy and cp.carFingerprint == CAR.KIA_SPORTAGE_5TH_GEN and cp.openpilotLongitudinalControl and
cp.alternativeExperience == 32 and len(cp.safetyConfigs) == 1 and
cp.safetyConfigs[0].safetyModel == structs.CarParams.SafetyModel.hyundaiCanfd and
cp.safetyConfigs[0].safetyParam == 0x82C):
return False
body = self.current(now_ns)
if body is None or not self.camera_integrity or not self.eps_healthy:
return False
indication = (body[4] >> 6) | ((body[5] & 1) << 2)
return (0 < self.eps_observed_ns <= now_ns <= self.eps_observed_ns + MAX_AGE_NS and
not (body[6] & 0xC0) and
((indication < 4 and body[7] >> 4 == 0) or self._system_fail(body)))
def owns_display_status(self, active, now_ns, *, healthy=False): def owns_display_status(self, active, now_ns, *, healthy=False):
if active and not self.request_active: if active and not self.request_active:
@@ -149,7 +189,12 @@ class CANFDLfaStatus:
if not healthy or body is None or not self.camera_integrity or not eps_fresh or not self.eps_healthy: if not healthy or body is None or not self.camera_integrity or not eps_fresh or not self.eps_healthy:
self.request_since_ns = self.display_fault_since_ns = self.display_last_active_ns = 0 self.request_since_ns = self.display_fault_since_ns = self.display_last_active_ns = 0
return False return False
if not self._ownership_warning(body): release_delay = self.camera_release_ns - self.camera_fault_since_ns
# A short competing camera request can delay handover evidence until its release.
camera_released = (not self.track_camera_release or release_delay == 0 or
(0 < release_delay <= MAX_AGE_NS + self.eps_response_margin_ns and
not body[5] & 0xFE and body[6] & 0x0F == 8))
if not self._ownership_warning(body) or not camera_released:
self.display_fault_since_ns = self.display_last_active_ns = 0 self.display_fault_since_ns = self.display_last_active_ns = 0
return False return False
established = self.display_fault_since_ns == self.camera_fault_since_ns and self.display_fault_since_ns > 0 established = self.display_fault_since_ns == self.camera_fault_since_ns and self.display_fault_since_ns > 0
@@ -161,7 +206,7 @@ class CANFDLfaStatus:
qualified = (self.eps_active and 0 < self.request_since_ns <= self.eps_active_since_ns <= self.camera_fault_since_ns and qualified = (self.eps_active and 0 < self.request_since_ns <= self.eps_active_since_ns <= self.camera_fault_since_ns and
((0 < self.camera_fault_since_ns - self.camera_healthy_ns <= MAX_AGE_NS) or ((0 < self.camera_fault_since_ns - self.camera_healthy_ns <= MAX_AGE_NS) or
(self.camera_fault_since_ns == self.camera_healthy_ns and self.camera_fault_same_batch_healthy)) and (self.camera_fault_since_ns == self.camera_healthy_ns and self.camera_fault_same_batch_healthy)) and
self.camera_fault_since_ns - self.eps_active_since_ns <= OWNERSHIP_RESPONSE_NS) self.camera_fault_since_ns - self.eps_active_since_ns <= OWNERSHIP_RESPONSE_NS + self.eps_response_margin_ns)
if qualified: if qualified:
self.display_fault_since_ns = self.camera_fault_since_ns self.display_fault_since_ns = self.camera_fault_since_ns
self.display_last_active_ns = now_ns self.display_last_active_ns = now_ns
@@ -41,7 +41,7 @@ from opendbc.car.hyundai.torque_ev_scc import eligible as torque_ev_scc_eligible
from opendbc.car.hyundai.ccnc_ev_stock import replacement_requested, qualified as qualified_ccnc_ev_stock from opendbc.car.hyundai.ccnc_ev_stock import replacement_requested, qualified as qualified_ccnc_ev_stock
from opendbc.car.hyundai.angle_tx_recovery import AngleTxRecovery from opendbc.car.hyundai.angle_tx_recovery import AngleTxRecovery
from opendbc.car.hyundai.values import is_blended, HyundaiFlags, HyundaiSafetyFlags, Buttons, CarControllerParams, CAR from opendbc.car.hyundai.values import is_blended, HyundaiFlags, HyundaiSafetyFlags, Buttons, CarControllerParams, CAR
from opendbc.car.interfaces import CarControllerBase from opendbc.car.interfaces import CarControllerBase, V_CRUISE_MAX
from opendbc.car.vehicle_model import VehicleModel from opendbc.car.vehicle_model import VehicleModel
EV9_OP_LONG_ANGLE_TARGET_MAX = 140.0 EV9_OP_LONG_ANGLE_TARGET_MAX = 140.0
@@ -178,7 +178,6 @@ class CarController(CarControllerBase):
int(CP.safetyConfigs[-1].safetyParam) in (0x0811, 0x0891)) int(CP.safetyConfigs[-1].safetyParam) in (0x0811, 0x0891))
self.canfd_torque_aol_status = (qualified_canfd_stock_aol(CP) or qualified_canfd_long_aol(CP)) self.canfd_torque_aol_status = (qualified_canfd_stock_aol(CP) or qualified_canfd_long_aol(CP))
self.ccnc_fault_ownership_required = preserves_stock_lfa(CP) self.ccnc_fault_ownership_required = preserves_stock_lfa(CP)
self.kona_last_lfa_counter = None
self.canfd_dash_icons = CanFDDashIcons() if ioniq6_status or self.canfd_torque_aol_status else None self.canfd_dash_icons = CanFDDashIcons() if ioniq6_status or self.canfd_torque_aol_status else None
self.classic_dash_icons = CanFDDashIcons() if classic_aol_dash_enabled(CP) else None self.classic_dash_icons = CanFDDashIcons() if classic_aol_dash_enabled(CP) else None
self.classic_lfa_icon = None self.classic_lfa_icon = None
@@ -447,7 +446,13 @@ class CarController(CarControllerBase):
_projection = self.learning_projection_observer _projection = self.learning_projection_observer
can_sends = [] can_sends = []
stock_popup_owned = False stock_popup_owned = False
sportage_legacy_display = False
stock_ccnc_owned = False stock_ccnc_owned = False
kona_handoff = (self.CP.carFingerprint == CAR.HYUNDAI_KONA_2ND_GEN and
self.CP.safetyConfigs[-1].safetyParam == KONA_IDLE_AOL_WORD)
show_cruise = CS.out.cruiseState.available and (not kona_handoff or CC.enabled or
0. < CS.out.vCruiseCluster <= V_CRUISE_MAX)
show_ccnc_lateral = CC.latActive
canfd_lfa_icon = (self.canfd_dash_icons.update(self.frame, CC.enabled, CC.latActive) canfd_lfa_icon = (self.canfd_dash_icons.update(self.frame, CC.enabled, CC.latActive)
if self.canfd_dash_icons is not None else None) if self.canfd_dash_icons is not None else None)
@@ -574,36 +579,29 @@ class CarController(CarControllerBase):
stock_lfa = stock_source.current(clock_boot_ns()) if stock_source is not None else None stock_lfa = stock_source.current(clock_boot_ns()) if stock_source is not None else None
stock_faults = stock_source.last_fault() if stock_source is not None and stock_lfa is None else None stock_faults = stock_source.last_fault() if stock_source is not None and stock_lfa is None else None
stock_owned_status = False stock_owned_status = False
if kona_handoff:
show_ccnc_lateral = bool(apply_steer_req and stock_source is not None and stock_source.steering_active_current(clock_boot_ns()))
if stock_source is not None: if stock_source is not None:
display_healthy = CS.out.canValid and not (CS.out.canTimeout or CS.out.steerFaultTemporary or display_healthy = CS.out.canValid and not (CS.out.canTimeout or CS.out.steerFaultTemporary or
CS.out.steerFaultPermanent or CS.out.accFaulted) CS.out.steerFaultPermanent or CS.out.accFaulted)
stock_owned_status = stock_source.owns_display_status(apply_steer_req, clock_boot_ns(), healthy=display_healthy) stock_owned_status = stock_source.owns_display_status(apply_steer_req, clock_boot_ns(), healthy=display_healthy)
stock_popup_owned = stock_source.owns_disengage_popup(apply_steer_req, clock_boot_ns(), healthy=display_healthy, stock_popup_owned = stock_source.owns_disengage_popup(apply_steer_req, clock_boot_ns(), healthy=display_healthy,
qualified_warning=stock_owned_status) qualified_warning=stock_owned_status)
if ccnc_non_lka: if self.CP.carFingerprint == CAR.KIA_SPORTAGE_5TH_GEN:
sportage_legacy_display = stock_source.sportage_legacy_display(self.CP, clock_boot_ns(), healthy=display_healthy)
if ccnc_non_lka and not kona_handoff:
stock_ccnc_owned = stock_source.owns_ccnc_fault_status(clock_boot_ns(), display_sample_ns=CS.ccnc_162_ts_ns, stock_ccnc_owned = stock_source.owns_ccnc_fault_status(clock_boot_ns(), display_sample_ns=CS.ccnc_162_ts_ns,
healthy=display_healthy, qualified_warning=stock_owned_status) healthy=display_healthy, qualified_warning=stock_owned_status)
damping_source = getattr(CS, "stock_lkas_damping", None) damping_source = getattr(CS, "stock_lkas_damping", None)
kona_handoff = (self.CP.carFingerprint == CAR.HYUNDAI_KONA_2ND_GEN and can_sends.extend(hyundaicanfd.create_steering_messages(self.packer, self.CP, self.CAN,
self.CP.safetyConfigs[-1].safetyParam == KONA_IDLE_AOL_WORD) steering_status_active, apply_steer_req, apply_torque,
lfa_counter = None stock_lfa=stock_lfa, stock_lfa_faults=stock_faults,
if kona_handoff: stock_lfa_owned_status=stock_owned_status and not kona_handoff,
if (CC.enabled or CC.latActive) and stock_lfa is not None: stock_lkas_damping=(damping_source.current_damping(clock_boot_ns())
if stock_lfa[2] != self.kona_last_lfa_counter: if damping_source is not None else None),
lfa_counter = stock_lfa[2] legacy_lane_display=sportage_legacy_display))
self.kona_last_lfa_counter = lfa_counter if _projection is not None:
else: _projection.emit('hyundai.CANFD_TORQUE', apply_torque, apply_steer_req, can_sends[-1])
self.kona_last_lfa_counter = None
if not kona_handoff or lfa_counter is not None:
can_sends.extend(hyundaicanfd.create_steering_messages(self.packer, self.CP, self.CAN,
steering_status_active, apply_steer_req, apply_torque,
stock_lfa=stock_lfa, stock_lfa_faults=stock_faults,
stock_lfa_owned_status=stock_owned_status,
stock_lkas_damping=(damping_source.current_damping(clock_boot_ns())
if damping_source is not None else None),
lfa_counter=lfa_counter))
if _projection is not None:
_projection.emit('hyundai.CANFD_TORQUE', apply_torque, apply_steer_req, can_sends[-1])
# prevent LFA from activating on LKA steering cars by sending "no lane lines detected" to ADAS ECU # prevent LFA from activating on LKA steering cars by sending "no lane lines detected" to ADAS ECU
if ( if (
@@ -628,14 +626,13 @@ class CarController(CarControllerBase):
now_nanos - min(CS.ccnc_161_ts_ns, CS.ccnc_162_ts_ns) <= 50_000_000 and now_nanos - min(CS.ccnc_161_ts_ns, CS.ccnc_162_ts_ns) <= 50_000_000 and
abs(CS.ccnc_161_ts_ns - CS.ccnc_162_ts_ns) <= 50_000_000) abs(CS.ccnc_161_ts_ns - CS.ccnc_162_ts_ns) <= 50_000_000)
if fresh_pair: if fresh_pair:
show_cruise = CS.out.cruiseState.available and (not kona_handoff or CC.enabled)
support_current = (CS.ccnc_1b5_ts_ns > 0 and CS.ccnc_1b5_ts_ns <= now_nanos and support_current = (CS.ccnc_1b5_ts_ns > 0 and CS.ccnc_1b5_ts_ns <= now_nanos and
abs(CS.ccnc_1b5_ts_ns - pair_ts) <= 50_000_000) abs(CS.ccnc_1b5_ts_ns - pair_ts) <= 50_000_000)
can_sends.extend(hyundaicanfd.create_ccnc(self.packer, self.CAN, self.CP.openpilotLongitudinalControl, can_sends.extend(hyundaicanfd.create_ccnc(self.packer, self.CAN, self.CP.openpilotLongitudinalControl,
CC.enabled, hud_control, CC.leftBlinker, CC.rightBlinker, CC.enabled, hud_control, CC.leftBlinker, CC.rightBlinker,
CS.ccnc_161.copy(), CS.ccnc_162.copy(), CS.ccnc_1b5 if support_current else None, CS.ccnc_161.copy(), CS.ccnc_162.copy(), CS.ccnc_1b5 if support_current else None,
CS.is_metric, CS.out, show_cruise, CC.latActive, CS.is_metric, CS.out, show_cruise, show_ccnc_lateral,
owned_lfa_status=(stock_ccnc_owned if self.ccnc_fault_ownership_required else None), owned_lfa_status=stock_ccnc_owned if kona_handoff or self.ccnc_fault_ownership_required else None,
owned_cruise_status=kona_handoff)) owned_cruise_status=kona_handoff))
self.last_ccnc_161_ts_ns = CS.ccnc_161_ts_ns self.last_ccnc_161_ts_ns = CS.ccnc_161_ts_ns
self.last_ccnc_162_ts_ns = CS.ccnc_162_ts_ns self.last_ccnc_162_ts_ns = CS.ccnc_162_ts_ns
@@ -643,7 +640,8 @@ class CarController(CarControllerBase):
cluster_source = getattr(CS, "stock_cluster_status", None) cluster_source = getattr(CS, "stock_cluster_status", None)
stock_cluster = cluster_source.current(clock_boot_ns()) if cluster_source is not None else None stock_cluster = cluster_source.current(clock_boot_ns()) if cluster_source is not None else None
can_sends.append(hyundaicanfd.create_lfahda_cluster(self.packer, self.CAN, CC.enabled, lfa_icon=canfd_lfa_icon, can_sends.append(hyundaicanfd.create_lfahda_cluster(self.packer, self.CAN, CC.enabled, lfa_icon=canfd_lfa_icon,
stock_cluster=stock_cluster, owned_lfa_status=stock_popup_owned)) stock_cluster=stock_cluster, owned_lfa_status=stock_popup_owned,
legacy_lane_display=sportage_legacy_display))
# blinkers # blinkers
if lka_steering and self.CP.flags & HyundaiFlags.CANFD_ENABLE_BLINKERS: if lka_steering and self.CP.flags & HyundaiFlags.CANFD_ENABLE_BLINKERS:
@@ -696,11 +694,11 @@ class CarController(CarControllerBase):
lead = (self.torque_ev_lead_inputs.update(CS.torque_ev_camera_lead, hud_control.leadVisible, now_nanos) lead = (self.torque_ev_lead_inputs.update(CS.torque_ev_camera_lead, hud_control.leadVisible, now_nanos)
if self.torque_ev_lead_inputs is not None else if self.torque_ev_lead_inputs is not None else
fallback_lead(CS.torque_ev_camera_lead, hud_control.leadVisible, self.torque_ev_floor_boot_ns)) fallback_lead(CS.torque_ev_camera_lead, hud_control.leadVisible, self.torque_ev_floor_boot_ns))
acc_options = torque_ev_scc_options(CS.out.cruiseState.available and (not kona_handoff or CC.enabled), acc_options = torque_ev_scc_options(show_cruise,
CC.actuators.longControlState, lead) CC.actuators.longControlState, lead)
if (kona_handoff and CC.longActive and not CC.cruiseControl.override and stopping and if (kona_handoff and CC.longActive and not CC.cruiseControl.override and stopping and
not (CS.out.standstill or CS.out.brakePressed or CS.out.gasPressed or hud_control.leadVisible or lead.visible) and not (CS.out.standstill or CS.out.brakePressed or CS.out.gasPressed or hud_control.leadVisible or lead.visible) and
0.0 < CS.out.vEgo < 3.0 and self.CP.stopAccel < accel < 0.0 and accel >= self.accel_last - 0.02): 0.0 < CS.out.vEgo < 3.0 and self.CP.stopAccel - 0.02 <= accel < 0.0 and accel >= self.accel_last - 0.02):
acc_options["jerk_lower"] = 1.2 acc_options["jerk_lower"] = 1.2
elif is_gv70(self.CP): elif is_gv70(self.CP):
request = scc_request(CC.enabled, CC.cruiseControl.override, stopping, accel, self.accel_last) request = scc_request(CC.enabled, CC.cruiseControl.override, stopping, accel, self.accel_last)
+4 -1
View File
@@ -64,7 +64,10 @@ class CarState(CarStateBase):
def __init__(self, CP): def __init__(self, CP):
super().__init__(CP) super().__init__(CP)
preserve_status = preserves_stock_lfa(CP) preserve_status = preserves_stock_lfa(CP)
self.stock_lfa_status = CANFDLfaStatus(CanBus(CP).CAM) if preserve_status else None sportage = CP.carFingerprint == CAR.KIA_SPORTAGE_5TH_GEN
self.stock_lfa_status = (CANFDLfaStatus(CanBus(CP).CAM, eps_response_margin_ns=10_000_000 if sportage else 0,
track_camera_release=sportage and bool(CP.flags & HyundaiFlags.CANFD_CAMERA_SCC))
if preserve_status else None)
self.stock_cluster_status = CANFDClusterStatus(CanBus(CP).CAM) if preserve_status else None self.stock_cluster_status = CANFDClusterStatus(CanBus(CP).CAM) if preserve_status else None
self.stock_lkas_damping = (CANFDLkasDamping(CanBus(CP).CAM, bool(CP.flags & HyundaiFlags.CANFD_LKA_STEER_MSG_ALT)) self.stock_lkas_damping = (CANFDLkasDamping(CanBus(CP).CAM, bool(CP.flags & HyundaiFlags.CANFD_LKA_STEER_MSG_ALT))
if preserves_stock_lkas_damping(CP) else None) if preserves_stock_lkas_damping(CP) else None)
@@ -45,7 +45,8 @@ LFA_FAULT_MASK = bytes.fromhex("00000000c001c0f00000000000000000")
def create_steering_messages(packer, CP, CAN, enabled, lat_active, apply_torque, *, stock_lfa=None, stock_lfa_faults=None, def create_steering_messages(packer, CP, CAN, enabled, lat_active, apply_torque, *, stock_lfa=None, stock_lfa_faults=None,
stock_lkas_damping=None, stock_lfa_owned_status=False, lfa_counter=None): stock_lkas_damping=None, stock_lfa_owned_status=False,
legacy_lane_display=False):
values = { values = {
"LKA_OptUsmSta": 2, "LKA_OptUsmSta": 2,
"LKA_SysIndReq": 2 if enabled else 1, "LKA_SysIndReq": 2 if enabled else 1,
@@ -73,16 +74,15 @@ def create_steering_messages(packer, CP, CAN, enabled, lat_active, apply_torque,
lkas_values = {**values, "Damping_Gain": damping} lkas_values = {**values, "Damping_Gain": damping}
ret.append(packer.make_can_msg(lkas_msg, CAN.ACAN, lkas_values)) ret.append(packer.make_can_msg(lkas_msg, CAN.ACAN, lkas_values))
else: else:
if lfa_counter is not None:
values["COUNTER"] = lfa_counter
message = packer.make_can_msg("LFA", CAN.ECAN, values) message = packer.make_can_msg("LFA", CAN.ECAN, values)
source = stock_lfa if stock_lfa is not None else stock_lfa_faults source = stock_lfa if stock_lfa is not None else stock_lfa_faults
if source is not None: if source is not None:
# Stale samples retain only faults; a fresh healthy camera sample clears them. # Stale samples retain only faults; a fresh healthy camera sample clears them.
mask = LFA_CONTROL_MASK if stock_lfa is not None else bytes(value ^ 0xFF for value in LFA_FAULT_MASK) mask = LFA_CONTROL_MASK if stock_lfa is not None else bytes(value ^ 0xFF for value in LFA_FAULT_MASK)
stock_indication = (source[4] >> 6) | ((source[5] & 1) << 2) stock_indication = (source[4] >> 6) | ((source[5] & 1) << 2)
owned_status = (stock_lfa is not None and stock_lfa_owned_status and stock_indication == 4 and owned_status = (stock_lfa is not None and stock_indication == 4 and source[7] >> 4 == 15 and
source[7] >> 4 == 15 and not source[6] & 0xF0) not source[6] & 0xC0 and
(legacy_lane_display or (stock_lfa_owned_status and not source[6] & 0x30)))
if owned_status: if owned_status:
mask = bytearray(mask) mask = bytearray(mask)
mask[7] |= 0xF0 mask[7] |= 0xF0
@@ -228,7 +228,7 @@ def create_acc_cancel(packer, CP, CAN, cruise_info_copy):
CLUSTER_CONTROL_MASK = bytes.fromhex("ffffff80008001000000000000000000") CLUSTER_CONTROL_MASK = bytes.fromhex("ffffff80008001000000000000000000")
def create_lfahda_cluster(packer, CAN, enabled, *, lfa_icon=None, stock_cluster=None, owned_lfa_status=False): def create_lfahda_cluster(packer, CAN, enabled, *, lfa_icon=None, stock_cluster=None, owned_lfa_status=False, legacy_lane_display=False):
values = { values = {
"HDA_ICON": 1 if enabled else 0, "HDA_ICON": 1 if enabled else 0,
"LFA_ICON": (2 if enabled else 0) if lfa_icon is None else lfa_icon, "LFA_ICON": (2 if enabled else 0) if lfa_icon is None else lfa_icon,
@@ -237,7 +237,8 @@ def create_lfahda_cluster(packer, CAN, enabled, *, lfa_icon=None, stock_cluster=
if stock_cluster is not None: if stock_cluster is not None:
data = bytearray((old & ~owned) | (new & owned) data = bytearray((old & ~owned) | (new & owned)
for old, new, owned in zip(stock_cluster, message[1], CLUSTER_CONTROL_MASK, strict=True)) for old, new, owned in zip(stock_cluster, message[1], CLUSTER_CONTROL_MASK, strict=True))
if owned_lfa_status and stock_cluster[4] & 7 == 3: popup = stock_cluster[4] & 7
if (owned_lfa_status and popup == 3) or (legacy_lane_display and popup in (3, 5, 6)):
data[4] &= 0xF8 data[4] &= 0xF8
data[:2] = hkg_can_fd_checksum(message[0], None, data).to_bytes(2, "little") data[:2] = hkg_can_fd_checksum(message[0], None, data).to_bytes(2, "little")
message = (message[0], bytes(data), message[2]) message = (message[0], bytes(data), message[2])
@@ -141,6 +141,9 @@ class CarInterface(CarInterfaceBase):
ret.brand = "hyundai" ret.brand = "hyundai"
if candidate == CAR.HYUNDAI_I30_2026: if candidate == CAR.HYUNDAI_I30_2026:
# Controls may construct a PID for this profile. Keep it inert with valid gains.
ret.lateralTuning.pid.kpBP = ret.lateralTuning.pid.kiBP = [0.0]
ret.lateralTuning.pid.kpV = ret.lateralTuning.pid.kiV = [0.0]
ret.dashcamOnly = True ret.dashcamOnly = True
ret.radarUnavailable = True ret.radarUnavailable = True
ret.safetyConfigs = [get_safety_config(structs.CarParams.SafetyModel.noOutput)] ret.safetyConfigs = [get_safety_config(structs.CarParams.SafetyModel.noOutput)]
@@ -1009,3 +1009,119 @@ def test_ccnc_fault_handover_preserves_obstruction_and_unknown_codes(fault, owne
for field in ('COUNTER', 'FAULT_FCA', 'FAULT_FSS', 'FAULT_ESS', 'FAULT_SCC'): for field in ('COUNTER', 'FAULT_FCA', 'FAULT_FSS', 'FAULT_ESS', 'FAULT_SCC'):
assert decoder.vl['CCNC_0x162'][field] == original[field] assert decoder.vl['CCNC_0x162'][field] == original[field]
assert decoder.vl['CCNC_0x161']['LFA_ICON'] == decoder.vl['CCNC_0x161']['CENTERLINE'] == 0 assert decoder.vl['CCNC_0x161']['LFA_ICON'] == decoder.vl['CCNC_0x161']['CENTERLINE'] == 0
@pytest.mark.parametrize('alpha', (False, True))
@pytest.mark.parametrize('vehicle,case,owned', [
(CAR.KIA_SPORTAGE_5TH_GEN, 'recorded', True),
(CAR.KIA_SPORTAGE_5TH_GEN, 'late', False),
(CAR.KIA_SPORTAGE_5TH_GEN, 'idle', False),
(CAR.KIA_SPORTAGE_5TH_GEN, 'eps_fault', False),
(CAR.KIA_SPORTAGE_5TH_GEN, 'camera_fault', False),
(CAR.KIA_NIRO_EV_2ND_GEN, 'recorded', False),
])
def test_sportage_display_ownership_accepts_one_camera_frame_of_timing_skew(vehicle, case, owned, alpha, clock):
cp = params(vehicle, alpha=alpha, alternate=True)
ci = CarInterface(cp)
ci.update([])
packer = CANPacker(DBC[vehicle][Bus.pt])
bus = ci.CC.CAN
command = structs.CarControl.new_message()
observed = {}
for tick in range(28):
clock[0] = 30_000_000_000 + tick * 10_000_000 + (310_000 if tick >= 19 else 0)
command.enabled = command.latActive = tick >= 2 and case != 'idle'
warning = tick >= (21 if case == 'late' else 19)
stock = template(packer, bus.CAM, tick, warning=15 if warning else 0, fault=int(warning and case == 'camera_fault'))
frames = [frame for frame in physical_frames(ci, packer, tick, stock) if frame[0] != 0xEA]
frames.append(packer.make_can_msg('MDPS', bus.ECAN, {'COUNTER': tick,
'MDPS_LkaToiActvSta': int(tick >= 4 and case != 'idle'), 'MDPS_LkaFailSta': int(warning and case == 'eps_fault')}))
if tick % 5 == 0:
frame = packer.make_can_msg('LFAHDA_CLUSTER', bus.CAM, {'COUNTER': tick // 5, 'NEW_SIGNAL_1': 3 if warning else 0})
frames.append(frame)
assert ci.update([(clock[0], frames)]).canValid
_, packets = ci.apply(command.as_reader(), clock[0])
if tick >= 25:
observed.update((address, body) for address, body, src in packets if src == bus.ECAN and address in (0x12A, 0x1E0))
assert observed[0x12A][7] >> 4 == (0 if owned else 15)
assert observed[0x12A][6] >> 6 == int(case == 'camera_fault')
assert observed[0x1E0][4] & 7 == (0 if owned else 3)
@pytest.mark.parametrize('alpha', (False, True))
@pytest.mark.parametrize('case', ('recorded', 'late', 'no_release', 'nonzero_release', 'eps_fault', 'camera_fault', 'crc_gap'))
def test_sportage_recovers_display_after_camera_yields_steering(alpha, case, clock):
cp = params(CAR.KIA_SPORTAGE_5TH_GEN, alpha=alpha, alternate=True)
ci = CarInterface(cp)
ci.update([])
packer = CANPacker(DBC[cp.carFingerprint][Bus.pt])
bus = ci.CC.CAN
command = structs.CarControl.new_message()
output = {}
for tick in range(41):
clock[0] = 40_000_000_000 + tick * 10_000_000
command.latActive = tick >= 2
warning = tick >= 18
release = 23 if case not in ('late', 'no_release') else 37 if case == 'late' else 42
factory_request = 16 <= tick < release
factory_torque = 4 if factory_request or (tick >= release and case == 'nonzero_release') else 0
stock = packer.make_can_msg('LFA', bus.CAM, {
'COUNTER': tick, 'LKA_SysIndReq': 4 if warning else 1, 'LKA_SysWrn': 15 if warning else 0,
'ActToiSta': int(factory_request), 'StrTqReqVal': factory_torque, 'ToiFltSta': int(warning and case == 'camera_fault'),
})
if case == 'crc_gap' and tick == 20:
bad = bytes([stock[1][0] ^ 1]) + stock[1][1:]
stock = stock[0], bad, stock[2]
frames = [frame for frame in physical_frames(ci, packer, tick, stock) if frame[0] != 0xEA]
frames.append(packer.make_can_msg('MDPS', bus.ECAN, {'COUNTER': tick, 'MDPS_LkaToiActvSta': int(tick >= 4),
'MDPS_LkaFailSta': int(warning and case == 'eps_fault')}))
if tick % 5 == 0:
frames.append(packer.make_can_msg('LFAHDA_CLUSTER', bus.CAM, {'COUNTER': tick // 5, 'NEW_SIGNAL_1': 3 if warning else 0}))
assert ci.update([(clock[0], frames)]).canValid
_, packets = ci.apply(command.as_reader(), clock[0])
for addr, data, src in packets:
if src != bus.ECAN:
continue
if addr == 0x12A:
assert data[6] >> 4 & 3 == int(command.latActive)
if warning and tick < release:
assert data[7] >> 4 == 15
if addr in (0x12A, 0x1E0):
output[addr] = data
expected = case == 'recorded'
assert output[0x12A][7] >> 4 == (0 if expected else 15)
assert output[0x1E0][4] & 7 == (0 if expected else 3)
@pytest.mark.parametrize('popup', (3, 5, 6, 7))
@pytest.mark.parametrize('case', ('recorded', 'stock', 'eps_failure', 'camera_failure', 'unknown_warning', 'stale_camera'))
def test_sportage_legacy_lane_display_is_scoped_and_fault_aware(popup, case, clock):
cp = params(CAR.KIA_SPORTAGE_5TH_GEN, alpha=case != 'stock', alternate=True)
cp.safetyConfigs[0].safetyParam = 0x828 if case == 'stock' else 0x82C
cp.alternativeExperience = 32
ci = CarInterface(cp)
ci.update([])
packer = CANPacker(DBC[cp.carFingerprint][Bus.pt])
bus = ci.CC.CAN
command = structs.CarControl.new_message()
output = {}
for tick in range(16):
clock[0] = 40_000_000_000 + tick * 10_000_000
warning = 9 if case == 'unknown_warning' else 15
stock = packer.make_can_msg('LFA', bus.CAM, {
'COUNTER': tick, 'LKA_SysIndReq': 4, 'LKA_SysWrn': warning, 'ActToiSta': 1, 'StrTqReqVal': 17,
'ToiFltSta': int(case == 'camera_failure'),
})
frames = [frame for frame in physical_frames(ci, packer, tick, stock) if frame[0] != 0xEA]
if case == 'stale_camera' and tick > 3:
frames = [frame for frame in frames if frame[0] != 0x12A]
frames.append(packer.make_can_msg('MDPS', bus.ECAN, {'COUNTER': tick, 'MDPS_LkaFailSta': int(case == 'eps_failure')}))
if tick % 5 == 0:
frames.append(packer.make_can_msg('LFAHDA_CLUSTER', bus.CAM, {'COUNTER': tick // 5, 'NEW_SIGNAL_1': popup}))
assert ci.update([(clock[0], frames)]).canValid
_, packets = ci.apply(command.as_reader(), clock[0])
output.update((addr, data) for addr, data, src in packets if src == bus.ECAN and addr in (0x12A, 0x1E0))
assert output[0x12A][7] >> 4 == (0 if case == 'recorded' else warning)
assert output[0x12A][6] >> 6 == int(case == 'camera_failure')
assert (int.from_bytes(output[0x12A], 'little') >> 41) & 0xFFF == 1024
assert output[0x1E0][4] & 7 == (0 if case == 'recorded' and popup != 7 else popup)
@@ -387,8 +387,21 @@ class TestHyundaiFingerprint(unittest.TestCase):
fingerprint = gen_empty_fingerprint() fingerprint = gen_empty_fingerprint()
for car_model in CAR: for car_model in CAR:
CP = CarInterface.get_params(car_model, fingerprint, [], False, False, False) CP = CarInterface.get_params(car_model, fingerprint, [], False, False, False)
if CP.safetyConfigs[-1].safetyModel == CarParams.SafetyModel.noOutput:
assert CP.dashcamOnly
continue
assert bool(CP.flags & HyundaiFlags.ALT_LIMITS) == bool(CP.safetyConfigs[-1].safetyParam & HyundaiSafetyFlags.ALT_LIMITS) assert bool(CP.flags & HyundaiFlags.ALT_LIMITS) == bool(CP.safetyConfigs[-1].safetyParam & HyundaiSafetyFlags.ALT_LIMITS)
def test_i30_2026_remains_dashcam_only(self):
for alpha in (False, True):
for release in (False, True):
with self.subTest(alpha=alpha, release=release):
cp = CarInterface.get_params(CAR.HYUNDAI_I30_2026, gen_empty_fingerprint(), [], alpha, release, False)
assert cp.dashcamOnly and not cp.openpilotLongitudinalControl
assert len(cp.safetyConfigs) == 1 and cp.safetyConfigs[0].safetyModel == CarParams.SafetyModel.noOutput
assert cp.lateralTuning.pid.kf == 0
assert list(cp.lateralTuning.pid.kpV) == list(cp.lateralTuning.pid.kiV) == [0.0]
def test_can_features(self): def test_can_features(self):
for car_model in CAR: for car_model in CAR:
flags = car_model.config.flags flags = car_model.config.flags
@@ -430,7 +443,8 @@ class TestHyundaiFingerprint(unittest.TestCase):
if b"-" not in code: if b"-" not in code:
continue continue
part = code.split(b"-")[1] part = code.split(b"-")[1]
assert not part.startswith(b'CW'), "Car has bad part number" verified_shared_camera = car_model == CAR.HYUNDAI_TUCSON_4TH_GEN and code == b'NX4-CW010'
assert verified_shared_camera or not part.startswith(b'CW'), "Car has bad part number"
def test_correct_ecu_response_database(self): def test_correct_ecu_response_database(self):
""" """
@@ -9,7 +9,7 @@ from unittest.mock import Mock, patch
from openpilot.starpilot.vehicle_startup import VehicleStartupOwner from openpilot.starpilot.vehicle_startup import VehicleStartupOwner
from opendbc.car import gen_empty_fingerprint from opendbc.car import gen_empty_fingerprint, structs
from opendbc.car.can_definitions import CanData from opendbc.car.can_definitions import CanData
from opendbc.car.car_helpers import get_car from opendbc.car.car_helpers import get_car
from opendbc.car.hyundai.ioniq6_handoff import (HandoffOutcome, HandoffResult, ObservingCanRecv, build_ioniq6_hda2_long_candidate, from opendbc.car.hyundai.ioniq6_handoff import (HandoffOutcome, HandoffResult, ObservingCanRecv, build_ioniq6_hda2_long_candidate,
@@ -686,7 +686,7 @@ class TestIoniq6PrepublicationHandoff(unittest.TestCase):
card = self.ready_card(ioniq_selected=True) card = self.ready_card(ioniq_selected=True)
cs = SimpleNamespace(canValid=True, canTimeout=False) cs = SimpleNamespace(canValid=True, canTimeout=False)
cc = object() cc = structs.CarControl().as_reader()
confirmed = HandoffResult(HandoffOutcome.CONFIRMED, 'confirmed') confirmed = HandoffResult(HandoffOutcome.CONFIRMED, 'confirmed')
with (patch.object(card_module, 'confirm_ioniq6_prepared_takeover', return_value=confirmed) as takeover, with (patch.object(card_module, 'confirm_ioniq6_prepared_takeover', return_value=confirmed) as takeover,
patch.object(card_module.cloudlog, 'event') as logged): patch.object(card_module.cloudlog, 'event') as logged):
@@ -737,7 +737,7 @@ class TestIoniq6PrepublicationHandoff(unittest.TestCase):
card = self.ready_card(ioniq_selected=True) card = self.ready_card(ioniq_selected=True)
card.sm.valid['carControl'] = True card.sm.valid['carControl'] = True
cs = SimpleNamespace(canValid=True, canTimeout=False) cs = SimpleNamespace(canValid=True, canTimeout=False)
cc = object() cc = structs.CarControl().as_reader()
failed = HandoffResult(HandoffOutcome.UNAVAILABLE, 'restore unverified') failed = HandoffResult(HandoffOutcome.UNAVAILABLE, 'restore unverified')
with (patch.object(card_module, 'confirm_ioniq6_prepared_takeover', return_value=failed) as takeover, with (patch.object(card_module, 'confirm_ioniq6_prepared_takeover', return_value=failed) as takeover,
patch.object(card_module.cloudlog, 'event') as logged): patch.object(card_module.cloudlog, 'event') as logged):
@@ -760,7 +760,7 @@ class TestIoniq6PrepublicationHandoff(unittest.TestCase):
card = self.ready_card(ioniq_selected=True) card = self.ready_card(ioniq_selected=True)
card.sm.valid['carControl'] = True card.sm.valid['carControl'] = True
cs = SimpleNamespace(canValid=True, canTimeout=False) cs = SimpleNamespace(canValid=True, canTimeout=False)
cc = object() cc = structs.CarControl().as_reader()
confirmed = HandoffResult(HandoffOutcome.CONFIRMED, 'confirmed') confirmed = HandoffResult(HandoffOutcome.CONFIRMED, 'confirmed')
with patch.object(card_module, 'confirm_ioniq6_prepared_takeover', return_value=confirmed) as takeover: with patch.object(card_module, 'confirm_ioniq6_prepared_takeover', return_value=confirmed) as takeover:
for mutation in ( for mutation in (
@@ -883,7 +883,7 @@ class TestIoniq6PrepublicationHandoff(unittest.TestCase):
card = self.ready_card(ioniq_selected=True) card = self.ready_card(ioniq_selected=True)
card.sm.valid['carControl'] = True card.sm.valid['carControl'] = True
cs = SimpleNamespace(canValid=True, canTimeout=False) cs = SimpleNamespace(canValid=True, canTimeout=False)
cc = object() cc = structs.CarControl().as_reader()
clock = [100.0] clock = [100.0]
waiting = HandoffResult(HandoffOutcome.NOT_READY, 'preflight_scc_period') waiting = HandoffResult(HandoffOutcome.NOT_READY, 'preflight_scc_period')
confirmed = HandoffResult(HandoffOutcome.CONFIRMED, 'confirmed') confirmed = HandoffResult(HandoffOutcome.CONFIRMED, 'confirmed')
@@ -911,7 +911,7 @@ class TestIoniq6PrepublicationHandoff(unittest.TestCase):
def test_generic_ecu_init_waits_for_valid_can_and_live_control_once(self): def test_generic_ecu_init_waits_for_valid_can_and_live_control_once(self):
card = self.ready_card(ioniq_selected=False) card = self.ready_card(ioniq_selected=False)
cs = SimpleNamespace(canValid=True, canTimeout=False) cs = SimpleNamespace(canValid=True, canTimeout=False)
cc = object() cc = structs.CarControl().as_reader()
for _ in range(20): for _ in range(20):
card.controls_update(cs, cc) card.controls_update(cs, cc)
card.CI.init.assert_not_called() card.CI.init.assert_not_called()
@@ -203,7 +203,7 @@ def test_wheel_choices_keep_aol_with_either_longitudinal_owner(car, alternate, a
assert 'Toggle AOL' in feature.choices('MainCruiseButtonControl') assert 'Toggle AOL' in feature.choices('MainCruiseButtonControl')
def test_idle_handoff_omits_only_kona_steering_packet(): def test_kona_steering_has_its_own_continuous_counter():
reference_cp = kona_params(CARS[0]) reference_cp = kona_params(CARS[0])
handoff_cp = kona_params(CARS[0]) handoff_cp = kona_params(CARS[0])
for cp, word in ((reference_cp, 0x0C0C), (handoff_cp, 0x1C0C)): for cp, word in ((reference_cp, 0x0C0C), (handoff_cp, 0x1C0C)):
@@ -212,11 +212,11 @@ def test_idle_handoff_omits_only_kona_steering_packet():
reference, candidate = CarInterface(reference_cp), CarInterface(handoff_cp) reference, candidate = CarInterface(reference_cp), CarInterface(handoff_cp)
source = Mock() source = Mock()
source.owns_display_status.return_value = False source.owns_display_status.return_value = False
source.last_fault.return_value = None
candidate.CS.stock_lfa_status = source candidate.CS.stock_lfa_status = source
states = ((False, False, 10), (True, True, 11), (False, True, 11), (True, False, 12), states = ((False, False, 10), (True, True, 11), (False, True, 11), (True, False, 12),
(True, True, None), (False, False, 13), (True, True, 14)) (True, True, None), (False, False, 13), (True, True, 14))
expected_counters = (None, 11, None, 12, None, None, 14) for expected, (enabled, lateral, camera_counter) in enumerate(states):
for (enabled, lateral, camera_counter), expected in zip(states, expected_counters, strict=True):
if camera_counter is None: if camera_counter is None:
source.current.return_value = None source.current.return_value = None
else: else:
@@ -226,7 +226,7 @@ def test_idle_handoff_omits_only_kona_steering_packet():
_, after = candidate.apply(ctrl, 1_000_000_000) _, after = candidate.apply(ctrl, 1_000_000_000)
assert [frame for frame in after if frame[0] != 0x12A] == [frame for frame in before if frame[0] != 0x12A] assert [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 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]) assert [data[2] for addr, data, _ in after if addr == 0x12A] == [expected]
@pytest.mark.parametrize('panda_type,faults,expected', [('cuatro', [], 0x1C0C), ('redPanda', [], 0x0C0C), ('cuatro', ['fault'], 0x0C0C)]) @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): def test_kona_factory_handoff_is_limited_to_healthy_internal_c4(panda_type, faults, expected):
@@ -238,14 +238,16 @@ def test_kona_factory_handoff_is_limited_to_healthy_internal_c4(panda_type, faul
assert cp.safetyConfigs[0].safetyParam == expected assert cp.safetyConfigs[0].safetyParam == expected
@pytest.mark.parametrize('handoff,enabled,hud_mode', ((True, False, 0), (True, True, 2), (False, False, 1))) @pytest.mark.parametrize('handoff,enabled,set_speed,hud_mode', (
def test_kona_handoff_cruise_main_display_follows_star_long_engagement(handoff, enabled, hud_mode): (True, False, 255., 0), (True, False, 40., 1), (True, True, 40., 2), (False, False, 40., 1),
))
def test_kona_handoff_cruise_main_display_follows_star_long_engagement(handoff, enabled, set_speed, hud_mode):
from opendbc.can import CANParser from opendbc.can import CANParser
cp = kona_params(CARS[0]) cp = kona_params(CARS[0])
cp.safetyConfigs[0].safetyParam = 0x1C0C if handoff else 0x0C0C cp.safetyConfigs[0].safetyParam = 0x1C0C if handoff else 0x0C0C
cp.alternativeExperience = 32 cp.alternativeExperience = 32
ci = CarInterface(cp) ci = CarInterface(cp)
ci.CS.out = structs.CarState(cruiseState={'available': True}, vCruiseCluster=40.).as_reader() ci.CS.out = structs.CarState(cruiseState={'available': True}, vCruiseCluster=set_speed).as_reader()
for frame in range(5): for frame in range(5):
ci.apply(structs.CarControl().as_reader(), 950_000_000 + frame * 10_000_000) ci.apply(structs.CarControl().as_reader(), 950_000_000 + frame * 10_000_000)
ci.CS.ccnc_161_ts_ns = ci.CS.ccnc_162_ts_ns = 1_000_000_000 ci.CS.ccnc_161_ts_ns = ci.CS.ccnc_162_ts_ns = 1_000_000_000
@@ -258,16 +260,20 @@ def test_kona_handoff_cruise_main_display_follows_star_long_engagement(handoff,
_, scc_packets = ci.apply(command.as_reader(), 1_010_000_000) _, scc_packets = ci.apply(command.as_reader(), 1_010_000_000)
assert {0x161, 0x162} <= parser.update((1_000_000_000, packets)) assert {0x161, 0x162} <= parser.update((1_000_000_000, packets))
assert 0x1A0 in parser.update((1_010_000_000, scc_packets)) assert 0x1A0 in parser.update((1_010_000_000, scc_packets))
assert parser.vl['SCC_CONTROL']['MainMode_ACC'] == int(not handoff or enabled) assert parser.vl['SCC_CONTROL']['MainMode_ACC'] == int(hud_mode != 0)
assert parser.vl['SCC_CONTROL']['ACCMode'] == int(enabled)
display = parser.vl['CCNC_0x161'] display = parser.vl['CCNC_0x161']
assert display['SETSPEED_HUD'] == hud_mode assert display['SETSPEED_HUD'] == hud_mode
assert display['LFA_ICON'] == 2 assert display['LFA_ICON'] == (0 if handoff else 2)
if handoff: if handoff:
assert display['SETSPEED'] == hud_mode assert display['SETSPEED'] == hud_mode
if hud_mode == 0: if hud_mode == 0:
assert display['DISTANCE'] == 0 assert display['DISTANCE'] == 0
assert display['SETSPEED_SPEED'] == 255 assert display['SETSPEED_SPEED'] == 255
assert display['DISTANCE_SPACING'] == 0 assert display['DISTANCE_SPACING'] == 0
elif handoff and not enabled:
assert display['SETSPEED_SPEED'] == round(set_speed * (1. if ci.CS.is_metric else 0.621371))
assert display['DISTANCE_SPACING'] == 3
assert parser.vl['CCNC_0x162']['FAULT_LSS'] == 2 assert parser.vl['CCNC_0x162']['FAULT_LSS'] == 2
assert parser.vl['CCNC_0x162']['FAULT_FCA'] == 1 assert parser.vl['CCNC_0x162']['FAULT_FCA'] == 1
@@ -278,7 +284,10 @@ def test_kona_handoff_cruise_main_display_follows_star_long_engagement(handoff,
(2.4, -1.13, -1.12, False, False, 0x1C0C, 1.2), (2.4, -1.13, -1.12, False, False, 0x1C0C, 1.2),
(1.2, -1.80, -1.78, False, False, 0x1C0C, 1.2), (1.2, -1.80, -1.78, False, False, 0x1C0C, 1.2),
(3.0, -0.60, -0.59, False, False, 0x1C0C, 5.0), (3.0, -0.60, -0.59, False, False, 0x1C0C, 5.0),
(0.3, -2.00, -1.99, False, False, 0x1C0C, 5.0), (0.3, -2.00, -1.99, False, False, 0x1C0C, 1.2),
(1.75, -2.01, -2.006, False, False, 0x1C0C, 1.2),
(1.75, -2.01, -1.80, False, False, 0x1C0C, 5.0),
(1.75, -2.10, -2.10, False, False, 0x1C0C, 5.0),
(0.3, -0.45, -0.20, False, False, 0x1C0C, 5.0), (0.3, -0.45, -0.20, False, False, 0x1C0C, 5.0),
(0.1, -0.27, -0.26, True, False, 0x1C0C, 5.0), (0.1, -0.27, -0.26, True, False, 0x1C0C, 5.0),
(0.3, -0.27, -0.26, False, True, 0x1C0C, 5.0), (0.3, -0.27, -0.26, False, True, 0x1C0C, 5.0),
@@ -304,3 +313,33 @@ def test_kona_final_braking_jerk(speed, accel, previous, standstill, lead, word,
assert values['aReqRaw'] == pytest.approx(accel) assert values['aReqRaw'] == pytest.approx(accel)
assert values['ACCMode'] == values['StopReq'] == 1 assert values['ACCMode'] == values['StopReq'] == 1
assert values['JerkLowerLimit'] == pytest.approx(cap) assert values['JerkLowerLimit'] == pytest.approx(cap)
@pytest.mark.parametrize('eps,age_ms,expected', [(0, 10, 0), (1, 10, 2), (1, 51, 0), (2, 10, 0)])
def test_kona_handoff_steering_icon_needs_current_eps_feedback(eps, age_ms, expected, monkeypatch):
import time
from opendbc.can import CANParser
from opendbc.car.hyundai import carcontroller
cp = kona_params(CARS[0])
cp.safetyConfigs[0].safetyParam = 0x1C0C
cp.alternativeExperience = 32
ci = CarInterface(cp)
ci.CS.out = structs.CarState(canValid=True, cruiseState={'available': True}).as_reader()
now = 2_000_000_000
monkeypatch.setattr(time, 'CLOCK_BOOTTIME', time.CLOCK_MONOTONIC, raising=False)
monkeypatch.setattr(time, 'clock_gettime_ns', lambda _: now)
monkeypatch.setattr(carcontroller, 'clock_boot_ns', lambda: now)
for tick in range(5):
ci.apply(structs.CarControl().as_reader(), now-(5-tick)*10_000_000)
ci.CS.ccnc_161_ts_ns = ci.CS.ccnc_162_ts_ns = now
ci.CS.ccnc_161 = {}
ci.CS.ccnc_162 = {'FAULT_LSS': 2}
mdps = ci.CC.packer.make_can_msg('MDPS', 0, {'MDPS_LkaToiActvSta': eps})
ci.CS.stock_lfa_status.update([(now - age_ms * 1_000_000, [mdps])])
_, packets = ci.apply(structs.CarControl(latActive=True).as_reader(), now)
parser = CANParser('hyundai_canfd_generated', [('CCNC_0x161', 0), ('CCNC_0x162', 0)], 0)
assert {0x161, 0x162} <= parser.update((now, packets))
assert parser.vl['CCNC_0x161']['LFA_ICON'] == expected
assert parser.vl['CCNC_0x162']['FAULT_LSS'] == 2
@@ -12,7 +12,7 @@ from opendbc.car.hyundai.ecu_startup import Outcome
from opendbc.car.hyundai.interface import CarInterface from opendbc.car.hyundai.interface import CarInterface
from opendbc.car.hyundai.ioniq6_handoff import TimestampedCanPacket from opendbc.car.hyundai.ioniq6_handoff import TimestampedCanPacket
from opendbc.car.hyundai.ordinary_classic_startup import CARS, OrdinaryClassicStartup from opendbc.car.hyundai.ordinary_classic_startup import CARS, OrdinaryClassicStartup
from opendbc.car.hyundai.values import HyundaiFlags from opendbc.car.hyundai.values import CAR, HyundaiFlags
from opendbc.safety.tests.test_hyundai import checksum from opendbc.safety.tests.test_hyundai import checksum
from opendbc.safety.tests.libsafety import libsafety_py from opendbc.safety.tests.libsafety import libsafety_py
from openpilot.cereal import messaging from openpilot.cereal import messaging
@@ -115,6 +115,11 @@ def test_actual_factory_rejection_restores_and_warms_exact_stock_before_publicat
expected.carFw = [] expected.carFw = []
expected.fingerprintSource = desired.fingerprintSource expected.fingerprintSource = desired.fingerprintSource
expected.fuzzyFingerprint = False expected.fuzzyFingerprint = False
if identity == CAR.HYUNDAI_I30_2026:
assert desired.dashcamOnly and expected.dashcamOnly
assert not desired.openpilotLongitudinalControl and not expected.openpilotLongitudinalControl
assert desired.safetyConfigs[0].safetyModel == expected.safetyConfigs[0].safetyModel == structs.CarParams.SafetyModel.noOutput
return
assert desired.openpilotLongitudinalControl and not expected.openpilotLongitudinalControl assert desired.openpilotLongitudinalControl and not expected.openpilotLongitudinalControl
identified = (identity, fingerprint, '0' * 17, [], desired.fingerprintSource, True) identified = (identity, fingerprint, '0' * 17, [], desired.fingerprintSource, True)
native.set_alternative_experience(0) native.set_alternative_experience(0)
+2 -1
View File
@@ -21,8 +21,9 @@ from opendbc.car.psa.values import CAR as PSA
from opendbc.car.mg.values import CAR as MG from opendbc.car.mg.values import CAR as MG
from opendbc.car.leapmotor.values import CAR as LEAPMOTOR from opendbc.car.leapmotor.values import CAR as LEAPMOTOR
# Configurations with source tests but no matching recorded route. # Configurations with source tests but no matching CI recording.
unrecorded_route_gaps = { unrecorded_route_gaps = {
HYUNDAI.HYUNDAI_I30_2026: "hyundai/tests/test_hyundai.py",
SUBARU.SUBARU_CROSSTREK_2018: "subaru/tests/test_supported_firmware.py", SUBARU.SUBARU_CROSSTREK_2018: "subaru/tests/test_supported_firmware.py",
GM.CHEVROLET_VOLT_CC: "gm/tests/test_volt_cc_gas.py", GM.CHEVROLET_VOLT_CC: "gm/tests/test_volt_cc_gas.py",
GM.CHEVROLET_MALIBU_HYBRID_CC: "gm/tests/test_ordinary_cc.py", GM.CHEVROLET_MALIBU_HYBRID_CC: "gm/tests/test_ordinary_cc.py",
@@ -4,6 +4,7 @@ from pathlib import Path
from opendbc.car.values import PLATFORMS from opendbc.car.values import PLATFORMS
from opendbc.car.tests.routes import non_tested_cars, routes, unrecorded_route_gaps 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.gm.values import CAR as GM
from opendbc.car.hyundai.values import CAR as HYUNDAI
from opendbc.car.subaru.values import CAR as SUBARU from opendbc.car.subaru.values import CAR as SUBARU
from opendbc.car.tesla.values import CAR as TESLA from opendbc.car.tesla.values import CAR as TESLA
from opendbc.car.toyota.values import CAR as TOYOTA from opendbc.car.toyota.values import CAR as TOYOTA
@@ -20,6 +21,7 @@ class TestRoutes(unittest.TestCase):
def test_explicit_unrecorded_configuration_gaps(self): def test_explicit_unrecorded_configuration_gaps(self):
self.assertEqual(set(unrecorded_route_gaps), { self.assertEqual(set(unrecorded_route_gaps), {
HYUNDAI.HYUNDAI_I30_2026,
GM.CHEVROLET_VOLT_CC, GM.CHEVROLET_MALIBU_HYBRID_CC, TOYOTA.TOYOTA_PRIUS_RETROFIT, TESLA.TESLA_MODEL_S_HW1, GM.CHEVROLET_VOLT_CC, GM.CHEVROLET_MALIBU_HYBRID_CC, TOYOTA.TOYOTA_PRIUS_RETROFIT, TESLA.TESLA_MODEL_S_HW1,
SUBARU.SUBARU_CROSSTREK_2018, VOLVO.VOLVO_XC40_RECHARGE, VOLVO.VOLVO_S60_RECHARGE, VOLVO.POLESTAR_2, VOLVO.VOLVO_V60, SUBARU.SUBARU_CROSSTREK_2018, VOLVO.VOLVO_XC40_RECHARGE, VOLVO.VOLVO_S60_RECHARGE, VOLVO.POLESTAR_2, VOLVO.VOLVO_V60,
}) })
@@ -89,7 +89,9 @@ class TestToyotaAutoHold(unittest.TestCase):
self.assertTrue(owner.brake_hold_active) self.assertTrue(owner.brake_hold_active)
def test_detected_early_hybrid_uses_manual_aeb_hold(self): def test_detected_early_hybrid_uses_manual_aeb_hold(self):
for car, hybrid, aeb in ((CAR.TOYOTA_RAV4_TSS2, True, True), for car, hybrid, aeb in ((CAR.TOYOTA_COROLLA_TSS2, True, True),
(CAR.TOYOTA_COROLLA_TSS2, False, False),
(CAR.TOYOTA_RAV4_TSS2, True, True),
(CAR.TOYOTA_RAV4_TSS2, False, False), (CAR.TOYOTA_RAV4_TSS2, False, False),
(CAR.TOYOTA_RAV4_TSS2_2022, True, False), (CAR.TOYOTA_RAV4_TSS2_2022, True, False),
(CAR.TOYOTA_CAMRY_TSS2, False, True)): (CAR.TOYOTA_CAMRY_TSS2, False, True)):
@@ -136,6 +138,10 @@ class TestToyotaAutoHold(unittest.TestCase):
self.assertTrue(owner.brake_hold_active) self.assertTrue(owner.brake_hold_active)
frame = next(frame for frame in frames if frame[0] == 0x344) frame = next(frame for frame in frames if frame[0] == 0x344)
self.assertEqual(decode(cp, frame, 'PRE_COLLISION_2')['DSS1GDRV'], -1.0) self.assertEqual(decode(cp, frame, 'PRE_COLLISION_2')['DSS1GDRV'], -1.0)
state.out.brakePressed = False
released = [frame for _ in range(2) for frame in step_hold(owner, command, state) if frame[0] == 0x344]
self.assertTrue(owner.brake_hold_active)
self.assertEqual(decode(cp, released[0], 'PRE_COLLISION_2')['DSS1GDRV'], -1.0)
state.out.gasPressed = True state.out.gasPressed = True
step_hold(owner, command, state) step_hold(owner, command, state)
self.assertFalse(owner.brake_hold_active) self.assertFalse(owner.brake_hold_active)
+2 -1
View File
@@ -639,7 +639,8 @@ TOYOTA_AUTO_HOLD_AEB_CARS = {CAR.TOYOTA_CAMRY_TSS2}
def uses_toyota_auto_hold_aeb(CP) -> bool: def uses_toyota_auto_hold_aeb(CP) -> bool:
return (CP.carFingerprint in TOYOTA_AUTO_HOLD_AEB_CARS or return (CP.carFingerprint in TOYOTA_AUTO_HOLD_AEB_CARS or
(CP.carFingerprint == CAR.TOYOTA_RAV4_TSS2 and bool(CP.flags & ToyotaFlags.HYBRID))) (CP.carFingerprint in (CAR.TOYOTA_COROLLA_TSS2, CAR.TOYOTA_RAV4_TSS2) and
bool(CP.flags & ToyotaFlags.HYBRID)))
def stopping_decel_rate(CP): def stopping_decel_rate(CP):
+2 -7
View File
@@ -233,8 +233,7 @@ 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_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 (*fwd_packet_hook)(const CANPacket_t *msg);
typedef bool (*stage_tx_hook)(const CANPacket_t *msg); typedef void (*fwd_output_hook)(const CANPacket_t *msg, CANPacket_t *output, bool *replaced);
typedef bool (*fwd_output_hook)(const CANPacket_t *msg, CANPacket_t *output, bool *replaced);
typedef struct { typedef struct {
safety_hook_init init; safety_hook_init init;
@@ -243,7 +242,6 @@ typedef struct {
tx_hook tx; tx_hook tx;
fwd_hook fwd; fwd_hook fwd;
fwd_packet_hook fwd_packet; fwd_packet_hook fwd_packet;
stage_tx_hook stage_tx;
fwd_output_hook fwd_output; fwd_output_hook fwd_output;
get_checksum_t get_checksum; get_checksum_t get_checksum;
compute_checksum_t compute_checksum; compute_checksum_t compute_checksum;
@@ -376,10 +374,7 @@ extern safety_config current_safety_config;
int safety_fwd_hook(int bus_num, int addr); int safety_fwd_hook(int bus_num, int addr);
int safety_fwd_packet_hook(const CANPacket_t *msg); int safety_fwd_packet_hook(const CANPacket_t *msg);
bool safety_uses_camera_slot(const CANPacket_t *msg); bool safety_uses_forward_transform(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 safety_fwd_output_hook(const CANPacket_t *msg, CANPacket_t *output, bool *replaced);
int set_safety_hooks(uint16_t mode, uint16_t param); int set_safety_hooks(uint16_t mode, uint16_t param);
+1 -1
View File
@@ -338,7 +338,7 @@ static void hyundai_rx_hook(const CANPacket_t *msg) {
} }
cruise_button_prev = cruise_button; cruise_button_prev = cruise_button;
} else if (hyundai_kona_ev_label_cruise) { } else if (hyundai_kona_ev_label_cruise) {
hyundai_common_cruise_buttons_check(cruise_button == HYUNDAI_BTN_CANCEL ? HYUNDAI_BTN_NONE : cruise_button, hyundai_common_cruise_buttons_check((cruise_button == HYUNDAI_BTN_CANCEL) ? HYUNDAI_BTN_NONE : cruise_button,
false, false, hyundai_long_main_policy); false, false, hyundai_long_main_policy);
if ((cruise_button == HYUNDAI_BTN_CANCEL) || main_button) { if ((cruise_button == HYUNDAI_BTN_CANCEL) || main_button) {
controls_allowed = false; controls_allowed = false;
@@ -170,12 +170,12 @@ static void blended_aol_rx(const CANPacket_t *msg) {
const uint32_t now = microsecond_timer_get(); const uint32_t now = microsecond_timer_get();
const bool stock_hda2 = blended_aol_hda2 && !blended_aol_long; const bool stock_hda2 = blended_aol_hda2 && !blended_aol_long;
if (stock_hda2 && msg_matches(msg, 0x421U, pt, 8U)) { if (stock_hda2 && msg_matches(msg, 0x421U, pt, 8U)) {
const bool main = GET_BIT(msg, 27U); const bool cruise_main = GET_BIT(msg, 27U);
if (blended_aol_main && !main) { if (blended_aol_main && !cruise_main) {
blended_aol_clear(); blended_aol_clear();
} }
blended_aol_main_seen = true; blended_aol_main_seen = true;
blended_aol_main = main; blended_aol_main = cruise_main;
blended_aol_main_ts = now; blended_aol_main_ts = now;
} }
if (stock_hda2 && msg_matches(msg, 0x394U, pt, 8U)) { if (stock_hda2 && msg_matches(msg, 0x394U, pt, 8U)) {
+78 -205
View File
@@ -527,7 +527,56 @@ static void hyundai_canfd_ioniq6_optional_rx_hook(const CANPacket_t *msg) {
} }
} }
#if defined(ALLOW_DEBUG) && !defined(STM32F4)
static bool hyundai_kona_ccnc_feedback = false;
typedef struct {
bool seen;
uint8_t counter;
uint32_t ts;
} HyundaiKonaLfaState;
static HyundaiKonaLfaState hyundai_kona_camera;
static HyundaiKonaLfaState hyundai_kona_host;
static bool hyundai_kona_lfa_valid(const CANPacket_t *msg) {
return !msg->extended && (GET_LEN(msg) == 16U) &&
(hyundai_canfd_get_checksum(msg) == (hyundai_common_canfd_compute_checksum(msg) ^ 0x041DU));
}
static void hyundai_kona_camera_rx(const CANPacket_t *msg) {
if (hyundai_kona_ccnc_feedback && (msg->addr == 0x12AU) && (msg->bus == 2U) &&
msg->fd && hyundai_kona_lfa_valid(msg)) {
const uint32_t now = microsecond_timer_get();
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;
}
}
}
static void hyundai_kona_mdps_output(const CANPacket_t *msg, CANPacket_t *output, bool *replaced) {
if (hyundai_kona_ccnc_feedback && (msg->addr == 0xEAU) && (msg->bus == 0U) &&
msg->fd && !msg->extended && (GET_LEN(msg) == 24U) &&
((msg->data[3] & 7U) == 0U) && ((msg->data[6] & 0xFCU) == 0U) &&
((msg->data[6] & 3U) <= 1U) && (hyundai_canfd_get_checksum(msg) == hyundai_common_canfd_compute_checksum(msg))) {
// The physical EPS frame is still used unchanged by the vehicle and RX safety.
*output = *msg;
output->data[6] = 0x04U;
const uint16_t checksum = hyundai_common_canfd_compute_checksum(output);
output->data[0] = (uint8_t)checksum;
output->data[1] = (uint8_t)(checksum >> 8U);
*replaced = true;
}
}
#endif
static void hyundai_canfd_optional_rx_hook(const CANPacket_t *msg) { static void hyundai_canfd_optional_rx_hook(const CANPacket_t *msg) {
#if defined(ALLOW_DEBUG) && !defined(STM32F4)
hyundai_kona_camera_rx(msg);
#endif
hyundai_daw_rx(msg); hyundai_daw_rx(msg);
if (hyundai_canfd_ioniq6_long && (msg->bus == 1U)) { if (hyundai_canfd_ioniq6_long && (msg->bus == 1U)) {
hyundai_canfd_ioniq6_optional_rx_hook(msg); hyundai_canfd_ioniq6_optional_rx_hook(msg);
@@ -1231,169 +1280,6 @@ static bool hyundai_canfd_tx_hook_valid(const CANPacket_t *msg) {
return tx; return tx;
} }
#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;
static bool hyundai_kona_host_output = false;
static uint32_t hyundai_kona_camera_ts = 0U;
static uint32_t hyundai_kona_output_ts = 0U;
static uint8_t hyundai_kona_camera_counter = 0U;
static uint8_t hyundai_kona_output_counter = 0U;
static bool hyundai_kona_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);
}
static bool hyundai_kona_lfa_valid(const CANPacket_t *msg) {
return !msg->extended && (GET_LEN(msg) == 16U) &&
(hyundai_canfd_get_checksum(msg) == (hyundai_common_canfd_compute_checksum(msg) ^ 0x041DU));
}
static bool hyundai_kona_output_ready(uint32_t now, bool host, uint8_t counter) {
const uint32_t age = safety_get_ts_elapsed(now, hyundai_kona_output_ts);
const uint8_t delta = (uint8_t)(counter - hyundai_kona_output_counter);
return !hyundai_kona_output_seen ||
(((hyundai_kona_host_output == host) || (age >= 10000U)) &&
((age > 50000U) || ((delta > 0U) && (delta <= 127U))));
}
static void hyundai_kona_track_output(uint32_t now, bool host, uint8_t counter) {
hyundai_kona_output_seen = true;
hyundai_kona_host_output = host;
hyundai_kona_output_ts = now;
hyundai_kona_output_counter = counter;
}
static bool hyundai_kona_camera_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() && msg->fd && 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 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 = !msg->fd || !hyundai_kona_lfa_valid(msg) || safety_rx_checks_invalid || !aol_rx_healthy() ||
(hyundai_kona_camera_seen && (camera_age <= 50000U) && !advancing);
if (!blocked) {
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.fd = msg->fd;
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 && authority && consecutive && hyundai_kona_slot_owned) {
// Keep the camera's status and counter without repeating old host torque.
CANPacket_t neutral = *msg;
neutral.data[5] &= 0x01U;
neutral.data[6] = (neutral.data[6] & 0xC0U) | 0x08U;
const uint16_t checksum = hyundai_common_canfd_compute_checksum(&neutral) ^ 0x041DU;
neutral.data[0] = (uint8_t)checksum;
neutral.data[1] = (uint8_t)(checksum >> 8U);
neutral.bus = 0U;
hyundai_kona_emitting = true;
*replaced = safety_tx_hook(&neutral);
hyundai_kona_emitting = false;
if (*replaced) {
*output = neutral;
}
}
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_checked(const CANPacket_t *msg) { static bool hyundai_canfd_tx_hook_checked(const CANPacket_t *msg) {
bool tx = false; bool tx = false;
const bool ordinary_angle_frame = hyundai_ordinary_angle_stock && ((msg->addr == 0x110U) || (msg->addr == 0x362U)); const bool ordinary_angle_frame = hyundai_ordinary_angle_stock && ((msg->addr == 0x110U) || (msg->addr == 0x362U));
@@ -1464,30 +1350,36 @@ static bool hyundai_canfd_tx_hook_checked(const CANPacket_t *msg) {
if (hyundai_angle_aol_enabled && independent_command && !tx) { if (hyundai_angle_aol_enabled && independent_command && !tx) {
hyundai_ordinary_angle_release(); hyundai_ordinary_angle_release();
} }
#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]);
}
#endif
return tx; return tx;
} }
static bool hyundai_canfd_tx_hook(const CANPacket_t *msg) { static bool hyundai_canfd_tx_hook(const CANPacket_t *msg) {
bool allowed;
#if defined(ALLOW_DEBUG) && !defined(STM32F4) #if defined(ALLOW_DEBUG) && !defined(STM32F4)
bool allowed = true; if (hyundai_kona_ccnc_feedback && (msg->addr == 0x12AU)) {
if (hyundai_kona_idle_handoff && (msg->addr == 0x12AU)) {
const uint32_t now = microsecond_timer_get(); const uint32_t now = microsecond_timer_get();
allowed = hyundai_kona_emitting && !safety_rx_checks_invalid && aol_rx_healthy() && hyundai_kona_host_steering() && const uint8_t delta = (uint8_t)(msg->data[2] - hyundai_kona_host.counter);
msg->fd && hyundai_kona_lfa_valid(msg) && hyundai_kona_camera_seen && const bool advancing = !hyundai_kona_host.seen ||
(safety_get_ts_elapsed(now, hyundai_kona_camera_ts) <= 50000U) && (safety_get_ts_elapsed(now, hyundai_kona_host.ts) > 50000U) ||
(msg->data[2] == hyundai_kona_camera_counter) && hyundai_kona_output_ready(now, true, msg->data[2]); ((delta > 0U) && (delta <= 127U));
const bool active = ((msg->data[5] & 0xFEU) != 0U) || ((msg->data[6] & 0x3FU) != 8U);
const bool camera_current = hyundai_kona_camera.seen &&
(safety_get_ts_elapsed(now, hyundai_kona_camera.ts) <= 50000U);
allowed = !relay_malfunction && advancing && hyundai_kona_lfa_valid(msg) &&
(!active || (!safety_rx_checks_invalid && aol_rx_healthy() &&
lateral_controls_allowed() && camera_current)) &&
hyundai_canfd_tx_hook_checked(msg);
if (allowed) {
hyundai_kona_host.seen = true;
hyundai_kona_host.counter = msg->data[2];
hyundai_kona_host.ts = now;
}
} else
#endif
{
allowed = hyundai_canfd_tx_hook_checked(msg);
} }
#endif return allowed;
return
#if defined(ALLOW_DEBUG) && !defined(STM32F4)
allowed &&
#endif
hyundai_canfd_tx_hook_checked(msg);
} }
static void hyundai_canfd_reset_ioniq6_state(void) { static void hyundai_canfd_reset_ioniq6_state(void) {
@@ -2442,14 +2334,11 @@ static safety_config hyundai_canfd_init(uint16_t raw_param) {
hyundai_canfd_reset_ioniq6_state(); hyundai_canfd_reset_ioniq6_state();
hyundai_ordinary_angle_reset(); hyundai_ordinary_angle_reset();
#if defined(ALLOW_DEBUG) && !defined(STM32F4) && !defined(PANDA_BODY) #if defined(ALLOW_DEBUG) && !defined(STM32F4) && !defined(PANDA_BODY)
hyundai_kona_idle_handoff = (raw_param == 0x1C0CU) && (alternative_experience == 32); hyundai_kona_ccnc_feedback = (raw_param == 0x1C0CU) && (alternative_experience == 32);
hyundai_kona_camera_seen = false; hyundai_kona_camera.seen = false;
hyundai_kona_output_seen = false; hyundai_kona_host.seen = false;
hyundai_kona_pending = false; const bool kona_profile_valid = (raw_param != 0x1C0CU) || hyundai_kona_ccnc_feedback;
hyundai_kona_emitting = false; const uint16_t param = hyundai_kona_ccnc_feedback ? 0x0C0CU : raw_param;
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) || const bool valid = !GET_FLAG(param, 32768U) || (param == 0x8015U) || (param == 0x8095U) ||
(param == 0x8815U) || (param == 0x8895U) || (param == 0x8815U) || (param == 0x8895U) ||
hyundai_canfd_gv60_long_param(param); hyundai_canfd_gv60_long_param(param);
@@ -2470,20 +2359,6 @@ static safety_config hyundai_canfd_init(uint16_t raw_param) {
const bool daw_profile = (param == 0x0011U) || (param == 0x0091U) || (param == 0x0811U) || (param == 0x0891U) || const bool daw_profile = (param == 0x0011U) || (param == 0x0091U) || (param == 0x0811U) || (param == 0x0891U) ||
(param == 0x8015U) || (param == 0x8095U) || (param == 0x8815U) || (param == 0x8895U); (param == 0x8015U) || (param == 0x8095U) || (param == 0x8815U) || (param == 0x8895U);
ret = hyundai_daw_configure(ret, true, daw_profile); ret = hyundai_daw_configure(ret, true, daw_profile);
#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 == 0x12A) {
kona_tx[i].disable_static_blocking = true;
}
}
ret.tx_msgs = kona_tx;
}
}
#endif
} }
return ret; return ret;
} }
@@ -2495,9 +2370,7 @@ const safety_hooks hyundai_canfd_hooks = {
.tx = hyundai_canfd_tx_hook, .tx = hyundai_canfd_tx_hook,
.fwd = hyundai_canfd_fwd_hook, .fwd = hyundai_canfd_fwd_hook,
#if defined(ALLOW_DEBUG) && !defined(STM32F4) #if defined(ALLOW_DEBUG) && !defined(STM32F4)
.fwd_packet = hyundai_kona_camera_without_slot, .fwd_output = hyundai_kona_mdps_output,
.stage_tx = hyundai_kona_stage_tx,
.fwd_output = hyundai_kona_camera_output,
#endif #endif
.get_counter = hyundai_canfd_get_counter, .get_counter = hyundai_canfd_get_counter,
.get_checksum = hyundai_canfd_get_checksum, .get_checksum = hyundai_canfd_get_checksum,
+5 -29
View File
@@ -368,46 +368,22 @@ int safety_fwd_packet_hook(const CANPacket_t *msg) {
} }
#if !defined(STM32F4) && (defined(ALLOW_DEBUG) || !defined(STM32H7)) #if !defined(STM32F4) && (defined(ALLOW_DEBUG) || !defined(STM32H7))
bool safety_uses_camera_slot(const CANPacket_t *msg) { bool safety_uses_forward_transform(const CANPacket_t *msg) {
#ifdef ALLOW_DEBUG #ifdef ALLOW_DEBUG
return (current_safety_mode == SAFETY_HYUNDAI_CANFD) && hyundai_kona_idle_handoff && (msg->addr == 0x12AU); return (current_safety_mode == SAFETY_HYUNDAI_CANFD) && hyundai_kona_ccnc_feedback &&
(msg->addr == 0xEAU) && (msg->bus == 0U);
#else #else
(void)msg; (void)msg;
return false; return false;
#endif #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 safety_fwd_output_hook(const CANPacket_t *msg, CANPacket_t *output, bool *replaced) {
int destination; int destination;
if (current_hooks->fwd_output != NULL) { if (current_hooks->fwd_output != NULL) {
destination = safety_fwd_hook(msg->bus, msg->addr); destination = safety_fwd_hook(msg->bus, msg->addr);
if ((destination >= 0) && current_hooks->fwd_output(msg, output, replaced)) { if (destination >= 0) {
destination = -1; current_hooks->fwd_output(msg, output, replaced);
} }
} else { } else {
destination = safety_fwd_packet_hook(msg); destination = safety_fwd_packet_hook(msg);
@@ -11,10 +11,7 @@ SAFETY_UNUSED(safety_rx_hook);
SAFETY_UNUSED(safety_tx_hook); SAFETY_UNUSED(safety_tx_hook);
SAFETY_UNUSED(safety_fwd_hook); SAFETY_UNUSED(safety_fwd_hook);
SAFETY_UNUSED(safety_fwd_packet_hook); SAFETY_UNUSED(safety_fwd_packet_hook);
SAFETY_UNUSED(safety_uses_camera_slot); SAFETY_UNUSED(safety_uses_forward_transform);
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_fwd_output_hook);
SAFETY_UNUSED(safety_tick); SAFETY_UNUSED(safety_tick);
SAFETY_UNUSED(set_safety_hooks); SAFETY_UNUSED(set_safety_hooks);
@@ -1,10 +1,11 @@
import unittest import unittest
from opendbc.car import structs from opendbc.car import structs
from opendbc.car.hyundai.hyundaicanfd import hkg_can_fd_checksum
from opendbc.safety.tests.libsafety import libsafety_py from opendbc.safety.tests.libsafety import libsafety_py
class TestHyundaiKonaCcncHandoff(unittest.TestCase): class TestHyundaiKonaCcncFeedback(unittest.TestCase):
def setUp(self): def setUp(self):
self.safety = libsafety_py.libsafety self.safety = libsafety_py.libsafety
self.addCleanup(self.safety.set_alternative_experience, 0) self.addCleanup(self.safety.set_alternative_experience, 0)
@@ -15,136 +16,109 @@ class TestHyundaiKonaCcncHandoff(unittest.TestCase):
self.safety.set_alternative_experience(alternative) self.safety.set_alternative_experience(alternative)
self.assertEqual(self.safety.set_safety_hooks(structs.CarParams.SafetyModel.hyundaiCanfd, word), 0) self.assertEqual(self.safety.set_safety_hooks(structs.CarParams.SafetyModel.hyundaiCanfd, word), 0)
def packet(self, bus, body): @staticmethod
packet = libsafety_py.make_CANPacket(0x12A, bus, bytes.fromhex(body)) def packet(address, bus, body):
packet[0].fd = bus == 2 body = bytearray(body)
body[:2] = hkg_can_fd_checksum(address, None, body).to_bytes(2, 'little')
packet = libsafety_py.make_CANPacket(address, bus, body)
packet[0].fd = 1
return packet 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): def forward(self, packet):
output = libsafety_py.new_CANPacket() output = libsafety_py.new_CANPacket()
replaced = libsafety_py.ffi.new('bool *') replaced = libsafety_py.ffi.new('bool *')
bus = self.safety.safety_fwd_output_hook(packet, output, replaced) bus = self.safety.safety_fwd_output_hook(packet, output, replaced)
return bus, bool(replaced[0]), output return bus, bool(replaced[0]), output
def test_handoff_requires_current_camera_and_one_output_owner(self): def debug_mode(self):
if self.safety.set_safety_hooks(structs.CarParams.SafetyModel.allOutput, 0) != 0: if self.safety.set_safety_hooks(structs.CarParams.SafetyModel.allOutput, 0) != 0:
self.skipTest('Kona factory handoff is DEBUG only') self.skipTest('Kona feedback profile is DEBUG only')
camera = self.packet(2, 'a6770a1880001800000a000000900000')
self.mode(0x0C0C)
self.assertEqual(self.forward(camera)[0], -1)
self.mode(0x1C0C) self.mode(0x1C0C)
def test_feedback_is_exact_profile_and_debug_only(self):
feedback = self.packet(0xEA, 0, bytes(24))
for word, alternative, forward in ((0x1C0C, 0, -1), (0x0C0C, 32, 2), (0x0008, 0, 2)):
with self.subTest(word=word, alternative=alternative):
self.mode(word, alternative)
self.assertFalse(self.safety.safety_uses_forward_transform(feedback))
self.assertEqual(self.forward(feedback)[:2], (forward, False))
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)
self.assertFalse(release.safety_uses_forward_transform(feedback))
self.assertEqual(release.safety_fwd_packet_hook(feedback), -1)
def test_output_hook_without_transform_keeps_normal_forwarding_decision(self):
self.assertEqual(self.safety.set_safety_hooks(structs.CarParams.SafetyModel.toyota, 0), 0)
packet = self.packet(0xEA, 0, bytes(24))
self.assertEqual(self.forward(packet)[:2], (2, False))
self.safety.set_relay_malfunction(True)
self.assertEqual(self.forward(packet)[:2], (-1, False))
def test_eps_feedback_preserves_faults_and_never_changes_vehicle_side_input(self):
self.debug_mode()
for warning_byte, toi_byte, modify in ((0, 0, True), (0, 1, True), (0, 3, False),
(1, 1, False), (0, 5, False), (0, 0x10, False), (0, 0x40, False)):
with self.subTest(warning_byte=warning_byte, toi_byte=toi_byte):
body = bytearray(24)
body[2:4] = bytes((0xAA, warning_byte))
body[6:9] = bytes((toi_byte, 0x12, 0xA3))
packet = self.packet(0xEA, 0, body)
original = bytes(packet[0].data[0:24])
self.assertTrue(self.safety.safety_uses_forward_transform(packet))
self.assertFalse(self.safety.safety_tx_hook(self.packet(0xEA, 2, original)))
bus, replaced, output = self.forward(packet)
self.assertEqual((bus, replaced), (2, modify))
self.assertEqual(bytes(packet[0].data[0:24]), original)
if modify:
body[6] = 4
expected = self.packet(0xEA, 0, body)
self.assertEqual(bytes(output[0].data[0:24]), bytes(expected[0].data[0:24]))
packet[0].data[0] ^= 1
self.assertFalse(self.forward(packet)[1])
self.safety.set_relay_malfunction(True)
self.assertEqual(self.forward(packet)[:2], (-1, False))
def test_host_steering_is_independent_of_camera_counter_and_respects_authority(self):
self.debug_mode()
self.safety.set_timer(1_000_000) self.safety.set_timer(1_000_000)
self.assertEqual(self.forward(camera)[0], -1)
for status in self.safety.rx_status: for status in self.safety.rx_status:
status.msg_seen = True status.msg_seen = True
status.valid_checksum = True status.valid_checksum = True
status.valid_quality_flag = True status.valid_quality_flag = True
status.last_timestamp = 1_000_000 status.last_timestamp = 1_000_000
camera[0].fd = 0 def lfa(bus, counter, torque, request):
self.assertEqual(self.forward(camera)[0], -1) body = bytearray.fromhex('0000000280000800000a000000900000')
camera[0].fd = 1 raw_torque = 1024 + torque
self.assertEqual(self.forward(camera)[:2], (0, False)) body[2] = counter
self.assertEqual(self.forward(camera)[0], -1) body[5] = (raw_torque & 127) << 1
corrupt = self.packet(2, 'a6770a1881001800000a000000900000') body[6] = (raw_torque >> 7) | (0x10 if request else 0)
self.assertEqual(self.forward(corrupt)[0], -1) return self.packet(0x12A, bus, body)
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_controls_allowed(True)
self.safety.set_aol_test_heartbeat(True) self.safety.set_aol_test_heartbeat(True)
self.safety.aol_set_host_request(3) self.safety.aol_set_host_request(3)
host = self.packet(0, 'a009150280001800000a000000900000') self.assertFalse(self.safety.safety_tx_hook(lfa(0, 254, 5, True)))
host[0].data[2] = 20 camera = lfa(2, 81, 0, False)
from opendbc.car.hyundai.hyundaicanfd import hkg_can_fd_checksum self.assertEqual(self.forward(camera)[:2], (-1, False))
crc = hkg_can_fd_checksum(0x12A, None, bytearray(host[0].data[0:16])) self.safety.safety_rx_hook(camera)
host[0].data[0], host[0].data[1] = crc & 255, crc >> 8 self.assertTrue(self.safety.safety_tx_hook(lfa(0, 254, 5, True)))
self.safety.set_timer(1_005_000) for stamp, count, torque in ((1_010_000, 255, 10), (1_020_000, 0, 15)):
self.assertFalse(self.safety.safety_tx_hook(host)) self.safety.set_timer(stamp)
host[0].data[0] ^= 1 self.safety.safety_rx_hook(lfa(2, 82, 0, False))
self.assertFalse(self.safety.safety_stage_tx_hook(host)) self.assertTrue(self.safety.safety_tx_hook(lfa(0, count, torque, True)))
host[0].data[0] ^= 1 self.assertFalse(self.safety.safety_tx_hook(lfa(0, count, torque, True)))
self.assertTrue(self.safety.safety_stage_tx_hook(host)) corrupt = lfa(0, 1, 20, True)
self.safety.set_timer(1_010_000) corrupt[0].data[0] ^= 1
match = self.packet(2, '5ce51500000108f0000a000000640000') self.assertFalse(self.safety.safety_tx_hook(corrupt))
bus, replaced, output = self.forward(match) self.assertFalse(self.safety.safety_tx_hook(lfa(0, 1, 500, True)))
self.assertEqual((bus, replaced, output[0].data[2]), (0, True, 21)) self.safety.set_timer(1_060_001)
self.assertTrue(output[0].fd) self.assertFalse(self.safety.safety_tx_hook(lfa(0, 1, 15, True)))
self.assertEqual(output[0].data[7] & 0xF0, 0xF0) self.safety.safety_rx_hook(lfa(2, 150, 0, False))
self.safety.set_controls_allowed(False) self.safety.set_controls_allowed(False)
self.safety.aol_set_host_request(0) self.safety.aol_set_host_request(0)
following = self.packet(2, '110d1600000108f0000a000000640000') self.assertFalse(self.safety.safety_tx_hook(lfa(0, 1, 5, True)))
self.safety.set_timer(1_019_999) self.assertTrue(self.safety.safety_tx_hook(lfa(0, 1, 0, False)))
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.safety.set_relay_malfunction(True)
self.assertEqual(self.forward(following)[0], -1) self.assertFalse(self.safety.safety_tx_hook(lfa(0, 2, 0, False)))
self.assertFalse(self.safety.safety_stage_tx_hook(host))
def test_empty_owned_slot_uses_neutral_camera_status(self):
if self.safety.set_safety_hooks(structs.CarParams.SafetyModel.allOutput, 0) != 0:
self.skipTest('Kona factory handoff is DEBUG only')
self.mode(0x1C0C)
self.safety.set_timer(1_000_000)
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(self.packet(2, '784d1400000108f0000a000000640000'))[: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.assertTrue(self.safety.safety_stage_tx_hook(host))
self.safety.set_timer(1_010_000)
self.assertEqual(self.forward(self.packet(2, '5ce51500000108f0000a000000640000'))[:2], (0, True))
self.safety.set_timer(1_019_900)
camera = self.packet(2, '110d1600000108f0000a000000640000')
bus, replaced, output = self.forward(camera)
self.assertEqual((bus, replaced), (0, True))
self.assertTrue(output[0].fd)
self.assertEqual(output[0].data[2], 22)
self.assertEqual(output[0].data[5] & 0xFE, 0)
self.assertEqual(output[0].data[6] & 0x3F, 8)
self.assertEqual(output[0].data[7], camera[0].data[7])
self.assertEqual(self.forward(camera)[0], -1)
Binary file not shown.
Binary file not shown.
-3
View File
@@ -135,9 +135,6 @@ inline static std::unordered_map<std::string, ParamKeyAttributes> keys = {
{"LaneCentering", {PERSISTENT, BOOL, "0"}}, {"LaneCentering", {PERSISTENT, BOOL, "0"}},
{"LaneCenteringPauseOnSignal", {PERSISTENT, BOOL, "1"}}, {"LaneCenteringPauseOnSignal", {PERSISTENT, BOOL, "1"}},
{"LaneCenterOffset", {PERSISTENT, FLOAT, "0.0"}}, {"LaneCenterOffset", {PERSISTENT, FLOAT, "0.0"}},
{"ParkedClearance", {PERSISTENT, BOOL, "0"}},
{"ParkedClearanceGap", {PERSISTENT, FLOAT, "1.5"}},
{"ParkedClearanceShift", {PERSISTENT, FLOAT, "0.3"}},
{"LaneCenteringE2EAuthority", {PERSISTENT, FLOAT, "0.5"}}, {"LaneCenteringE2EAuthority", {PERSISTENT, FLOAT, "0.5"}},
{"LaneCenteringStrength", {PERSISTENT, FLOAT, "1.5"}}, {"LaneCenteringStrength", {PERSISTENT, FLOAT, "1.5"}},
{"UnidenConfig", {PERSISTENT | DONT_LOG, JSON}}, {"UnidenConfig", {PERSISTENT | DONT_LOG, JSON}},
+18 -34
View File
@@ -35,7 +35,7 @@ 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.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.selfdrive.car.cruise import LOW_SPEED_CRUISE_ON_SET, SlcWheelContext, VCruiseHelper, slc_target_kph
from openpilot.starpilot.speed_limits import physical_actions as slc_physical, tesla_set_speed_card from openpilot.starpilot.speed_limits import physical_actions as slc_physical, tesla_set_speed_card
from openpilot.starpilot.aol.intent import AolProcessFaultContext, independent_axis_requested, read_settings from openpilot.starpilot.aol.intent import AolProcessFaultContext, claim_remapped_lkas, independent_axis_requested, read_settings
from openpilot.starpilot.aol.transport_pause import TransportPauseFeedback, cp_identity 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 from opendbc.car.honda.stock_aol import qualified as qualified_honda_stock_aol, native_observation as honda_native_observation
from opendbc.car.volkswagen.stock_aol import safety_config as volkswagen_aol_safety_config from opendbc.car.volkswagen.stock_aol import safety_config as volkswagen_aol_safety_config
@@ -700,8 +700,10 @@ class Car:
paddle_denial = getattr(getattr(self, 'aol_transport_feedback', None), 'subaru_paddle_denial', None) paddle_denial = getattr(getattr(self, 'aol_transport_feedback', None), 'subaru_paddle_denial', None)
subaru_paddle_pending = bool(paddle_denial and not transport_reset and native is not None and subaru_paddle_pending = bool(paddle_denial and not transport_reset and native is not None and
paddle_denial[0] == int(native.observedMonoTime)) paddle_denial[0] == int(native.observedMonoTime))
mazda_restriction_pending = bool(mazda_aol and not transport_reset and native is not None and
getattr(self.aol_transport_feedback, 'mazda_restriction_native_ns', 0) == int(native.observedMonoTime))
rejected = native_reset or (not angle_arm_pending and not subaru_braked_main_pending and not subaru_paddle_pending and rejected = native_reset or (not angle_arm_pending and not subaru_braked_main_pending and not subaru_paddle_pending and
not volkswagen_initial_wait and not volkswagen_reverse_pending and not honda_eps_pending and not volkswagen_initial_wait and not volkswagen_reverse_pending and not honda_eps_pending and not mazda_restriction_pending and
native_latch_rejected(self.CP, native, state=CS if angle_panda_ready else None)) native_latch_rejected(self.CP, native, state=CS if angle_panda_ready else None))
rejection_ns = now_ns if native_reset else int(native.observedMonoTime) if rejected else 0 rejection_ns = now_ns if native_reset else int(native.observedMonoTime) if rejected else 0
observe_physical = getattr(self.aol_card_intent, 'observe_physical_samples', None) observe_physical = getattr(self.aol_card_intent, 'observe_physical_samples', None)
@@ -713,7 +715,8 @@ class Car:
now_ns=now_ns, producer=self.slc_producer_session) now_ns=now_ns, producer=self.slc_producer_session)
if hasattr(self.aol_card_intent, 'observe_vehicle_state'): if hasattr(self.aol_card_intent, 'observe_vehicle_state'):
self.aol_card_intent.observe_vehicle_state(self.CI.CS) self.aol_card_intent.observe_vehicle_state(self.CI.CS)
self.aol_card_intent.update(CS, fault_active=fault_active, now_ns=now_ns, native_rejection_ns=rejection_ns, consumed_buttons = claim_remapped_lkas(self.params, self.aol_settings, CS)
self.aol_card_intent.update(CS, consumed_buttons=consumed_buttons, fault_active=fault_active, now_ns=now_ns, native_rejection_ns=rejection_ns,
standard_enabled=(host_enabled if getattr(self.aol_card_intent, 'observe_stock_engagement', False) standard_enabled=(host_enabled if getattr(self.aol_card_intent, 'observe_stock_engagement', False)
else host_control_enabled)) else host_control_enabled))
# Observe ordinary state directly: independent AOL actuator activity is # Observe ordinary state directly: independent AOL actuator activity is
@@ -1264,11 +1267,17 @@ class Car:
self.pm.send('radarTracks', tracks_msg) self.pm.send('radarTracks', tracks_msg)
def publish_traffic_receipt(self, cs_send): def publish_traffic_receipt(self, cs_send):
traffic_receipt = getattr(self, 'traffic_receipt', None) for kind, enabled_attr, receipt_attr, sequence_attr in (
if getattr(self, 'conditional_replay', False) and traffic_receipt is not None: ('trafficMode', 'conditional_replay', 'traffic_receipt', 'traffic_event_sequence'),
toggle, gesture, drive_id, fingerprint, map_fingerprint, source_epoch, source_boot_ns, observed_ns = traffic_receipt ('switchbackMode', 'switchback_capable', 'switchback_receipt', 'switchback_event_sequence'),
):
receipt = getattr(self, receipt_attr, None)
if not getattr(self, enabled_attr, False) or receipt is None:
continue
toggle, gesture, drive_id, fingerprint, map_fingerprint, source_epoch, source_boot_ns, observed_ns = receipt
self.slc_cruise_event_id += 1 self.slc_cruise_event_id += 1
self.traffic_event_sequence += 1 sequence = getattr(self, sequence_attr) + 1
setattr(self, sequence_attr, sequence)
event = messaging.new_message('slcCruiseEvent') event = messaging.new_message('slcCruiseEvent')
event.logMonoTime = int(cs_send.logMonoTime) event.logMonoTime = int(cs_send.logMonoTime)
event.valid = bool(cs_send.valid) event.valid = bool(cs_send.valid)
@@ -1276,34 +1285,9 @@ class Car:
record.eventId = self.slc_cruise_event_id record.eventId = self.slc_cruise_event_id
record.producerSessionId = self.slc_producer_session record.producerSessionId = self.slc_producer_session
record.observedMonoTime = observed_ns record.observedMonoTime = observed_ns
record.kind = 'trafficMode' record.kind = kind
record.trafficMode = { record.trafficMode = {
'version': 1, 'sessionId': self.slc_producer_session, 'sequence': self.traffic_event_sequence, 'version': 1, 'sessionId': self.slc_producer_session, 'sequence': sequence,
'observedMonoTime': observed_ns, 'driveStartMonoTime': drive_id,
'settingsFingerprint': fingerprint, 'buttonMapFingerprint': map_fingerprint,
'sourceEpoch': source_epoch, 'sourceBootTime': source_boot_ns,
'sourceCarStateMonoTime': int(cs_send.logMonoTime),
'validUntilMonoTime': int(cs_send.logMonoTime) + 100_000_000,
'toggle': toggle, 'button': gesture.button.value if gesture is not None else 'unknown',
'press': gesture.press.value if gesture is not None else 'unknown',
}
self.pm.send('slcCruiseEvent', event)
switchback_receipt = getattr(self, 'switchback_receipt', None)
if getattr(self, 'switchback_capable', False) and switchback_receipt is not None:
toggle, gesture, drive_id, fingerprint, map_fingerprint, source_epoch, source_boot_ns, observed_ns = switchback_receipt
self.slc_cruise_event_id += 1
self.switchback_event_sequence += 1
event = messaging.new_message('slcCruiseEvent')
event.logMonoTime = int(cs_send.logMonoTime)
event.valid = bool(cs_send.valid)
record = event.slcCruiseEvent
record.eventId = self.slc_cruise_event_id
record.producerSessionId = self.slc_producer_session
record.observedMonoTime = observed_ns
record.kind = 'switchbackMode'
record.trafficMode = {
'version': 1, 'sessionId': self.slc_producer_session, 'sequence': self.switchback_event_sequence,
'observedMonoTime': observed_ns, 'driveStartMonoTime': drive_id, 'observedMonoTime': observed_ns, 'driveStartMonoTime': drive_id,
'settingsFingerprint': fingerprint, 'buttonMapFingerprint': map_fingerprint, 'settingsFingerprint': fingerprint, 'buttonMapFingerprint': map_fingerprint,
'sourceEpoch': source_epoch, 'sourceBootTime': source_boot_ns, 'sourceEpoch': source_epoch, 'sourceBootTime': source_boot_ns,
@@ -2,7 +2,7 @@ import unittest
from types import SimpleNamespace from types import SimpleNamespace
from unittest.mock import Mock, patch from unittest.mock import Mock, patch
from opendbc.car import gen_empty_fingerprint from opendbc.car import gen_empty_fingerprint, structs
from opendbc.car.can_definitions import CanData from opendbc.car.can_definitions import CanData
from opendbc.car.gm.interface import CarInterface as GMInterface from opendbc.car.gm.interface import CarInterface as GMInterface
from opendbc.car.gm.values import CAR as GMCar, GMFlags from opendbc.car.gm.values import CAR as GMCar, GMFlags
@@ -101,7 +101,7 @@ class CardInitLifecycleTest(unittest.TestCase):
cs = SimpleNamespace(canValid=True, canTimeout=False) cs = SimpleNamespace(canValid=True, canTimeout=False)
card.state_update = Mock(return_value=(cs, None)) card.state_update = Mock(return_value=(cs, None))
self.defer_radar_fixture(card) self.defer_radar_fixture(card)
control = object() control = structs.CarControl().as_reader()
class SubMaster: class SubMaster:
valid = {'carControl': False} valid = {'carControl': False}
+10 -14
View File
@@ -17,6 +17,8 @@ from openpilot.common.swaglog import cloudlog
from opendbc.car.car_helpers import interfaces from opendbc.car.car_helpers import interfaces
from opendbc.car.honda.values import CAR as HONDA_CAR, accord_angle_steer_ratio from opendbc.car.honda.values import CAR as HONDA_CAR, accord_angle_steer_ratio
from opendbc.car.toyota import radar_filter
from opendbc.car.toyota.values import CAR as TOYOTA_CAR, ToyotaFlags
from opendbc.car.vehicle_model import VehicleModel from opendbc.car.vehicle_model import VehicleModel
from openpilot.selfdrive.controls.lib.drive_helpers import clip_curvature 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 from openpilot.selfdrive.controls.lib.highway_correction_gain import HighwayCorrectionGain, predicted_lateral_accels, read_gain
@@ -59,11 +61,10 @@ from openpilot.starpilot.lateral.lane_change_preferences import LiveLaneChangePo
from openpilot.starpilot.lateral.lane_change_smoothing import LaneChangeSmoother, limit_rate from openpilot.starpilot.lateral.lane_change_smoothing import LaneChangeSmoother, limit_rate
from openpilot.starpilot.lateral.auto_lane_change import paired_clocks_ns from openpilot.starpilot.lateral.auto_lane_change import paired_clocks_ns
from openpilot.starpilot.lateral.lane_runtime import LaneCenteringHost, runtime_supported as lane_runtime_supported from openpilot.starpilot.lateral.lane_runtime import LaneCenteringHost, runtime_supported as lane_runtime_supported
from openpilot.starpilot.lateral.parked_runtime import ParkedClearanceHost, runtime_supported as parked_runtime_supported
from openpilot.starpilot.lateral.live_preferences import LiveSteeringPreferences from openpilot.starpilot.lateral.live_preferences import LiveSteeringPreferences
from openpilot.starpilot.lateral.torque_runtime import TorqueHost, runtime_enabled as torque_runtime_enabled from openpilot.starpilot.lateral.torque_runtime import TorqueHost, runtime_enabled as torque_runtime_enabled
from openpilot.starpilot.feature_capabilities import lateral_supported from openpilot.starpilot.feature_capabilities import lateral_supported
from openpilot.starpilot.lateral.controller_selection import learning_allowed, read_selection from openpilot.starpilot.lateral.controller_selection import ControllerMode, learning_allowed, read_selection
from openpilot.starpilot.lateral.gain_runtime import create_gain_owner from openpilot.starpilot.lateral.gain_runtime import create_gain_owner
from openpilot.starpilot.flm.global_runtime import GlobalRuntime from openpilot.starpilot.flm.global_runtime import GlobalRuntime
from openpilot.starpilot.flm.evidence_hooks import control_message from openpilot.starpilot.flm.evidence_hooks import control_message
@@ -145,7 +146,6 @@ class Controls:
optional = list( optional = list(
dict.fromkeys( dict.fromkeys(
self.longitudinal_inputs.optional_services + ['starpilotCarState', 'deviceState', 'autoSteeringLearning', 'starpilotSteeringTracking', 'pandaStates'] self.longitudinal_inputs.optional_services + ['starpilotCarState', 'deviceState', 'autoSteeringLearning', 'starpilotSteeringTracking', 'pandaStates']
+ (['radarTracks'] if parked_runtime_supported(self.CP) else [])
) )
) )
if optional: if optional:
@@ -174,8 +174,13 @@ class Controls:
self._prev_lkas_button_pressed = False self._prev_lkas_button_pressed = False
if self.CP.carFingerprint == "SUBARU_LEGACY_2025": if self.CP.carFingerprint == "SUBARU_LEGACY_2025":
self._refresh_subaru_aol_setting(0, force=True) self._refresh_subaru_aol_setting(0, force=True)
self.lane_centering_controller = ( camry_highway_damping = (self.CP.carFingerprint == TOYOTA_CAR.TOYOTA_CAMRY and bool(self.CP.flags & ToyotaFlags.HYBRID) and
LaneCenteringController(body=interface_dimensions(self.CI, self.CP), body_required=True) if predict_lane_clearance else LaneCenteringController() self.CP.openpilotLongitudinalControl and radar_filter.configured(self.CP) and
self.lateral_controller_selection.mode == ControllerMode.STARPILOT)
self.lane_centering_controller = LaneCenteringController(
body=interface_dimensions(self.CI, self.CP) if predict_lane_clearance else None,
body_required=predict_lane_clearance,
damp_centered_highway=camry_highway_damping,
) )
self.highway_correction_gain = HighwayCorrectionGain() self.highway_correction_gain = HighwayCorrectionGain()
self.highway_smoothing_supported = lateral_supported(self.CP) self.highway_smoothing_supported = lateral_supported(self.CP)
@@ -192,9 +197,6 @@ class Controls:
self.lane_centering_host = LaneCenteringHost( self.lane_centering_host = LaneCenteringHost(
self.params, settings_reader=(lambda: preferences.current.lane_centering) if preferences is not None else None, self.params, settings_reader=(lambda: preferences.current.lane_centering) if preferences is not None else None,
) if lane_runtime_supported(self.CP) else None ) if lane_runtime_supported(self.CP) else None
self.parked_clearance_host = ParkedClearanceHost(
self.params, settings_reader=(lambda: preferences.current.parked) if preferences is not None else None,
) if parked_runtime_supported(self.CP) else None
self.torque_host = ( self.torque_host = (
TorqueHost(self.params, self.CP, allow_learning=(self.torque_learning_allowed if self.lateral_controller_selection.policy is not None else None)) TorqueHost(self.params, self.CP, allow_learning=(self.torque_learning_allowed if self.lateral_controller_selection.policy is not None else None))
if torque_runtime_enabled(self.CP, self.params) if torque_runtime_enabled(self.CP, self.params)
@@ -675,11 +677,6 @@ class Controls:
steering_limited=self.steer_limited_by_safety, steering_limited=self.steer_limited_by_safety,
actuator_delay_s=lat_delay, actuator_delay_s=lat_delay,
) )
parked_clearance = getattr(self, 'parked_clearance_host', None)
if parked_clearance is not None:
new_desired_curvature += parked_clearance.update(
self.sm, now_ns=int(self.sm.logMonoTime['carState']) if os.getenv('REPLAY') == '1' else time.monotonic_ns(),
lateral_active=bool(CC.latActive), maneuver=bool(self.sm.valid['lateralManeuverPlan']))
lane_base_curvature = new_desired_curvature lane_base_curvature = new_desired_curvature
self.lane_centering_applied = 0.0 self.lane_centering_applied = 0.0
self.lane_centering_inactive_reason = 'inactive' self.lane_centering_inactive_reason = 'inactive'
@@ -716,7 +713,6 @@ class Controls:
time_discontinuity=lane_centering.time_discontinuity, time_discontinuity=lane_centering.time_discontinuity,
measured_curvature=self.curvature, measured_curvature=self.curvature,
lateral_delay_s=lane_delay, lateral_delay_s=lane_delay,
hold=bool(parked_clearance is not None and parked_clearance.shift > 0.0),
) )
) )
self.last_lane_centering_result = result self.last_lane_centering_result = result
@@ -36,7 +36,7 @@ from openpilot.starpilot.longitudinal.ioniq6_start import eligible as ioniq6_lon
from openpilot.starpilot.longitudinal.lane_change_gap import LaneChangeGap, project as project_lane_gap from openpilot.starpilot.longitudinal.lane_change_gap import LaneChangeGap, project as project_lane_gap
from openpilot.starpilot.longitudinal.experimental_release import ConditionalHandoff, ExperimentalRelease, project as project_release from openpilot.starpilot.longitudinal.experimental_release import ConditionalHandoff, ExperimentalRelease, project as project_release
from openpilot.starpilot.longitudinal.force_stop import StopPlan from openpilot.starpilot.longitudinal.force_stop import StopPlan
from openpilot.starpilot.longitudinal.force_stop_braking import distance_target, eligible as distance_braking_eligible from openpilot.starpilot.longitudinal.force_stop_braking import distance_target, eligible as distance_braking_eligible, kona_eligible
from openpilot.starpilot.longitudinal.follow_jerk import FollowJerk from openpilot.starpilot.longitudinal.follow_jerk import FollowJerk
from openpilot.starpilot.longitudinal.highlander_cruise import owner_for as highlander_cruise_owner from openpilot.starpilot.longitudinal.highlander_cruise import owner_for as highlander_cruise_owner
from openpilot.starpilot.longitudinal.lead_takeoff import LeadTakeoff, project as project_takeoff from openpilot.starpilot.longitudinal.lead_takeoff import LeadTakeoff, project as project_takeoff
@@ -82,7 +82,7 @@ def get_cruise_accel(e2e, v_cruise, v_ego, a_cruise_prev, angle_steers, CP, dt,
profile: AppliedProfile | None = None, profile: AppliedProfile | None = None,
base_brake_floor: float = A_CRUISE_MIN, selected_acceleration_max: float | None = None, faster_takeoffs: bool = False, base_brake_floor: float = A_CRUISE_MIN, selected_acceleration_max: float | None = None, faster_takeoffs: bool = False,
*, a_target_prev: float | None = None, ease_slc_braking: bool = False, *, a_target_prev: float | None = None, ease_slc_braking: bool = False,
speed_step: bool = False, downhill_error: float | None = None): speed_step: bool = False, downhill_error: float | None = None, gentle_settle: bool = False):
ceiling = TAKEOFF_ACCEL_MAX if faster_takeoffs else ACCEL_MAX ceiling = TAKEOFF_ACCEL_MAX if faster_takeoffs else ACCEL_MAX
max_accel = ceiling if e2e else get_max_accel(v_ego, faster_takeoffs) max_accel = ceiling if e2e else get_max_accel(v_ego, faster_takeoffs)
if selected_acceleration_max is not None and not e2e: if selected_acceleration_max is not None and not e2e:
@@ -110,6 +110,9 @@ def get_cruise_accel(e2e, v_cruise, v_ego, a_cruise_prev, angle_steers, CP, dt,
max_accel = min(max_accel, 0.) max_accel = min(max_accel, 0.)
if not e2e and not faster_takeoffs and v_ego >= MIN_ALLOW_THROTTLE_SPEED and speed_error > 0.: if not e2e and not faster_takeoffs and v_ego >= MIN_ALLOW_THROTTLE_SPEED and speed_error > 0.:
speed_error /= CRUISE_ACCEL_RESPONSE_TIME speed_error /= CRUISE_ACCEL_RESPONSE_TIME
elif gentle_settle and speed_error > 0.:
# The Elantra's delayed response can overshoot when Fast Takeoffs doubles a small speed correction.
speed_error /= np.interp(speed_error, [.5, 1.5], [CRUISE_ACCEL_RESPONSE_TIME, 1.0])
elif ease_slc_braking and speed_error < 0.: elif ease_slc_braking and speed_error < 0.:
speed_error /= CRUISE_ACCEL_RESPONSE_TIME # correct an SLC overshoot as gradually as an approach 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) target_accel = np.clip(speed_error, cruise_min, max_accel)
@@ -148,6 +151,7 @@ class LongitudinalPlanner:
self.throttle_gate = ModelThrottleGate() self.throttle_gate = ModelThrottleGate()
self.ioniq6_throttle_gate_enabled = ioniq6_long_eligible(CP) self.ioniq6_throttle_gate_enabled = ioniq6_long_eligible(CP)
self.force_stop_distance_braking = distance_braking_eligible(CP) self.force_stop_distance_braking = distance_braking_eligible(CP)
self.kona_distance_handoff = self.force_stop_distance_braking and kona_eligible(CP)
self.lane_change_gap = LaneChangeGap() self.lane_change_gap = LaneChangeGap()
self.experimental_release = ExperimentalRelease() self.experimental_release = ExperimentalRelease()
self.lead_approach = LeadApproach(dt, CP.longitudinalActuatorDelay) self.lead_approach = LeadApproach(dt, CP.longitudinalActuatorDelay)
@@ -199,7 +203,9 @@ class LongitudinalPlanner:
self.plan_drive_id = drive_id self.plan_drive_id = drive_id
model_y_no_lead_takeoff = (faster_lead_takeoff and self.CP.carFingerprint == 'TESLA_MODEL_Y' and model_y_no_lead_takeoff = (faster_lead_takeoff and self.CP.carFingerprint == 'TESLA_MODEL_Y' and
not any(lead.present for lead in (sm['radarState'].leadOne, sm['radarState'].leadTwo))) not any(lead.present for lead in (sm['radarState'].leadOne, sm['radarState'].leadTwo)))
faster_takeoffs = bool(faster_lead_takeoff and not model_y_no_lead_takeoff) model_y_turn_takeoff = self.CP.carFingerprint == 'TESLA_MODEL_Y' and (
sm['carState'].leftBlinker or sm['carState'].rightBlinker)
faster_takeoffs = bool(faster_lead_takeoff and not model_y_no_lead_takeoff and not model_y_turn_takeoff)
accel_ceiling = TAKEOFF_ACCEL_MAX if faster_takeoffs else ACCEL_MAX accel_ceiling = TAKEOFF_ACCEL_MAX if faster_takeoffs else ACCEL_MAX
if self.max_accel_override is not None: if self.max_accel_override is not None:
accel_ceiling = min(accel_ceiling, self.max_accel_override) accel_ceiling = min(accel_ceiling, self.max_accel_override)
@@ -513,13 +519,26 @@ class LongitudinalPlanner:
else: else:
self.previous_manual_cruise_kph = None self.previous_manual_cruise_kph = None
self.manual_cruise_step_until_ns = 0 self.manual_cruise_step_until_ns = 0
cs = sm['carState']
gentle_settle = (
self.CP.carFingerprint == 'HYUNDAI_ELANTRA_2021' and faster_takeoffs and
profile_eligible and not reset_state and v_ego >= 10. and self.allow_throttle and
cs.canValid and not (cs.canTimeout or cs.gasPressed or cs.brakePressed or cs.standstill) and
not sm['selfdriveState'].experimentalMode and not sm['controlsState'].forceDecel and traffic_mode is not True and
not any(lead.present for lead in (sm['radarState'].leadOne, sm['radarState'].leadTwo)) and
not (self.fcw or self.force_stop_plan.forcing or self.force_stop_plan.should_stop or self.force_stop_plan.approach_distance_m or
output_should_stop_mpc or output_should_stop_e2e) and self.mpc.solution_status == 0 and
ceiling.effective_mps is None and curve.effective_mps is None and navigation_target is None and downhill_error 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
v_cruise == v_cruise_kph * CV.KPH_TO_MS
)
self.a_cruise = get_cruise_accel(sm['selfdriveState'].experimentalMode, v_cruise, v_ego, self.a_cruise = get_cruise_accel(sm['selfdriveState'].experimentalMode, v_cruise, v_ego,
cruise_seed, 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, accel_coast, self.allow_throttle, cruise_profile,
base_brake_floor=global_floor, selected_acceleration_max=selected_acceleration, faster_takeoffs=faster_takeoffs, base_brake_floor=global_floor, selected_acceleration_max=selected_acceleration, faster_takeoffs=faster_takeoffs,
a_target_prev=self.output_a_target, a_target_prev=self.output_a_target,
ease_slc_braking=v_cruise == ceiling.effective_mps and not relevant_lead, speed_step=speed_step, ease_slc_braking=v_cruise == ceiling.effective_mps and not relevant_lead, speed_step=speed_step,
downhill_error=downhill_error) downhill_error=downhill_error, gentle_settle=gentle_settle)
if self.button_cruise is not None: if self.button_cruise is not None:
button_target = self.button_cruise.sample( button_target = self.button_cruise.sample(
sm, now_ns=sample_now_ns, drive_id=drive_id, target_speed=v_cruise, sm, now_ns=sample_now_ns, drive_id=drive_id, target_speed=v_cruise,
@@ -546,8 +565,10 @@ class LongitudinalPlanner:
candidates = [(output_a_target_mpc, self.mpc.source, output_should_stop_mpc), candidates = [(output_a_target_mpc, self.mpc.source, output_should_stop_mpc),
(self.a_cruise, LongitudinalPlanSource.cruise, cruise_should_stop)] (self.a_cruise, LongitudinalPlanSource.cruise, cruise_should_stop)]
if self.force_stop_distance_braking and self.force_stop_plan.forcing and self.force_stop_plan.obstacle_m is not None: if (self.force_stop_distance_braking and self.force_stop_plan.forcing and self.force_stop_plan.obstacle_m is not None and
stop_target = distance_target(v_ego, sm['carState'].aEgo, self.force_stop_plan.obstacle_m, action_t) (not self.kona_distance_handoff or self.force_stop_plan.should_stop)):
stop_target = distance_target(v_ego, sm['carState'].aEgo, self.force_stop_plan.obstacle_m, action_t,
existing_brake=self.kona_distance_handoff)
candidates.append((stop_target, LongitudinalPlanSource.cruise, False)) candidates.append((stop_target, LongitudinalPlanSource.cruise, False))
if sm['selfdriveState'].experimentalMode: if sm['selfdriveState'].experimentalMode:
candidates.append((output_a_target_e2e, LongitudinalPlanSource.e2e, output_should_stop_e2e)) candidates.append((output_a_target_e2e, LongitudinalPlanSource.e2e, output_should_stop_e2e))
File diff suppressed because one or more lines are too long
View File
@@ -94,7 +94,7 @@ class TestActualSettingsOwners(unittest.TestCase):
self.assertNotIn("setting_data_ShareUsageStats", large) self.assertNotIn("setting_data_ShareUsageStats", large)
self.assertNotIn("default_data_ShareUsageStats", large) self.assertNotIn("default_data_ShareUsageStats", large)
self.assertTrue(large["setting_lane_LaneCentering"]) self.assertTrue(large["setting_lane_LaneCentering"])
self.assertTrue(large["default_lane_LaneCentering"]) self.assertFalse(large["default_lane_LaneCentering"])
self.assertFalse(compact["setting_appearance_StockConfidenceBallWidget"]) self.assertFalse(compact["setting_appearance_StockConfidenceBallWidget"])
self.assertTrue(compact["default_appearance_StockConfidenceBallWidget"]) self.assertTrue(compact["default_appearance_StockConfidenceBallWidget"])
self.assertEqual(large["default_display_ScreenTimeoutOnroad"], 10.0) self.assertEqual(large["default_display_ScreenTimeoutOnroad"], 10.0)
+28 -6
View File
@@ -9,6 +9,7 @@ from openpilot.cereal import log
from openpilot.selfdrive.car.cruise import CRUISE_LONG_PRESS from openpilot.selfdrive.car.cruise import CRUISE_LONG_PRESS
from openpilot.system.manager.process_health import driving_process_failures from openpilot.system.manager.process_health import driving_process_failures
from openpilot.starpilot.conditional_mode.manual import Button, ButtonTracker, Press from openpilot.starpilot.conditional_mode.manual import Button, ButtonTracker, Press
from openpilot.starpilot.saved_source import read_saved
ButtonType = car.CarState.ButtonEvent.Type ButtonType = car.CarState.ButtonEvent.Type
GearShifter = car.CarState.GearShifter GearShifter = car.CarState.GearShifter
@@ -32,6 +33,21 @@ class AolSettings:
default_physical_buttons: bool = True default_physical_buttons: bool = True
main_wheel_action: bool = False main_wheel_action: bool = False
lkas_wheel_action: bool = False lkas_wheel_action: bool = False
lkas_unassigned: bool = True
@property
def default_lkas_toggle(self) -> bool:
return self.lkas_unassigned and self.lkas_action == 0 and not self.lkas_wheel_action
_LKAS_CONSUMED = frozenset((int(ButtonType.lkas),))
def claim_remapped_lkas(params, settings: AolSettings | None, CS) -> frozenset[int]:
if not CS.buttonEvents or settings is None or not settings.default_lkas_toggle or not any(
event.type == ButtonType.lkas and event.pressed for event in CS.buttonEvents):
return frozenset()
return frozenset() if read_saved(params, 'LKASButtonControl', 8) in ((None, True), (b'9', True)) else _LKAS_CONSUMED
def _button_value(params, key: str) -> int | None: def _button_value(params, key: str) -> int | None:
@@ -62,14 +78,19 @@ def read_settings(params) -> AolSettings:
pause_mps = float('nan') pause_mps = float('nan')
break break
valid_pause = 0.0 <= pause_mps <= 100.0 valid_pause = 0.0 <= pause_mps <= 100.0
lkas = _button_value(params, 'LKASButtonControl') saved_lkas = params.get('LKASButtonControl')
try:
lkas = 0 if saved_lkas is None else int(saved_lkas)
except (TypeError, ValueError):
lkas = None
main = _button_value(params, 'MainCruiseButtonControl') main = _button_value(params, 'MainCruiseButtonControl')
return AolSettings( return AolSettings(
enabled=params.get_bool('AlwaysOnLateral') and valid_pause, pause_brake_mps=pause_mps if valid_pause else 0.0, enabled=params.get_bool('AlwaysOnLateral') and valid_pause, pause_brake_mps=pause_mps if valid_pause else 0.0,
lkas_action=_axis_action(lkas), main_action=_axis_action(main), lkas_action=_axis_action(lkas), main_action=_axis_action(main),
default_physical_buttons=lkas == 0 and main == 0, default_physical_buttons=lkas == 0 and main == 0,
main_wheel_action=main == ADOPT_SPEED_LIMIT, main_wheel_action=main == ADOPT_SPEED_LIMIT,
lkas_wheel_action=lkas in (1, 2, 5, 6, 7, 8, 10, 11, 12, 13, 14), lkas_wheel_action=lkas in (1, 2, 5, 6, 7, 8, 10, 11, 12, 13, 14, 15),
lkas_unassigned=saved_lkas is None,
distance_actions=(_button_action(params, 'DistanceButtonControl'), distance_actions=(_button_action(params, 'DistanceButtonControl'),
_button_action(params, 'LongDistanceButtonControl'), _button_action(params, 'LongDistanceButtonControl'),
_button_action(params, 'VeryLongDistanceButtonControl')), _button_action(params, 'VeryLongDistanceButtonControl')),
@@ -337,7 +358,8 @@ class AolCardIntent:
# owners keep their current event and native contracts. # owners keep their current event and native contracts.
main_toggle = (not independent_buttons or main_managed) and not ( main_toggle = (not independent_buttons or main_managed) and not (
self.independent_cruise_buttons and self.settings.main_wheel_action) self.independent_cruise_buttons and self.settings.main_wheel_action)
lkas_toggle = (not independent_buttons or lkas_managed) and not getattr(self, 'allow_manumatic', False) lkas_toggle = (lkas_managed or not independent_buttons and self.settings.default_lkas_toggle) and not getattr(
self, 'allow_manumatic', False)
previously_held = (self._main_held and main_toggle) or (self._lkas_held and lkas_toggle) previously_held = (self._main_held and main_toggle) or (self._lkas_held and lkas_toggle)
cancel_pressed = False cancel_pressed = False
for event in CS.buttonEvents: for event in CS.buttonEvents:
@@ -348,16 +370,16 @@ class AolCardIntent:
self._perform(self.main_action if not main_managed else 0) self._perform(self.main_action if not main_managed else 0)
self._main_held = bool(event.pressed) self._main_held = bool(event.pressed)
elif button == int(ButtonType.lkas): elif button == int(ButtonType.lkas):
if (independent_buttons and event.pressed and not self._lkas_held and if (event.pressed and not self._lkas_held and self.lkas_action in (PAUSE_LATERAL, PAUSE_LONGITUDINAL) and
button not in consumed_buttons and self.settings.enabled and not CS.accFaulted and not self._fault_inhibit): button not in consumed_buttons and self.settings.enabled and not CS.accFaulted and not self._fault_inhibit):
self._perform(self.lkas_action if not lkas_managed else 0) self._perform(self.lkas_action)
self._lkas_held = bool(event.pressed) self._lkas_held = bool(event.pressed)
elif button == int(ButtonType.cancel) and event.pressed: elif button == int(ButtonType.cancel) and event.pressed:
cancel_pressed = True cancel_pressed = True
gesture_held = ((self._main_held and main_toggle and gesture_held = ((self._main_held and main_toggle and
(not independent_buttons or int(ButtonType.mainCruise) not in consumed_buttons)) or (not independent_buttons or int(ButtonType.mainCruise) not in consumed_buttons)) or
(self._lkas_held and lkas_toggle and (self._lkas_held and lkas_toggle and
(not independent_buttons or int(ButtonType.lkas) not in consumed_buttons))) int(ButtonType.lkas) not in consumed_buttons))
if not previously_held and gesture_held and (not (independent_buttons or self.preserve_unassigned_cancel) or not cancel_pressed): if not previously_held and gesture_held and (not (independent_buttons or self.preserve_unassigned_cancel) or not cancel_pressed):
self._last_latch_edge_ns = now_ns self._last_latch_edge_ns = now_ns
if cancel_pressed: if cancel_pressed:
@@ -129,7 +129,6 @@ def test_actual_card_disarming_preserves_intent_then_brake_fallback(identity):
with OpenpilotPrefix(): with OpenpilotPrefix():
saved = Params() saved = Params()
saved.put_bool('AlwaysOnLateral', True, block=True) saved.put_bool('AlwaysOnLateral', True, block=True)
saved.put('LKASButtonControl', 0, block=True)
saved.put('MainCruiseButtonControl', 0, block=True) saved.put('MainCruiseButtonControl', 0, block=True)
saved.put('AolBrakePauseSpeedMps', 0.0, block=True) saved.put('AolBrakePauseSpeedMps', 0.0, block=True)
settings = read_settings(saved) settings = read_settings(saved)
@@ -43,6 +43,12 @@ def update(owner, tick, button=None, pressed=False, **kwargs):
@pytest.mark.parametrize('identity', sorted(CLASSIC_LONG_IDS, key=str)) @pytest.mark.parametrize('identity', sorted(CLASSIC_LONG_IDS, key=str))
@pytest.mark.parametrize('mapped', [Button.mainCruise, Button.lkas]) @pytest.mark.parametrize('mapped', [Button.mainCruise, Button.lkas])
def test_actual_family_factory_keeps_unassigned_physical_button_independent(identity, mapped): def test_actual_family_factory_keeps_unassigned_physical_button_independent(identity, mapped):
if identity == CAR.HYUNDAI_I30_2026:
cp = params(identity, lda=True)
assert cp.dashcamOnly and not cp.openpilotLongitudinalControl
assert cp.safetyConfigs[0].safetyModel == structs.CarParams.SafetyModel.noOutput
assert not qualified(cp, marked_only=True)
return
cp = configure(identity) cp = configure(identity)
before = cp.to_dict() before = cp.to_dict()
settings = saved(mapped) settings = saved(mapped)
@@ -1,5 +1,8 @@
import pytest import pytest
from opendbc.car import structs
from opendbc.car.hyundai.values import CAR
from opendbc.car.hyundai.classic_long_aol import CLASSIC_LONG_IDS, aol_word, independent_buttons_qualified from opendbc.car.hyundai.classic_long_aol import CLASSIC_LONG_IDS, aol_word, independent_buttons_qualified
from openpilot.starpilot.aol.intent import AolSettings from openpilot.starpilot.aol.intent import AolSettings
from openpilot.starpilot.aol.tests.test_classic_long_profiles import params from openpilot.starpilot.aol.tests.test_classic_long_profiles import params
@@ -11,6 +14,11 @@ from openpilot.starpilot.car.hyundai.classic_long_intent import ClassicLongCardI
@pytest.mark.parametrize('release', [False, True]) @pytest.mark.parametrize('release', [False, True])
def test_each_actual_factory_preserves_marker_lda_and_release_boundary(identity, lda, release): def test_each_actual_factory_preserves_marker_lda_and_release_boundary(identity, lda, release):
cp = params(identity, lda=lda, release=release) cp = params(identity, lda=lda, release=release)
if identity == CAR.HYUNDAI_I30_2026:
assert cp.dashcamOnly and not cp.openpilotLongitudinalControl
assert cp.safetyConfigs[0].safetyModel == structs.CarParams.SafetyModel.noOutput
assert not independent_buttons_qualified(cp, marked_only=False)
return
before = cp.to_dict() before = cp.to_dict()
assert independent_buttons_qualified(cp, marked_only=False) == (lda and not release) assert independent_buttons_qualified(cp, marked_only=False) == (lda and not release)
assert not independent_buttons_qualified(cp) assert not independent_buttons_qualified(cp)
@@ -29,5 +37,5 @@ def test_each_family_profile_keeps_exact_saved_mapping(identity, lkas, main):
before = cp.to_dict() before = cp.to_dict()
settings = AolSettings(True, 0., lkas, main, (0, 0, 0), (0, 0, 0)) settings = AolSettings(True, 0., lkas, main, (0, 0, 0), (0, 0, 0))
owner = ClassicLongCardIntent(cp, settings) owner = ClassicLongCardIntent(cp, settings)
assert owner.independent_cruise_buttons assert owner.independent_cruise_buttons == (identity != CAR.HYUNDAI_I30_2026)
assert owner.settings == settings and cp.to_dict() == before assert owner.settings == settings and cp.to_dict() == before
@@ -116,6 +116,10 @@ class TestEv6ConfiguredDesire(unittest.TestCase):
for action in (0, AOL_TOGGLE, PAUSE_LATERAL, PAUSE_LONGITUDINAL): for action in (0, AOL_TOGGLE, PAUSE_LATERAL, PAUSE_LONGITUDINAL):
owner = self.owner(**{button: action}) owner = self.owner(**{button: action})
self.sample(owner, [(0, 0, Buttons.NONE)]) self.sample(owner, [(0, 0, Buttons.NONE)])
if button == 'lkas' and action in (PAUSE_LATERAL, PAUSE_LONGITUDINAL):
# A pause action is independent of physical MAIN authorization.
assert not owner.physical.authorized
self.sample(owner, [(1, 0, Buttons.NONE), (0, 0, Buttons.NONE)])
pressed = (1, 0, Buttons.NONE) if button == 'main' else (0, 1, Buttons.NONE) pressed = (1, 0, Buttons.NONE) if button == 'main' else (0, 1, Buttons.NONE)
self.sample(owner, [pressed, (0, 0, Buttons.NONE)]) self.sample(owner, [pressed, (0, 0, Buttons.NONE)])
self.assertTrue(owner.physical.authorized) self.assertTrue(owner.physical.authorized)
@@ -7,7 +7,7 @@ from opendbc.car import structs
from openpilot.starpilot.controllers.wheel_actions import DELIVERED_ACTIONS from openpilot.starpilot.controllers.wheel_actions import DELIVERED_ACTIONS
@pytest.mark.parametrize("action", (1, 2, 5, 6, 7, 8, 10, 11, 12, 13, 14)) @pytest.mark.parametrize("action", (0, 1, 2, 5, 6, 7, 8, 10, 11, 12, 13, 14, 15))
def test_remapped_lkas_keeps_established_lateral_after_brake(action, tmp_path): def test_remapped_lkas_keeps_established_lateral_after_brake(action, tmp_path):
from openpilot.common.params import Params from openpilot.common.params import Params
params = Params(str(tmp_path)) params = Params(str(tmp_path))
@@ -55,7 +55,7 @@ def test_remapped_lkas_never_creates_authority(tmp_path):
def test_lkas_wheel_action_catalog_matches_publisher(tmp_path): def test_lkas_wheel_action_catalog_matches_publisher(tmp_path):
from openpilot.common.params import Params from openpilot.common.params import Params
params = Params(str(tmp_path)) params = Params(str(tmp_path))
for action in range(15): for action in range(16):
params.put("LKASButtonControl", action, block=True) params.put("LKASButtonControl", action, block=True)
assert read_settings(params).lkas_wheel_action == (action in DELIVERED_ACTIONS) assert read_settings(params).lkas_wheel_action == (action in DELIVERED_ACTIONS)
@@ -91,7 +91,8 @@ def _exercise_join(identity, alternate, incidental, withdrawal, monkeypatch, *,
saved = Params() saved = Params()
saved.put_bool('OpenpilotEnabledToggle', True, block=True) saved.put_bool('OpenpilotEnabledToggle', True, block=True)
saved.put_bool('AlwaysOnLateral', True, block=True) saved.put_bool('AlwaysOnLateral', True, block=True)
saved.put('LKASButtonControl', 0 if unmapped else AOL_TOGGLE, block=True) if not unmapped:
saved.put('LKASButtonControl', AOL_TOGGLE, block=True)
saved.put('MainCruiseButtonControl', main_binding, block=True) saved.put('MainCruiseButtonControl', main_binding, block=True)
now = [10_000_000_000] now = [10_000_000_000]
holder = None holder = None
@@ -1,4 +1,6 @@
"""Cruise MAIN assigned to Adopt speed limit is not also the Hyundai physical lateral toggle.""" """Cruise MAIN assigned to Adopt speed limit is not also the Hyundai physical lateral toggle."""
from pathlib import Path
import pytest import pytest
from opendbc.car import structs from opendbc.car import structs
from openpilot.starpilot.aol.intent import AolCardIntent, AolSettings, read_settings from openpilot.starpilot.aol.intent import AolCardIntent, AolSettings, read_settings
@@ -54,8 +56,9 @@ def test_main_toggle_is_unchanged_without_independent_cruise_buttons():
class SavedParams: class SavedParams:
def __init__(self, values): def __init__(self, values, root=Path("/nonexistent")):
self.values = values self.values = values
self.root = root
def get(self, key, return_default=False): def get(self, key, return_default=False):
return self.values.get(key) return self.values.get(key)
@@ -64,10 +67,141 @@ class SavedParams:
return self.values.get(key) == b'1' return self.values.get(key) == b'1'
def get_param_path(self, key): def get_param_path(self, key):
return f'/nonexistent/{key}' return str(self.root / key)
@pytest.mark.parametrize('lkas,main,main_wheel', [(b'0', b'10', True), (b'0', b'9', False), (b'10', b'0', False), (b'0', b'8', False)]) @pytest.mark.parametrize('lkas,main,main_wheel', [(b'0', b'10', True), (b'0', b'9', False), (b'10', b'0', False), (b'0', b'8', False)])
def test_only_main_adopt_is_marked_as_a_main_wheel_action(lkas, main, main_wheel): def test_only_main_adopt_is_marked_as_a_main_wheel_action(lkas, main, main_wheel):
settings = read_settings(SavedParams({'AlwaysOnLateral': b'1', 'LKASButtonControl': lkas, 'MainCruiseButtonControl': main})) settings = read_settings(SavedParams({'AlwaysOnLateral': b'1', 'LKASButtonControl': lkas, 'MainCruiseButtonControl': main}))
assert settings.main_wheel_action == main_wheel assert settings.main_wheel_action == main_wheel
@pytest.mark.parametrize('action,keeps_lateral', [(8, True), (9, False), (0, True)])
def test_tucson_lkas_bookmark_does_not_double_as_lateral_toggle(action, keeps_lateral):
from opendbc.car import gen_empty_fingerprint
from opendbc.car.hyundai.interface import CarInterface
from opendbc.car.hyundai.values import CAR
fingerprint = gen_empty_fingerprint()
fingerprint[0][0x1AA] = 16
cp = CarInterface.get_params(CAR.HYUNDAI_TUCSON_4TH_GEN, fingerprint, [], False, False, False)
assert cp.safetyConfigs[0].safetyParam == 0x28
cp.safetyConfigs[0].safetyParam |= 0x800
settings = read_settings(SavedParams({'AlwaysOnLateral': b'1', 'LKASButtonControl': str(action).encode()}))
owner = create_intent(cp, settings)
assert owner.independent_cruise_buttons
cs = structs.CarState(canValid=True, gearShifter='drive', cruiseState={'available': True})
owner.update(cs, now_ns=1, fault_active=False)
if keeps_lateral:
press(owner, cs, 'lkas', 2)
assert not lateral(owner) and owner.physical_arm_ns == 0
cs.buttonEvents = []
owner.observe_full_engagement(cs, enabled=False, active=False, source_ns=5, observation_valid=True, now_ns=5, fault_active=False)
owner.observe_full_engagement(cs, enabled=True, active=True, source_ns=6, observation_valid=True, now_ns=6, fault_active=False)
assert lateral(owner)
press(owner, cs, 'lkas', 10, engaged=True)
assert lateral(owner) == keeps_lateral
assert owner.pause_lateral != keeps_lateral
@pytest.mark.parametrize('topology', ['hdai', 'hdaii'])
@pytest.mark.parametrize('alpha_long', [False, True])
@pytest.mark.parametrize('action', [0, 8, 9])
def test_mixed_palisade_lkas_bookmark_owns_only_the_wheel_action(tmp_path, topology, alpha_long, action):
from opendbc.car.hyundai.blended_stock_aol import qualified, qualified_alpha
from opendbc.car.hyundai.tests.test_palisade_2023 import params as palisade_params
from openpilot.starpilot.controllers.wheel_actions import WheelPublisher
cp = palisade_params(topology)
cp.alternativeExperience = 32
if alpha_long:
cp.openpilotLongitudinalControl = True
cp.pcmCruise = False
cp.alphaLongitudinalAvailable = True
cp.safetyConfigs[0].safetyParam |= 4
assert (qualified_alpha if alpha_long else qualified)(cp, marked_only=True)
saved = SavedParams({'AlwaysOnLateral': b'1', 'LKASButtonControl': str(action).encode(), 'MainCruiseButtonControl': b'0'}, tmp_path)
(tmp_path/'LKASButtonControl').write_bytes(saved.get('LKASButtonControl'))
owner = create_intent(cp, read_settings(saved))
cs = structs.CarState(canValid=True, gearShifter='drive', cruiseState={'available': True, 'enabled': True})
now = 3_000_000_000
publisher = WheelPublisher()
owner.update(cs, now_ns=now, fault_active=False)
assert publisher.observe(saved, cp, cs, now_ns=now, drive_id=1_000_000_000) == (('', 0),)
if action != 9:
press(owner, cs, 'lkas', now + 1)
assert not owner.allowed_latch and owner.physical_arm_ns == 0
cs.buttonEvents = []
owner.observe_full_engagement(cs, enabled=False, active=False, source_ns=now + 3,
observation_valid=True, now_ns=now + 3, fault_active=False)
owner.observe_full_engagement(cs, enabled=True, active=True, source_ns=now + 4,
observation_valid=True, now_ns=now + 4, fault_active=False)
assert lateral(owner)
edge = owner._last_latch_edge_ns
cs.buttonEvents = [structs.CarState.ButtonEvent(type='lkas', pressed=True)]
owner.update(cs, now_ns=now + 10_000_000, fault_active=False, standard_enabled=True)
actions = publisher.observe(saved, cp, cs, now_ns=now + 10_000_000, drive_id=1_000_000_000)
assert actions == ((('LKASButtonControl', 8),) if action == 8 else ())
assert lateral(owner) == (action != 9)
if action != 9:
assert not owner.pause_lateral and owner._last_latch_edge_ns == edge
owner.update(cs, now_ns=now + 20_000_000, fault_active=True, standard_enabled=True)
assert not lateral(owner)
@pytest.mark.parametrize('action,toggles', [(None, True), (b'0', False), (b'8', False), (b'9', True),
(b'15', False), (b'invalid', False)])
@pytest.mark.parametrize('owner_type', ['shared', 'ford', 'tesla'])
def test_saved_lkas_assignment_beats_physical_aol_fallback(owner_type, action, toggles):
from openpilot.starpilot.car.ford.aol import FordCardIntent
from openpilot.starpilot.car.tesla.screen_intent import TeslaScreenCardIntent
settings = read_settings(SavedParams({'AlwaysOnLateral': b'1', 'LKASButtonControl': action}))
cp = structs.CarParams(safetyConfigs=[{'safetyParam': 512}])
if owner_type == 'shared':
owner = AolCardIntent(settings, explicit_latch=True)
elif owner_type == 'ford':
owner = FordCardIntent(cp, settings)
else:
owner = TeslaScreenCardIntent(cp, settings)
cs = structs.CarState(canValid=True, gearShifter='drive', cruiseState={'available': True, 'enabled': True})
owner.update(cs, now_ns=1, fault_active=False)
owner.observe_full_engagement(cs, enabled=False, active=False, source_ns=2, observation_valid=True, now_ns=2, fault_active=False)
owner.observe_full_engagement(cs, enabled=True, active=True, source_ns=3, observation_valid=True, now_ns=3, fault_active=False)
assert lateral(owner)
press(owner, cs, 'lkas', 10, engaged=True)
assert lateral(owner) is not toggles
assert owner.pause_lateral is toggles
@pytest.mark.parametrize('action', [3, 4])
def test_lkas_pause_mapping_only_pauses_the_selected_axis(action):
saved = SavedParams({'AlwaysOnLateral': b'1', 'LKASButtonControl': str(action).encode()})
owner = AolCardIntent(read_settings(saved), explicit_latch=True)
cs = structs.CarState(canValid=True, gearShifter='drive', cruiseState={'available': True})
owner.update(cs, now_ns=1, fault_active=False)
owner.observe_full_engagement(cs, enabled=False, active=False, source_ns=2, observation_valid=True, now_ns=2, fault_active=False)
owner.observe_full_engagement(cs, enabled=True, active=True, source_ns=3, observation_valid=True, now_ns=3, fault_active=False)
assert lateral(owner)
press(owner, cs, 'lkas', 10, engaged=True)
assert owner.allowed_latch and owner.pause_lateral == (action == 3) and owner.pause_longitudinal == (action == 4)
@pytest.mark.parametrize('saved_action', [b'0', b'8', b'15'])
def test_live_lkas_remap_does_not_also_toggle_default_aol(tmp_path, saved_action):
from openpilot.starpilot.aol.intent import claim_remapped_lkas
saved = SavedParams({'AlwaysOnLateral': b'1'}, tmp_path)
settings = read_settings(saved)
owner = AolCardIntent(settings, explicit_latch=True)
cs = armed(owner)
(tmp_path/'LKASButtonControl').write_bytes(saved_action)
cs.buttonEvents = [structs.CarState.ButtonEvent(type='lkas', pressed=True)]
claimed = claim_remapped_lkas(saved, settings, cs)
assert claimed == frozenset((int(structs.CarState.ButtonEvent.Type.lkas),))
owner.update(cs, now_ns=10, consumed_buttons=claimed, fault_active=False, standard_enabled=True)
assert lateral(owner)
cs.buttonEvents = []
assert not claim_remapped_lkas(saved, settings, cs)
owner.update(cs, now_ns=11, fault_active=False, standard_enabled=True)
assert lateral(owner)
@@ -0,0 +1,45 @@
from dataclasses import replace
import pytest
from openpilot.starpilot.aol.tests.test_mazda_eps_recovery import output, set_events, setup
from openpilot.starpilot.tests.test_ford_reverse_intent import NOW, PRODUCER, change, native_change, sample
@pytest.mark.parametrize('stop', [False, True])
@pytest.mark.parametrize('fault', [None, 'panda', 'stale', 'permanent', 'main_off'])
def test_first_eps_frame_with_previous_active_receipt(stop, fault):
cp, cs, feedback = setup()
cs.steerFaultTemporary = True
cs.standstill = cs.brakePressed = stop
cs.gasPressed = not stop
cs.vEgo = 0.02 if stop else 6.
now = NOW + 10_000_000
sm, native = sample(cp, NOW, NOW, 1)
# Event receipt can predate Card's new physical sample.
set_events(sm, {'name': 'pcmDisable', 'userDisable': True})
if fault == 'panda':
native = native_change(sm, native, pandaInventory=(replace(native.pandaInventory[0], faults=1),))
elif fault == 'stale':
now = NOW + 31_000_000
elif fault == 'permanent':
cs.steerFaultPermanent = True
elif fault == 'main_off':
cs.cruiseState.available = False
lost = feedback.observe(sm, cp, cs, now, latched=True, intent_producer_session=PRODUCER)
assert not output(cs, native).lateral_active
if fault:
assert getattr(feedback, 'mazda_restriction_native_ns', 0) == 0
return
assert not lost and feedback.mazda_restriction_ns == now
cs.steerFaultTemporary = cs.standstill = cs.brakePressed = False
waiting, denial = sample(cp, now + 10_000_000, now + 10_000_000, 2, active=False, allowed=False, event_stamp=now + 10_000_000)
change(waiting, 'aolAxisState', lambda axis: setattr(axis, 'desiredLateral', True))
set_events(waiting)
assert not feedback.observe(waiting, cp, cs, now + 10_000_000, latched=True, intent_producer_session=PRODUCER)
assert feedback.mazda_restriction_ns == now
assert not output(cs, denial).lateral_active
resumed, grant = sample(cp, now + 100_000_000, now + 100_000_000, 3, event_stamp=now + 10_000_000)
set_events(resumed)
assert not feedback.observe(resumed, cp, cs, now + 100_000_000, latched=True, intent_producer_session=PRODUCER)
assert output(cs, grant).lateral_active
@@ -0,0 +1,53 @@
from dataclasses import replace
import pytest
from openpilot.starpilot.aol.tests.test_mazda_eps_recovery import output, set_events, setup
from openpilot.starpilot.tests.test_ford_reverse_intent import NOW, PRODUCER, change, native_change, sample
@pytest.mark.parametrize('approach', ['cold_main', 'braked_stop', 'eps_reblock'])
@pytest.mark.parametrize('fault', [None, 'wrong_panda', 'explicit_disarm', 'expired', 'native_fault'])
def test_pending_restriction_keeps_only_existing_intent(approach, fault):
cp, state, feedback = setup(acc=approach == 'eps_reblock')
if approach == 'cold_main':
# The idle proof before the first MAIN arm does not contain a lateral grant.
idle, _ = sample(cp, NOW + 1, NOW + 1, 2, active=False, allowed=False, requested=False, event_stamp=NOW + 1)
set_events(idle)
assert not feedback.observe(idle, cp, state, NOW + 1, latched=False, intent_producer_session=PRODUCER)
assert not feedback.lateral_only_baseline
stamp = NOW + 10_000_000
pending, native = sample(cp, stamp, stamp, 3, active=False, requested=approach == 'braked_stop', allowed=False, event_stamp=stamp)
change(pending, 'aolAxisState', lambda axis: setattr(axis, 'desiredLateral', True))
state.brakePressed = state.standstill = approach == 'braked_stop'
state.gasPressed = not state.brakePressed
state.steerFaultTemporary = True
set_events(pending, {'name': 'pcmDisable', 'userDisable': True}) if not state.cruiseState.enabled else set_events(pending)
if fault == 'wrong_panda':
slot = replace(native.pandaInventory[0], hardwareSerial='other')
native_change(pending, native, pandaSerial='other', pandaInventory=(slot,))
elif fault == 'native_fault':
native_change(pending, native, pandaInventory=(replace(native.pandaInventory[0], faults=1),))
elif fault == 'explicit_disarm':
set_events(pending, {'name': 'buttonCancel', 'userDisable': True})
now = stamp + (31_000_000 if fault == 'expired' else 5_000_000)
lost = feedback.observe(pending, cp, state, now, latched=True, intent_producer_session=PRODUCER)
assert not output(state, native).lateral_active
if fault is not None:
assert getattr(feedback, 'mazda_restriction_native_ns', 0) == 0
return
assert not lost and not feedback.failed
assert feedback.mazda_restriction_native_ns == native.observedMonoTime
state.steerFaultTemporary = state.brakePressed = state.standstill = False
recovery = stamp + 50_000_000
waiting, native = sample(cp, recovery, recovery, 4, active=False, requested=True, allowed=False, event_stamp=recovery)
change(waiting, 'aolAxisState', lambda axis: setattr(axis, 'desiredLateral', True))
set_events(waiting)
assert not feedback.observe(waiting, cp, state, recovery, latched=True, intent_producer_session=PRODUCER)
assert feedback.mazda_restriction_native_ns == native.observedMonoTime
assert feedback.mazda_restriction_ns == now
assert not output(state, native).lateral_active
active, grant = sample(cp, recovery + 10_000_000, recovery + 10_000_000, 5, event_stamp=recovery)
set_events(active)
assert not feedback.observe(active, cp, state, recovery + 10_000_000, latched=True, intent_producer_session=PRODUCER)
assert output(state, grant).lateral_active
@@ -1,5 +1,4 @@
from dataclasses import replace from dataclasses import replace
from types import SimpleNamespace
import pytest import pytest
@@ -11,6 +10,7 @@ from openpilot.selfdrive.selfdrived.events import Events
from openpilot.selfdrive.selfdrived.selfdrived import EventName, SelfdriveD from openpilot.selfdrive.selfdrived.selfdrived import EventName, SelfdriveD
from openpilot.selfdrive.selfdrived.state import StateMachine from openpilot.selfdrive.selfdrived.state import StateMachine
from openpilot.starpilot.aol.intent import AolSettings from openpilot.starpilot.aol.intent import AolSettings
from openpilot.starpilot.aol.intent_companion import IntentCompanion
from openpilot.starpilot.aol.runtime import AxisDecision, current_native from openpilot.starpilot.aol.runtime import AxisDecision, current_native
from openpilot.starpilot.aol.tests.test_gm_held_native import Peers from openpilot.starpilot.aol.tests.test_gm_held_native import Peers
from openpilot.starpilot.aol.wire import IntentState, PandaSlot, SafetyState, encode_safety from openpilot.starpilot.aol.wire import IntentState, PandaSlot, SafetyState, encode_safety
@@ -45,7 +45,7 @@ def native_health(cp, stamp, session):
@pytest.mark.parametrize('fault', ('none', 'assigned', 'missing_edge', 'stale', 'native_denial', 'native_fault', @pytest.mark.parametrize('fault', ('none', 'assigned', 'missing_edge', 'stale', 'native_denial', 'native_fault',
'hard_fault', 'main_off', 'other_user', 'no_prior_lat')) 'hard_fault', 'main_off', 'other_user', 'no_prior_lat'))
def test_mqb_cancel_can_publish_fresh_lateral_after_old_axis_expires(fault): def test_mqb_cancel_can_publish_fresh_lateral_after_old_axis_expires(fault, monkeypatch):
# Route 5e: the prior axis expires during processing, 28 ms after a fresh physical Cancel. # Route 5e: the prior axis expires during processing, 28 ms after a fresh physical Cancel.
edge = 10_000_000_000 edge = 10_000_000_000
now = edge + 28_173_000 now = edge + 28_173_000
@@ -58,7 +58,8 @@ def test_mqb_cancel_can_publish_fresh_lateral_after_old_axis_expires(fault):
sd.aol_car_state_log_ns = source = edge - (3_000_000 if fault == 'stale' else 0) sd.aol_car_state_log_ns = source = edge - (3_000_000 if fault == 'stale' else 0)
sd.conditional_car_state_valid = True sd.conditional_car_state_valid = True
sd.aol_last_intent = IntentState('mqb-card', 2, source, source, source + 200_000_000, True, False, False, True, True) sd.aol_last_intent = IntentState('mqb-card', 2, source, source, source + 200_000_000, True, False, False, True, True)
sd.aol_intent_companion = SimpleNamespace(integrity_epoch=44) sd.aol_intent_companion = IntentCompanion(None)
sd.aol_intent_companion.integrity_epoch = 44
sd.aol_published_input_proof = (sd.aol_session_id, edge - 11_623_000, edge - 5_618_000, sd.aol_published_input_proof = (sd.aol_session_id, edge - 11_623_000, edge - 5_618_000,
edge + 24_382_000, 'mqb-card', 44, True, True, fault != 'no_prior_lat', True) edge + 24_382_000, 'mqb-card', 44, True, True, fault != 'no_prior_lat', True)
sd.aol_authority_lost = sd.enabled = sd.active = False sd.aol_authority_lost = sd.enabled = sd.active = False
@@ -75,7 +76,8 @@ def test_mqb_cancel_can_publish_fresh_lateral_after_old_axis_expires(fault):
if fault != 'missing_edge': if fault != 'missing_edge':
cs.buttonEvents = [structs.CarState.ButtonEvent(type='cancel', pressed=True)] cs.buttonEvents = [structs.CarState.ButtonEvent(type='cancel', pressed=True)]
slot, native, wire, panda = native_health(cp, edge - 29_808_000, sd.aol_session_id) slot, native, wire, panda = native_health(cp, edge - 29_808_000, sd.aol_session_id)
sd.sm = Peers([wire.as_reader(), panda.as_reader()]) peers = Peers([wire.as_reader(), panda.as_reader()])
monkeypatch.setattr(sd, "sm", peers, raising=False)
sd.aol_published_input_native = current_native(sd.sm, cp, now_ns=now, axis_session_id=sd.aol_session_id) sd.aol_published_input_native = current_native(sd.sm, cp, now_ns=now, axis_session_id=sd.aol_session_id)
assert sd.aol_published_input_native is not None assert sd.aol_published_input_native is not None
if fault in ('native_denial', 'native_fault'): if fault in ('native_denial', 'native_fault'):
@@ -84,7 +86,7 @@ def test_mqb_cancel_can_publish_fresh_lateral_after_old_axis_expires(fault):
else: else:
native = replace(native, pandaInventory=(replace(slot, safetyRxChecksInvalid=True),)) native = replace(native, pandaInventory=(replace(slot, safetyRxChecksInvalid=True),))
wire.aolSafetyWire = encode_safety(native) wire.aolSafetyWire = encode_safety(native)
sd.sm.messages['aolSafetyWire'] = wire.as_reader() peers.messages['aolSafetyWire'] = wire.as_reader()
result = sd._expire_axis_continuity(cs, now) result = sd._expire_axis_continuity(cs, now)
assert result == (fault != 'none') assert result == (fault != 'none')
assert sd.aol_axis_decision.lateral_active == (fault == 'none') assert sd.aol_axis_decision.lateral_active == (fault == 'none')
@@ -94,7 +96,6 @@ def test_mqb_cancel_can_publish_fresh_lateral_after_old_axis_expires(fault):
@pytest.mark.parametrize('fault', ('none', 'unverified', 'mutated', 'session', 'revoked', 'old', 'hard_fault', 'native_denial')) @pytest.mark.parametrize('fault', ('none', 'unverified', 'mutated', 'session', 'revoked', 'old', 'hard_fault', 'native_denial'))
def test_mqb_armed_source_gap_handles_split_recovery(fault): def test_mqb_armed_source_gap_handles_split_recovery(fault):
from openpilot.starpilot.aol.intent_companion import IntentCompanion
from openpilot.starpilot.aol.transport_pause import AvailabilityPause, _healthy_transport_native from openpilot.starpilot.aol.transport_pause import AvailabilityPause, _healthy_transport_native
from openpilot.starpilot.aol.wire import encode_intent from openpilot.starpilot.aol.wire import encode_intent
@@ -111,8 +111,17 @@ def test_eps_retention_does_not_mask_independent_vetoes(fault, brake):
elif fault in ('hard_event', 'other_user'): elif fault in ('hard_event', 'other_user'):
change(sm, 'onroadEvents', lambda events: setattr(events[0], change(sm, 'onroadEvents', lambda events: setattr(events[0],
'immediateDisable' if fault == 'hard_event' else 'name', True if fault == 'hard_event' else 'buttonCancel')) 'immediateDisable' if fault == 'hard_event' else 'name', True if fault == 'hard_event' else 'buttonCancel'))
assert feedback.observe(sm, cp, state, now, latched=True, if fault == 'no_eps':
intent_producer_session='different' if fault == 'wrong_producer' else PRODUCER) before = leases(feedback)
# Native denial may precede the paddle data. Hold intent briefly while LAT stays denied.
assert not feedback.observe(sm, cp, state, now, latched=True, intent_producer_session=PRODUCER)
assert feedback.subaru_paddle_denial == (now, PRODUCER, int(sm['aolAxisState'].intentIntegrityEpoch), False)
assert not native.lateralAllowed and leases(feedback) == before
assert feedback.observe(sm, cp, state, now + 30_000_001, latched=True, intent_producer_session=PRODUCER)
assert feedback.subaru_paddle_denial is None
else:
assert feedback.observe(sm, cp, state, now, latched=True,
intent_producer_session='different' if fault == 'wrong_producer' else PRODUCER)
@pytest.mark.parametrize('gas', (False, True)) @pytest.mark.parametrize('gas', (False, True))
@@ -360,3 +360,48 @@ def test_missing_or_malformed_vehicle_policy_grants_no_intent_capability(cp):
elif cp == 'malformed_registered_brand': elif cp == 'malformed_registered_brand':
cp = SimpleNamespace(brand='hyundai') cp = SimpleNamespace(brand='hyundai')
assert not policy_for(cp).intent_supported assert not policy_for(cp).intent_supported
@pytest.mark.parametrize('gas', [False, True])
def test_classic_hyundai_main_off_lag_retains_independent_lateral_intent(gas):
from opendbc.car import gen_empty_fingerprint
from opendbc.car.hyundai.interface import CarInterface
from opendbc.car.hyundai.values import CAR
from opendbc.car.hyundai.classic_scc_aol import aol_word
from openpilot.cereal import messaging
fingerprint = gen_empty_fingerprint()
fingerprint[0].update({0x391: 8, 0x38d: 8})
fingerprint[2][0x485] = 4
fingerprint[1][0x500] = 8
cp = CarInterface.get_params(CAR.HYUNDAI_SONATA_HYBRID, fingerprint, [], False, False, False)
cp.safetyConfigs[0].safetyParam = aol_word(cp)
cp.alternativeExperience = 32
case = fixture.IoniqAvailabilityTests(methodName='runTest')
with ExitStack() as cleanup:
cleanup.callback(case.doCleanups)
cleanup.enter_context(OpenpilotPrefix())
sd, _, drive, card, receive = case._ioniq_availability_callers(full_op=False, cp=cp)
state = fixture.car_state()
state.cruiseState.available = False
state.cruiseState.enabled = False
state.gasPressed = gas
def state_event(tick):
message = messaging.new_message('carState', valid=True, logMonoTime=10_000_000_000 + tick * 10_000_000)
message.carState = state
return message
axis, _, command = drive(2, car_state_message=state_event(2), native_request_long=False)
assert axis.lateralActive and command.latActive
assert receive(10_020_000_000, axis=sd.pm.messages['aolAxisState'], event=sd.pm.messages['onroadEvents'],
state=state, preserve_cruise_state=True)
with mock.patch.object(type(sd.rk), 'lagging', new_callable=mock.PropertyMock, return_value=True):
axis, alerts, command = drive(3, car_state_message=state_event(3), native_request_long=False)
assert alerts.alertType == 'selfdrivedLagging/softDisable'
assert not axis.lateralActive and not axis.longitudinalActive and not axis.nativeAcknowledged
assert not command.latActive and not command.longActive
events = sd.pm.messages['onroadEvents']
assert any(event.name == 'wrongCarMode' and event.userDisable for event in events.onroadEvents)
assert receive(10_030_000_000, axis=sd.pm.messages['aolAxisState'], event=events, state=state, preserve_cruise_state=True)
assert card.aol_transport_feedback.ordinary_warning_qualified
@@ -25,7 +25,8 @@ def configured_callers(identity, lka, guard, *, hybrid=False, lkas_action=9):
with OpenpilotPrefix(): with OpenpilotPrefix():
saved = Params() saved = Params()
saved.put_bool('AlwaysOnLateral', True, block=True) saved.put_bool('AlwaysOnLateral', True, block=True)
saved.put('LKASButtonControl', lkas_action, block=True) if lkas_action is not None:
saved.put('LKASButtonControl', lkas_action, block=True)
saved.put('MainCruiseButtonControl', 9 if guard == 'mapped_main' else 0, block=True) saved.put('MainCruiseButtonControl', 9 if guard == 'mapped_main' else 0, block=True)
for key in ('CancelButtonControl', 'LongCancelButtonControl', 'VeryLongCancelButtonControl'): for key in ('CancelButtonControl', 'LongCancelButtonControl', 'VeryLongCancelButtonControl'):
saved.put(key, 3 if guard == 'configured_cancel' and key == 'CancelButtonControl' else 0, block=True) saved.put(key, 3 if guard == 'configured_cancel' and key == 'CancelButtonControl' else 0, block=True)
@@ -212,7 +213,7 @@ def test_source_selected_hybrid_stock_brake_continuity(tick, gesture):
@pytest.mark.parametrize('tick', [3, 7]) @pytest.mark.parametrize('tick', [3, 7])
@pytest.mark.parametrize('gesture', ['cancel', 'brake']) @pytest.mark.parametrize('gesture', ['cancel', 'brake'])
def test_default_button_mapping_retains_independent_lateral_on_cruise_withdrawal(identity, lka, tick, gesture): def test_default_button_mapping_retains_independent_lateral_on_cruise_withdrawal(identity, lka, tick, gesture):
with configured_callers(identity, lka, 'baseline', lkas_action=0) as context: with configured_callers(identity, lka, 'baseline', lkas_action=None) as context:
sd, step, card, receive = context.sd, context.step, context.card, context.receive sd, step, card, receive = context.sd, context.step, context.card, context.receive
state = car_state(brake=gesture == 'brake') state = car_state(brake=gesture == 'brake')
state.vEgoRaw = state.vEgo state.vEgoRaw = state.vEgo
+3 -2
View File
@@ -200,7 +200,8 @@ class TestHighlanderAol(unittest.TestCase):
self.assertTrue(policy.full_axis_runtime_required) self.assertTrue(policy.full_axis_runtime_required)
cp.alternativeExperience |= policy.alternative_experience_addition cp.alternativeExperience |= policy.alternative_experience_addition
preferences.finalize(cp) preferences.finalize(cp)
expected = 288 if hold and (car == CAR.TOYOTA_CAMRY_TSS2 or hybrid and car == CAR.TOYOTA_RAV4_TSS2) else 160 if hold else 32 aeb_hold = car == CAR.TOYOTA_CAMRY_TSS2 or (hybrid and car in (CAR.TOYOTA_RAV4_TSS2, CAR.TOYOTA_COROLLA_TSS2))
expected = 288 if hold and aeb_hold else 160 if hold else 32
self.assertEqual(cp.alternativeExperience, expected) self.assertEqual(cp.alternativeExperience, expected)
self.assertTrue(qualified(cp, marked_only=True)) self.assertTrue(qualified(cp, marked_only=True))
for experience in (33, 416, 288 if expected != 288 else 160): for experience in (33, 416, 288 if expected != 288 else 160):
@@ -315,7 +316,7 @@ class TestHighlanderAol(unittest.TestCase):
with patch('openpilot.selfdrive.car.card.messaging.recv_one_retry', return_value=SimpleNamespace(can=[1])), \ with patch('openpilot.selfdrive.car.card.messaging.recv_one_retry', return_value=SimpleNamespace(can=[1])), \
patch('openpilot.selfdrive.car.card.get_car', side_effect=discover): patch('openpilot.selfdrive.car.card.get_car', side_effect=discover):
selected = Car() selected = Car()
aeb_hold = car == CAR.TOYOTA_CAMRY_TSS2 or hybrid and car == CAR.TOYOTA_RAV4_TSS2 aeb_hold = car == CAR.TOYOTA_CAMRY_TSS2 or (hybrid and car in (CAR.TOYOTA_RAV4_TSS2, CAR.TOYOTA_COROLLA_TSS2))
self.assertEqual(selected.CP.alternativeExperience, 288 if hold and aeb_hold else 160 if hold else 32) self.assertEqual(selected.CP.alternativeExperience, 288 if hold and aeb_hold else 160 if hold else 32)
self.assertEqual(bool(selected.CP.flags & ToyotaFlags.AUTO_BRAKE_HOLD), hold) self.assertEqual(bool(selected.CP.flags & ToyotaFlags.AUTO_BRAKE_HOLD), hold)
self.assertTrue(qualified(selected.CP, marked_only=True)) self.assertTrue(qualified(selected.CP, marked_only=True))
+90
View File
@@ -0,0 +1,90 @@
from openpilot.cereal import log
from openpilot.starpilot.aol.runtime import AXIS_MAX_AGE_NS, SAFETY_MAX_AGE_NS
from openpilot.starpilot.aol.transport_pause_conditions import stock_lateral_off
def temporary_lag_intent_current(self, sm, cp, cs, axis, stamp, now_ns, *, latched, producer, signature, healthy_native, stock_user_event):
reason = str(axis.faultReason)
events = sm['onroadEvents']
faults = [event for event in events if event.immediateDisable or event.softDisable]
isolated = bool(len(faults) == 1 and faults[0].name == log.OnroadEvent.EventName.selfdrivedLagging and
faults[0].softDisable and not faults[0].immediateDisable)
recovering = bool(cp.brand == 'gm' and not faults and reason == 'none' and
0 < self.lag_withdrawal_ns <= now_ns <= self.lag_withdrawal_ns + SAFETY_MAX_AGE_NS and
axis.desiredLateral and not axis.lateralActive and axis.nativeAcknowledged and
not axis.desiredLongitudinal and not axis.longitudinalActive)
if not recovering and not isolated and (reason != 'critical' or faults):
return False
previous = self.signature
joining = bool(self.pending_event and previous is not None and previous[5] == 'critical' and previous[6] == self.pending_event)
if (not latched or self.failed or self.paused or self.pending_event and not joining or self.retention_started_ns or
not self.session or str(axis.sessionId) != self.session or reason not in ('none', 'critical') or
not producer or producer != self.availability_producer or
str(getattr(axis, 'intentProducerSessionId', '')) != producer or
int(getattr(axis, 'intentIntegrityEpoch', 0)) != self.availability_epoch or
not self.lateral_baseline_ns or not self.lateral_inventory or
not cs.canValid or cs.canTimeout or cs.steerFaultTemporary or cs.steerFaultPermanent or cs.accFaulted or
not 0 < axis.sourceCarStateMonoTime <= stamp <= now_ns or
now_ns - axis.sourceCarStateMonoTime > AXIS_MAX_AGE_NS):
return False
event_ns = int(sm.logMonoTime['onroadEvents'])
if (not sm.seen['onroadEvents'] or not sm.valid['onroadEvents'] or not sm.alive['onroadEvents'] or
not 0 < event_ns <= now_ns or now_ns - event_ns > 1_500_000_000 or
joining and (axis.faultEventMonoTime != self.pending_event or now_ns - self.pending_event > AXIS_MAX_AGE_NS)):
return False
withdrawn = bool(reason == 'critical' and not axis.desiredLateral and not axis.desiredLongitudinal and
not axis.lateralActive and not axis.longitudinalActive)
matched = bool(withdrawn and isolated and axis.faultEventMonoTime == event_ns <= stamp)
held_original = bool(reason == 'none' and isolated and signature == previous and
axis.desiredLateral and axis.lateralActive and axis.nativeAcknowledged and
0 < axis.faultEventMonoTime < event_ns and now_ns - event_ns <= AXIS_MAX_AGE_NS)
known_lag = bool(isolated and previous is not None and previous[5] == 'critical' and previous[6] == event_ns)
pending = bool(withdrawn and event_ns < axis.faultEventMonoTime <= stamp and
now_ns - axis.faultEventMonoTime <= AXIS_MAX_AGE_NS and
(joining or known_lag or not faults and previous is not None and previous[5] == 'none' and
0 <= now_ns - self.lateral_baseline_ns <= AXIS_MAX_AGE_NS))
if not (matched or held_original or pending or recovering):
return False
from openpilot.starpilot.aol.vehicle import policy_for
if not policy_for(cp).intent_supported:
return False
native = healthy_native(sm, cp, cs, self.session, now_ns)
if native is None and cp.brand == 'ford':
from openpilot.starpilot.car.ford.gas_override import healthy_gas_transport_native
native = healthy_gas_transport_native(sm, cp, cs, self.session, now_ns)
if (native is None or not native.pandaInventory or
held_original and not (native.requestedLateral and native.lateralAllowed) or
native.observedMonoTime < self.lateral_native_ns or
(native.pandaSerial, tuple(p.hardwareSerial for p in native.pandaInventory)) != self.lateral_inventory):
return False
users = [event for event in events if event.userDisable]
if users:
from opendbc.car.gm.values import is_volt_sdgm_accepted_envelope, is_bolt_pedal_profile
from openpilot.starpilot.nostalgia import physical_cancel
gm_pedal = bool(self.lateral_only_baseline and (is_volt_sdgm_accepted_envelope(cp) or is_bolt_pedal_profile(cp)) and
(cs.brakePressed or cs.regenBraking) and cs.cruiseState.available and
not cs.doorOpen and not cs.seatbeltUnlatched and not cs.steeringDisengage and not physical_cancel(cs, cp) and
not axis.desiredLongitudinal and not axis.longitudinalActive and
not native.requestedLongitudinal and not native.longitudinalAllowed and
all(event.name == log.OnroadEvent.EventName.pedalPressed and event.noEntry and not event.softDisable and not event.immediateDisable for event in users))
stock_user = stock_user_event(cp)
gm_stock_withdrawal = bool(cp.brand == 'gm' and cp.pcmCruise and self.lateral_only_baseline and
(withdrawn or recovering) and cs.cruiseState.available and not cs.cruiseState.enabled and
not cs.brakePressed and not cs.regenBraking and not cs.gasPressed and
not cs.doorOpen and not cs.seatbeltUnlatched and not cs.steeringDisengage and
not physical_cancel(cs, cp) and not native.requestedLateral and not native.lateralAllowed and
not native.requestedLongitudinal and not native.longitudinalAllowed and
all(event.name == stock_user and not event.softDisable and not event.immediateDisable for event in users))
if not gm_pedal and not gm_stock_withdrawal and (not getattr(self, 'lateral_only_baseline', False) or stock_user is None or
any(event.name != stock_user or event.softDisable or event.immediateDisable for event in users) or
not stock_lateral_off(cp, cs, native)):
return False
if pending:
if not self.pending_event:
self.pending_event = int(axis.faultEventMonoTime)
self.awaiting = True
elif joining:
self.pending_event = 0
if matched and cp.brand == 'gm':
self.lag_withdrawal_ns = stamp
return True
+23 -84
View File
@@ -8,6 +8,7 @@ from openpilot.starpilot.aol.transport_pause_conditions import (
from openpilot.starpilot.aol.transport_pause_session import ( from openpilot.starpilot.aol.transport_pause_session import (
AvailabilityPause as AvailabilityPause, TransportPause as TransportPause, cp_identity as cp_identity, AvailabilityPause as AvailabilityPause, TransportPause as TransportPause, cp_identity as cp_identity,
) )
from openpilot.starpilot.aol.transport_lag import temporary_lag_intent_current
from openpilot.starpilot.aol.panda_faults import blocking_fault_mask, blocking_fault_list from openpilot.starpilot.aol.panda_faults import blocking_fault_mask, blocking_fault_list
from openpilot.starpilot.aol.runtime import AXIS_MAX_AGE_NS, SAFETY_MAX_AGE_NS, current_native, native_inventory_matches_cp from openpilot.starpilot.aol.runtime import AXIS_MAX_AGE_NS, SAFETY_MAX_AGE_NS, current_native, native_inventory_matches_cp
from openpilot.starpilot.aol.wire import SafetyState, decode_intent as decode_intent from openpilot.starpilot.aol.wire import SafetyState, decode_intent as decode_intent
@@ -122,6 +123,7 @@ class TransportPauseFeedback:
self.subaru_main_retained_native_ns = 0 self.subaru_main_retained_native_ns = 0
self.volkswagen_reverse_retained_native_ns = 0 self.volkswagen_reverse_retained_native_ns = 0
self.honda_eps_retained_native_ns = 0 self.honda_eps_retained_native_ns = 0
self.mazda_restriction_native_ns = 0
self.fit_eps_intent = self.fit_eps_grant = None self.fit_eps_intent = self.fit_eps_grant = None
self.subaru_eps_brake_event_ns = 0 self.subaru_eps_brake_event_ns = 0
self.hkg_eps_join_until_ns = 0 self.hkg_eps_join_until_ns = 0
@@ -302,6 +304,7 @@ class TransportPauseFeedback:
return native return native
def _ordinary_warning_intent_current(self, sm, cp, cs, axis, stamp, now_ns, *, latched, producer): def _ordinary_warning_intent_current(self, sm, cp, cs, axis, stamp, now_ns, *, latched, producer):
from opendbc.car.hyundai.classic_scc_aol import qualified as stock_classic_qualified
from openpilot.starpilot.aol.vehicle import policy_for from openpilot.starpilot.aol.vehicle import policy_for
from openpilot.starpilot.nostalgia import physical_cancel from openpilot.starpilot.nostalgia import physical_cancel
@@ -335,7 +338,14 @@ class TransportPauseFeedback:
released_brake = bool(self.ordinary_warning_retained and not cs.brakePressed and not cs.regenBraking and released_brake = bool(self.ordinary_warning_retained and not cs.brakePressed and not cs.regenBraking and
brake_proof is not None and brake_proof[0] == event_ns and brake_proof is not None and brake_proof[0] == event_ns and
brake_proof[2:] == (self.session, producer, self.availability_epoch) and now_ns <= brake_proof[1]) brake_proof[2:] == (self.session, producer, self.availability_epoch) and now_ns <= brake_proof[1])
stock_main_off = bool(self.lateral_only_baseline and cp.brand == 'hyundai' and not policy.cruise_main_required and
(warning or recovering or pending) and not cs.cruiseState.available and not cs.cruiseState.enabled and
not cs.brakePressed and not cs.regenBraking and not cs.buttonEvents and
not axis.desiredLongitudinal and not axis.longitudinalActive and
all(not event.softDisable or event.name == log.OnroadEvent.EventName.selfdrivedLagging for event in events) and
stock_classic_qualified(cp, marked_only=True))
if any(event.userDisable and event.name != stock_user and not ( if any(event.userDisable and event.name != stock_user and not (
event.name == log.OnroadEvent.EventName.wrongCarMode and stock_main_off and not event.softDisable or
event.name == log.OnroadEvent.EventName.pedalPressed and (cs.brakePressed or cs.regenBraking or released_brake) or event.name == log.OnroadEvent.EventName.pedalPressed and (cs.brakePressed or cs.regenBraking or released_brake) or
event.name == log.OnroadEvent.EventName.buttonCancel and (physical_cancel(cs, cp) or event.name == log.OnroadEvent.EventName.buttonCancel and (physical_cancel(cs, cp) or
cp.brand == 'gm' and 0 < self.gm_withdrawal_ns == event_ns <= now_ns and cp.brand == 'gm' and 0 < self.gm_withdrawal_ns == event_ns <= now_ns and
@@ -556,90 +566,8 @@ class TransportPauseFeedback:
return True return True
def _temporary_lag_intent_current(self, sm, cp, cs, axis, stamp, now_ns, *, latched, producer, signature): def _temporary_lag_intent_current(self, sm, cp, cs, axis, stamp, now_ns, *, latched, producer, signature):
reason = str(axis.faultReason) return temporary_lag_intent_current(self, sm, cp, cs, axis, stamp, now_ns, latched=latched, producer=producer,
events = sm['onroadEvents'] signature=signature, healthy_native=_healthy_transport_native, stock_user_event=stock_lateral_user_event)
faults = [event for event in events if event.immediateDisable or event.softDisable]
isolated = bool(len(faults) == 1 and faults[0].name == log.OnroadEvent.EventName.selfdrivedLagging and
faults[0].softDisable and not faults[0].immediateDisable)
recovering = bool(cp.brand == 'gm' and not faults and reason == 'none' and
0 < self.lag_withdrawal_ns <= now_ns <= self.lag_withdrawal_ns + SAFETY_MAX_AGE_NS and
axis.desiredLateral and not axis.lateralActive and axis.nativeAcknowledged and
not axis.desiredLongitudinal and not axis.longitudinalActive)
if not recovering and not isolated and (reason != 'critical' or faults):
return False
previous = self.signature
joining = bool(self.pending_event and previous is not None and previous[5] == 'critical' and previous[6] == self.pending_event)
if (not latched or self.failed or self.paused or self.pending_event and not joining or self.retention_started_ns or
not self.session or str(axis.sessionId) != self.session or reason not in ('none', 'critical') or
not producer or producer != self.availability_producer or
str(getattr(axis, 'intentProducerSessionId', '')) != producer or
int(getattr(axis, 'intentIntegrityEpoch', 0)) != self.availability_epoch or
not self.lateral_baseline_ns or not self.lateral_inventory or
not cs.canValid or cs.canTimeout or cs.steerFaultTemporary or cs.steerFaultPermanent or cs.accFaulted or
not 0 < axis.sourceCarStateMonoTime <= stamp <= now_ns or
now_ns - axis.sourceCarStateMonoTime > AXIS_MAX_AGE_NS):
return False
event_ns = int(sm.logMonoTime['onroadEvents'])
if (not sm.seen['onroadEvents'] or not sm.valid['onroadEvents'] or not sm.alive['onroadEvents'] or
not 0 < event_ns <= now_ns or now_ns - event_ns > 1_500_000_000 or
joining and (axis.faultEventMonoTime != self.pending_event or now_ns - self.pending_event > AXIS_MAX_AGE_NS)):
return False
withdrawn = bool(reason == 'critical' and not axis.desiredLateral and not axis.desiredLongitudinal and
not axis.lateralActive and not axis.longitudinalActive)
matched = bool(withdrawn and isolated and axis.faultEventMonoTime == event_ns <= stamp)
held_original = bool(reason == 'none' and isolated and signature == previous and
axis.desiredLateral and axis.lateralActive and axis.nativeAcknowledged and
0 < axis.faultEventMonoTime < event_ns and now_ns - event_ns <= AXIS_MAX_AGE_NS)
known_lag = bool(isolated and previous is not None and previous[5] == 'critical' and previous[6] == event_ns)
pending = bool(withdrawn and event_ns < axis.faultEventMonoTime <= stamp and
now_ns - axis.faultEventMonoTime <= AXIS_MAX_AGE_NS and
(joining or known_lag or not faults and previous is not None and previous[5] == 'none' and
0 <= now_ns - self.lateral_baseline_ns <= AXIS_MAX_AGE_NS))
if not (matched or held_original or pending or recovering):
return False
from openpilot.starpilot.aol.vehicle import policy_for
if not policy_for(cp).intent_supported:
return False
native = _healthy_transport_native(sm, cp, cs, self.session, now_ns)
if native is None and cp.brand == 'ford':
from openpilot.starpilot.car.ford.gas_override import healthy_gas_transport_native
native = healthy_gas_transport_native(sm, cp, cs, self.session, now_ns)
if (native is None or not native.pandaInventory or
held_original and not (native.requestedLateral and native.lateralAllowed) or
native.observedMonoTime < self.lateral_native_ns or
(native.pandaSerial, tuple(p.hardwareSerial for p in native.pandaInventory)) != self.lateral_inventory):
return False
users = [event for event in events if event.userDisable]
if users:
from opendbc.car.gm.values import is_volt_sdgm_accepted_envelope, is_bolt_pedal_profile
from openpilot.starpilot.nostalgia import physical_cancel
gm_pedal = bool(self.lateral_only_baseline and (is_volt_sdgm_accepted_envelope(cp) or is_bolt_pedal_profile(cp)) and
(cs.brakePressed or cs.regenBraking) and cs.cruiseState.available and
not cs.doorOpen and not cs.seatbeltUnlatched and not cs.steeringDisengage and not physical_cancel(cs, cp) and
not axis.desiredLongitudinal and not axis.longitudinalActive and
not native.requestedLongitudinal and not native.longitudinalAllowed and
all(event.name == log.OnroadEvent.EventName.pedalPressed and event.noEntry and not event.softDisable and not event.immediateDisable for event in users))
stock_user = stock_lateral_user_event(cp)
gm_stock_withdrawal = bool(cp.brand == 'gm' and cp.pcmCruise and self.lateral_only_baseline and
(withdrawn or recovering) and cs.cruiseState.available and not cs.cruiseState.enabled and
not cs.brakePressed and not cs.regenBraking and not cs.gasPressed and
not cs.doorOpen and not cs.seatbeltUnlatched and not cs.steeringDisengage and
not physical_cancel(cs, cp) and not native.requestedLateral and not native.lateralAllowed and
not native.requestedLongitudinal and not native.longitudinalAllowed and
all(event.name == stock_user and not event.softDisable and not event.immediateDisable for event in users))
if not gm_pedal and not gm_stock_withdrawal and (not getattr(self, 'lateral_only_baseline', False) or stock_user is None or
any(event.name != stock_user or event.softDisable or event.immediateDisable for event in users) or
not stock_lateral_off(cp, cs, native)):
return False
if pending:
if not self.pending_event:
self.pending_event = int(axis.faultEventMonoTime)
self.awaiting = True
elif joining:
self.pending_event = 0
if matched and cp.brand == 'gm':
self.lag_withdrawal_ns = stamp
return True
def _ford_gas_release_eps_join_current(self, sm, cp, cs, axis, stamp, now_ns, *, producer, latched): def _ford_gas_release_eps_join_current(self, sm, cp, cs, axis, stamp, now_ns, *, producer, latched):
from openpilot.starpilot.car.ford.aol import temporary_eps_restriction from openpilot.starpilot.car.ford.aol import temporary_eps_restriction
@@ -689,6 +617,10 @@ class TransportPauseFeedback:
def _temporary_steering_intent_current(self, sm, cp, cs, axis, stamp, now_ns, *, latched, producer, signature): def _temporary_steering_intent_current(self, sm, cp, cs, axis, stamp, now_ns, *, latched, producer, signature):
from openpilot.starpilot.aol.temporary_steering import temporary_steering_intent_current from openpilot.starpilot.aol.temporary_steering import temporary_steering_intent_current
if cp.brand == 'mazda' and axis.lateralActive:
from openpilot.starpilot.car.mazda.aol import retain_pending_restriction
if retain_pending_restriction(self, sm, cp, cs, axis, stamp, now_ns, latched=latched, producer=producer):
return True
return temporary_steering_intent_current(self, sm, cp, cs, axis, stamp, now_ns, return temporary_steering_intent_current(self, sm, cp, cs, axis, stamp, now_ns,
latched=latched, producer=producer, signature=signature) latched=latched, producer=producer, signature=signature)
@@ -1256,6 +1188,7 @@ class TransportPauseFeedback:
self.volkswagen_brake_event = None self.volkswagen_brake_event = None
self.ordinary_warning_pending_baseline = None self.ordinary_warning_pending_baseline = None
self.temporary_eps_event_ns = 0 self.temporary_eps_event_ns = 0
self.mazda_restriction_ns = 0
self.hkg_eps_join_until_ns = 0 self.hkg_eps_join_until_ns = 0
self.ccnc_main_off_source_ns = 0 self.ccnc_main_off_source_ns = 0
self.cold_park_waiting = False self.cold_park_waiting = False
@@ -1469,6 +1402,11 @@ class TransportPauseFeedback:
latched=latched, producer=intent_producer_session, signature=signature): latched=latched, producer=intent_producer_session, signature=signature):
self.sequence, self.signature = int(axis.sequence), signature self.sequence, self.signature = int(axis.sequence), signature
return False return False
if cp.brand == 'mazda' and not axis.lateralActive and current and continuity:
from openpilot.starpilot.car.mazda.aol import retain_pending_restriction
if retain_pending_restriction(self, sm, cp, cs, axis, stamp, now_ns, latched=latched, producer=intent_producer_session):
self.sequence, self.signature = int(axis.sequence), signature
return False
if cp.brand == 'honda' and current and continuity: if cp.brand == 'honda' and current and continuity:
from openpilot.starpilot.aol.temporary_steering import honda_eps_recovery_intent_current from openpilot.starpilot.aol.temporary_steering import honda_eps_recovery_intent_current
if honda_eps_recovery_intent_current(self, sm, cp, cs, axis, stamp, now_ns, latched=latched, producer=intent_producer_session): if honda_eps_recovery_intent_current(self, sm, cp, cs, axis, stamp, now_ns, latched=latched, producer=intent_producer_session):
@@ -1760,6 +1698,7 @@ class TransportPauseFeedback:
self.cold_main_sparse_waiting = False self.cold_main_sparse_waiting = False
self.cold_park_waiting = False self.cold_park_waiting = False
self.temporary_eps_event_ns = 0 self.temporary_eps_event_ns = 0
self.mazda_restriction_ns = 0
self.lateral_native_ns = int(native.observedMonoTime) self.lateral_native_ns = int(native.observedMonoTime)
self.lateral_inventory = (native.pandaSerial, tuple(p.hardwareSerial for p in native.pandaInventory)) self.lateral_inventory = (native.pandaSerial, tuple(p.hardwareSerial for p in native.pandaInventory))
else: else:
@@ -1,7 +1,7 @@
"""EV6 configured AOL desire gated by actual physical authorization.""" """EV6 configured AOL desire gated by actual physical authorization."""
from opendbc.car.hyundai.values import Buttons from opendbc.car.hyundai.values import Buttons
from opendbc.car.hyundai.ev6_aol import Ev6PhysicalAuthorization from opendbc.car.hyundai.ev6_aol import Ev6PhysicalAuthorization
from openpilot.starpilot.aol.intent import AolCardIntent, AOL_TOGGLE, ButtonType from openpilot.starpilot.aol.intent import AolCardIntent, AOL_TOGGLE, ButtonType, PAUSE_LATERAL, PAUSE_LONGITUDINAL
class StockEv6CardIntent(AolCardIntent): class StockEv6CardIntent(AolCardIntent):
@@ -90,6 +90,9 @@ class Ev6CardIntent(AolCardIntent):
self._full_engagement_release_ns = 0 self._full_engagement_release_ns = 0
lkas_managed = self.settings.enabled and self.settings.lkas_action == AOL_TOGGLE lkas_managed = self.settings.enabled and self.settings.lkas_action == AOL_TOGGLE
main_managed = self.settings.main_action == AOL_TOGGLE main_managed = self.settings.main_action == AOL_TOGGLE
lkas_consumed = int(ButtonType.lkas) in consumed_buttons
lkas_toggle = not lkas_consumed and (lkas_managed or self.settings.default_lkas_toggle)
lkas_axis_action = not lkas_consumed and (lkas_toggle or self.settings.lkas_action in (PAUSE_LATERAL, PAUSE_LONGITUDINAL))
auto_main = self.settings.enabled and not lkas_managed and not main_managed auto_main = self.settings.enabled and not lkas_managed and not main_managed
if healthy and not rejected: if healthy and not rejected:
for main, lkas, cruise in self._samples: for main, lkas, cruise in self._samples:
@@ -103,11 +106,11 @@ class Ev6CardIntent(AolCardIntent):
self._raw_neutral_seen = not (main or lkas) and cruise == Buttons.NONE self._raw_neutral_seen = not (main or lkas) and cruise == Buttons.NONE
continue continue
self.physical.observe(main, lkas, cruise, main_available=CS.cruiseState.available, self.physical.observe(main, lkas, cruise, main_available=CS.cruiseState.available,
lkas_toggle=not self.settings.lkas_wheel_action) lkas_toggle=lkas_toggle)
main_press = bool(main and not previous_main) main_press = bool(main and not previous_main)
# A remapped LKAS press belongs to WheelPublisher, not the AOL owner. # A remapped LKAS press belongs to WheelPublisher, not the AOL owner.
# Keep raw level history but neither grant nor revoke physical authority. # Keep raw level history but neither grant nor revoke physical authority.
lkas_press = bool(lkas and not previous_lkas and not self.settings.lkas_wheel_action) lkas_press = bool(lkas and not previous_lkas and lkas_axis_action)
self._engagement_manual_withdrawal |= main_press or lkas_press self._engagement_manual_withdrawal |= main_press or lkas_press
engagement_release = (self.physical.lkas_on_engage and cruise != previous_cruise engagement_release = (self.physical.lkas_on_engage and cruise != previous_cruise
and previous_cruise in (Buttons.SET_DECEL, Buttons.RES_ACCEL)) and previous_cruise in (Buttons.SET_DECEL, Buttons.RES_ACCEL))
@@ -317,7 +317,7 @@ class RedneckCruise:
if state is not None: if state is not None:
target = slc_target_kph(state.presentationAdjustedLimit, card.is_metric) target = slc_target_kph(state.presentationAdjustedLimit, card.is_metric)
minimum = get_minimum_set_speed(card.is_metric) * (1. if card.is_metric else CV.MPH_TO_KPH) minimum = get_minimum_set_speed(card.is_metric) * (1. if card.is_metric else CV.MPH_TO_KPH)
if minimum <= target < helper.v_cruise_kph: if minimum <= target and target != helper.v_cruise_kph:
helper.apply_slc_target(state.presentationAdjustedLimit, card.is_metric) helper.apply_slc_target(state.presentationAdjustedLimit, card.is_metric)
def update(self, card, cs, cc, now_ns): def update(self, card, cs, cc, now_ns):
+47
View File
@@ -72,3 +72,50 @@ def expected_stopped_lateral_denial(cp, state, native, *, sm, axis_session_id, n
native is not None and native.pandaInventory and native.requestedLateral and not native.lateralAllowed and native is not None and native.pandaInventory and native.requestedLateral and not native.lateralAllowed and
not native.requestedLongitudinal and not native.longitudinalAllowed and not native.requestedLongitudinal and not native.longitudinalAllowed and
_configured_transport_native(sm, cp, axis_session_id, now_ns, native, allow_restricted_lateral=True) == native) _configured_transport_native(sm, cp, axis_session_id, now_ns, native, allow_restricted_lateral=True) == native)
def retain_pending_restriction(feedback, sm, cp, state, axis, stamp, now_ns, *, latched, producer):
"""Retain intent across a physical restriction and its pending LAT grant."""
from openpilot.cereal import log
from openpilot.starpilot.aol.runtime import AXIS_MAX_AGE_NS, SAFETY_MAX_AGE_NS
from openpilot.starpilot.aol.transport_pause import _configured_transport_native
prior = feedback.signature
physical = state.steerFaultTemporary or state.standstill
eps_on_previous_grant = bool(state.steerFaultTemporary and axis.lateralActive and
axis.desiredLateral and axis.nativeAcknowledged and str(axis.mode) == 'lateralOnly' and
prior is not None and prior[9] and prior[11] and prior[13] and not prior[10] and not prior[12] and
0 < prior[8] <= prior[2] <= now_ns <= prior[4])
restricted_ns = getattr(feedback, 'mazda_restriction_ns', 0)
if (not latched or feedback.failed or feedback.paused or feedback.pending_event or feedback.retention_started_ns or
not qualified(cp, marked_only=True) or not state.canValid or state.canTimeout or state.steerFaultPermanent or
state.gearShifter != structs.CarState.GearShifter.drive or not state.cruiseState.available or
state.accFaulted or state.doorOpen or state.seatbeltUnlatched or state.vehicleSensorsInvalid or
state.steeringDisengage or state.buttonEvents or state.regenBraking or
not (physical or 0 < restricted_ns <= now_ns <= restricted_ns + SAFETY_MAX_AGE_NS) or
prior is None or not producer or prior[14:16] != (producer, int(axis.intentIntegrityEpoch)) or axis.intentProducerSessionId != producer or
prior[5] != 'none' or str(axis.faultReason) != 'none' or
not feedback.session or axis.sessionId != feedback.session or not feedback.healthy_inventory or
axis.lateralActive and not eps_on_previous_grant or axis.desiredLongitudinal or axis.longitudinalActive or
not 0 < prior[8] <= axis.sourceCarStateMonoTime <= stamp <= now_ns or
now_ns - axis.sourceCarStateMonoTime > AXIS_MAX_AGE_NS):
return False
event_ns = int(sm.logMonoTime['onroadEvents'])
names = log.OnroadEvent.EventName
if (not sm.seen['onroadEvents'] or not sm.valid['onroadEvents'] or not sm.alive['onroadEvents'] or
not 0 < event_ns <= now_ns or now_ns - event_ns > 1_500_000_000 or
any(e.immediateDisable or e.softDisable and e.name != names.steerTempUnavailable or
e.userDisable and not (e.name == names.pcmDisable and not state.cruiseState.enabled or
e.name == names.pedalPressed and state.brakePressed and not state.gasPressed)
for e in sm['onroadEvents'])):
return False
native = _configured_transport_native(sm, cp, feedback.session, now_ns, allow_restricted_lateral=True)
if (native is None or not native.pandaInventory or native.requestedLongitudinal or native.longitudinalAllowed or
eps_on_previous_grant and not native.requestedLateral or
native.observedMonoTime < feedback.healthy_native_ns or
(native.pandaSerial, tuple(p.hardwareSerial for p in native.pandaInventory)) != feedback.healthy_inventory):
return False
feedback.mazda_restriction_native_ns = int(native.observedMonoTime)
if physical:
feedback.mazda_restriction_ns = now_ns
return True
@@ -158,13 +158,15 @@ def retain_paddle_denial(feedback, sm, cp, state, axis, stamp, now_ns, *, latche
now_ns - axis.sourceCarStateMonoTime > AXIS_MAX_AGE_NS or now_ns - axis.sourceCarStateMonoTime > AXIS_MAX_AGE_NS or
not state.canValid or state.canTimeout or state.steerFaultTemporary or state.steerFaultPermanent or not state.canValid or state.canTimeout or state.steerFaultTemporary or state.steerFaultPermanent or
state.accFaulted or state.vehicleSensorsInvalid or state.doorOpen or state.seatbeltUnlatched or state.accFaulted or state.vehicleSensorsInvalid or state.doorOpen or state.seatbeltUnlatched or
state.steeringDisengage or state.buttonEvents or not state.cruiseState.available or state.cruiseState.enabled): state.steeringDisengage or state.gasPressed or state.regenBraking or state.buttonEvents or
not state.cruiseState.available or state.cruiseState.enabled):
return False return False
names = log.OnroadEvent.EventName names = log.OnroadEvent.EventName
event_ns = int(sm.logMonoTime['onroadEvents']) event_ns = int(sm.logMonoTime['onroadEvents'])
if (not sm.seen['onroadEvents'] or not sm.valid['onroadEvents'] or not sm.alive['onroadEvents'] or if (not sm.seen['onroadEvents'] or not sm.valid['onroadEvents'] or not sm.alive['onroadEvents'] or
not 0 < event_ns <= now_ns or now_ns - event_ns > 1_500_000_000 or not 0 < event_ns <= now_ns or now_ns - event_ns > 1_500_000_000 or
any(e.immediateDisable or e.softDisable and e.name != names.wrongGear or any(e.immediateDisable or (e.softDisable or e.noEntry) and e.name != names.wrongGear and
not (e.name == names.pedalPressed and state.brakePressed and not e.softDisable) or
e.userDisable and e.name != names.pcmDisable and not (e.name == names.pedalPressed and state.brakePressed) e.userDisable and e.name != names.pcmDisable and not (e.name == names.pedalPressed and state.brakePressed)
for e in sm['onroadEvents'])): for e in sm['onroadEvents'])):
return False return False
@@ -214,6 +214,7 @@ def test_actual_full_engage_brake_reverse_temporary_recovery_mainoff(candidate,
for addr, data, bus in incoming: for addr, data, bus in incoming:
if panda_gear_ahead and addr == 0x48 and bus == 0: if panda_gear_ahead and addr == 0x48 and bus == 0:
raw = bytearray(data) raw = bytearray(data)
assert manual_ratio is not None
raw[3] = manual_ratio raw[3] = manual_ratio
raw[0] = (0x48 + sum(raw[1:])) & 255 raw[0] = (0x48 + sum(raw[1:])) & 255
data = bytes(raw) data = bytes(raw)
@@ -1,7 +1,7 @@
"""Modern screen gesture override layered over ordinary cruise availability.""" """Modern screen gesture override layered over ordinary cruise availability."""
from dataclasses import replace from dataclasses import replace
from opendbc.car import structs from opendbc.car import structs
from openpilot.starpilot.aol.intent import AolCardIntent, ButtonType from openpilot.starpilot.aol.intent import AolCardIntent, AOL_TOGGLE, ButtonType
class TeslaScreenCardIntent(AolCardIntent): class TeslaScreenCardIntent(AolCardIntent):
@@ -45,7 +45,8 @@ class TeslaScreenCardIntent(AolCardIntent):
continue continue
fresh_press = bool(event.pressed and not self.screen_held) fresh_press = bool(event.pressed and not self.screen_held)
self.screen_held = bool(event.pressed) self.screen_held = bool(event.pressed)
if (fresh_press and CS.gearShifter == structs.CarState.GearShifter.drive and not CS.steerFaultTemporary and if (fresh_press and self.screen_toggle_mapped and int(ButtonType.lkas) not in kwargs.get('consumed_buttons', ()) and
CS.gearShifter == structs.CarState.GearShifter.drive and not CS.steerFaultTemporary and
not fault and not cancel and self.settings.enabled and not fault and not cancel and self.settings.enabled and
not (self.brake_disengage and CS.brakePressed)): not (self.brake_disengage and CS.brakePressed)):
current = (available if self.screen_override is None else self.screen_override) current = (available if self.screen_override is None else self.screen_override)
@@ -70,4 +71,5 @@ class TeslaScreenCardIntent(AolCardIntent):
@settings.setter @settings.setter
def settings(self, value): def settings(self, value):
self.screen_toggle_mapped = value.lkas_action == AOL_TOGGLE or value.default_lkas_toggle
self._settings = replace(value, lkas_action=0) self._settings = replace(value, lkas_action=0)
@@ -11,6 +11,9 @@ from openpilot.starpilot.conditional_mode.stop import FROZEN_RAW_STOP_DISTANCE_M
SOURCES = ('carState', 'carControl', 'controlsState', 'selfdriveState', 'radarState', 'modelV2') SOURCES = ('carState', 'carControl', 'controlsState', 'selfdriveState', 'radarState', 'modelV2')
MAX_AGE_NS = 150_000_000 MAX_AGE_NS = 150_000_000
CLEAR_DWELL_NS = 500_000_000 CLEAR_DWELL_NS = 500_000_000
MIN_TURN_PATH_M = 45.0
MIN_TURN_FORWARD_M = 36.0
MIN_TURN_LEAD_GAP_M = 4.0
def _supported(cp): def _supported(cp):
@@ -54,14 +57,23 @@ class StoppedLeadRelease:
self.reset() self.reset()
return False return False
extent = _standstill_path_extent(model) extent = _standstill_path_extent(model)
if extent is None or extent < max(FROZEN_RAW_STOP_DISTANCE_M, detector.commit_distance_m) + STOP_MODEL_RELEASE_MARGIN_M: turning = False
if extent is not None and car.leftBlinker != car.rightBlinker:
x, y = tuple(model.position.x), tuple(model.position.y)
if len(x) == len(y) and all(math.isfinite(v) for v in y):
turn_displacement = y[-1] - y[0]
turning = (turn_displacement * (-1 if car.leftBlinker else 1) >= 3. and
sum(math.hypot(b - a, d - c) for a, b, c, d in zip(x, x[1:], y, y[1:], strict=False)) >= MIN_TURN_PATH_M)
minimum_extent = MIN_TURN_FORWARD_M if turning else FROZEN_RAW_STOP_DISTANCE_M + STOP_MODEL_RELEASE_MARGIN_M
if extent is None or extent < max(minimum_extent, detector.commit_distance_m + STOP_MODEL_RELEASE_MARGIN_M):
self.reset() self.reset()
return False return False
velocities, times = tuple(model.velocity.x), tuple(ModelConstants.T_IDXS) velocities, times = tuple(model.velocity.x), tuple(ModelConstants.T_IDXS)
# A stationary Model Y can predict a few centimeters of reverse motion at launch. # A stationary Model Y can predict a few centimeters of reverse motion at launch.
prefix_noise = cp.carFingerprint == 'TESLA_MODEL_Y' and min(model.position.x) >= -.03 prefix_noise = cp.carFingerprint == 'TESLA_MODEL_Y' and min(model.position.x) >= -.03
prefix_min_velocity = -.09 if turning else -.08
if (len(velocities) != 33 or len(times) != 33 or if (len(velocities) != 33 or len(times) != 33 or
not all(math.isfinite(v) and (-.08 if prefix_noise and t < .2 else -.05) <= v <= 100. not all(math.isfinite(v) and (prefix_min_velocity if prefix_noise and t < .2 else -.05) <= v <= 100.
for v, t in zip(velocities, times, strict=True))): for v, t in zip(velocities, times, strict=True))):
self.reset() self.reset()
return False return False
@@ -70,26 +82,37 @@ class StoppedLeadRelease:
self.reset() self.reset()
return False return False
leads = [(slot, lead) for slot, lead in enumerate((sm['radarState'].leadOne, sm['radarState'].leadTwo)) if lead.present] leads = [(slot, lead) for slot, lead in enumerate((sm['radarState'].leadOne, sm['radarState'].leadTwo)) if lead.present]
minimum_gap = MIN_TURN_LEAD_GAP_M if turning else 6.3
if not leads or any(lead.radar and lead.radarTrackId < 0 or not all(math.isfinite(v) for v in if not leads or any(lead.radar and lead.radarTrackId < 0 or not all(math.isfinite(v) for v in
(lead.dRel, lead.vLead, lead.aLeadK, lead.yRel, lead.modelProb)) or (lead.dRel, lead.vLead, lead.aLeadK, lead.yRel, lead.modelProb)) or
not 6.3 <= lead.dRel <= 18. or lead.vLead < .6 or lead.aLeadK < -.15 or not minimum_gap <= lead.dRel <= 18. or lead.vLead < .6 or lead.aLeadK < -.15 or
abs(lead.yRel) > 1. or lead.modelProb < .95 for _, lead in leads): abs(lead.yRel) > 1. for _, lead in leads):
self.reset() self.reset()
return False return False
primary = leads[0][1]
for slot, lead in leads: for slot, lead in leads:
# The model can emit the same departing car in both temporal slots.
# A weaker duplicate still has to agree with the primary and its own projection.
duplicate = (turning and slot == 1 and leads[0][0] == 0 and not (primary.radar or lead.radar) and
all(abs(getattr(primary, field) - getattr(lead, field)) <= .25
for field in ('dRel', 'yRel', 'vLead', 'aLeadK')))
minimum_probability = .9 if duplicate else .95
if lead.modelProb < minimum_probability:
self.reset()
return False
if not lead.radar: if not lead.radar:
if lead.radarTrackId != -1: if lead.radarTrackId != -1:
self.reset() self.reset()
return False return False
source = model.leadsV3[slot] source = model.leadsV3[slot]
projected = get_RadarState_from_vision(source, car.vEgo, model.velocity.x[0], source.prob) projected = get_RadarState_from_vision(source, car.vEgo, model.velocity.x[0], source.prob)
if (source.prob < .95 or not math.isfinite(source.prob) or if (source.prob < minimum_probability or not math.isfinite(source.prob) or
any(not math.isfinite(projected[field]) or abs(projected[field] - getattr(lead, field)) > .5 any(not math.isfinite(projected[field]) or abs(projected[field] - getattr(lead, field)) > .5
for field in ('dRel', 'yRel', 'vLead', 'aLeadK'))): for field in ('dRel', 'yRel', 'vLead', 'aLeadK'))):
self.reset() self.reset()
return False return False
key = (drive_id, cp.carFingerprint, tuple((str(config.safetyModel), config.safetyParam) for config in cp.safetyConfigs), key = (drive_id, cp.carFingerprint, tuple((str(config.safetyModel), config.safetyParam) for config in cp.safetyConfigs),
tuple((slot, bool(lead.radar), lead.radarTrackId if lead.radar else -1) for slot, lead in leads)) turning, tuple((slot, bool(lead.radar), lead.radarTrackId if lead.radar else -1) for slot, lead in leads))
stamp = int(sm.logMonoTime['modelV2']) stamp = int(sm.logMonoTime['modelV2'])
if (key != self.key or not self.last_ns < now_ns <= self.last_ns + MAX_AGE_NS or stamp <= self.model_ns): if (key != self.key or not self.last_ns < now_ns <= self.last_ns + MAX_AGE_NS or stamp <= self.model_ns):
self.reset() self.reset()
@@ -191,3 +191,41 @@ def test_departure_tolerates_only_bounded_model_y_prefix_noise(fingerprint, slot
results.append(owner.sample(sm, cp, planner, detector, now_ns=now, drive_id=green.MONO-1_000_000_000)) results.append(owner.sample(sm, cp, planner, detector, now_ns=now, drive_id=green.MONO-1_000_000_000))
assert not any(results[:10]) assert not any(results[:10])
assert results[10:] == [clear] * 3 assert results[10:] == [clear] * 3
@pytest.mark.parametrize('case', ('matched-turn', 'duplicate', 'distinct', 'weak-primary', 'prefix-noise', 'large-prefix',
'opposite-signal', 'no-signal', 'short-path', 'no-lead', 'model-stop', 'native-stop'))
def test_shorter_turn_path_can_release_only_with_matching_lead_and_no_stop(case):
cp = CarParams(openpilotLongitudinalControl=True, carFingerprint='TESLA_MODEL_Y')
owner = StoppedLeadRelease()
detector = SimpleNamespace(committed=True, standstill_committed=True, standstill_reason='light', commit_distance_m=5.)
planner = SimpleNamespace(mpc=SimpleNamespace(solution_status=0), output_should_stop=case == 'native-stop', output_a_target=.5,
force_stop_plan=SimpleNamespace(forcing=False, should_stop=False))
results = []
for tick in range(13):
now = green.MONO + 1_000_000_000 + tick * 50_000_000
sm = scene(now, True)
car, model = sm['carState'], sm['modelV2']
car.leftBlinker, car.rightBlinker = case not in ('no-signal', 'opposite-signal'), case == 'opposite-signal'
path = list(model.position.x)
forward = 25. if case == 'short-path' else 43.
model.position.x = [x * forward / path[-1] for x in path]
model.position.y = [-x * 20. / path[-1] for x in path]
if case in ('prefix-noise', 'large-prefix'):
xs, velocities = list(model.position.x), list(model.velocity.x)
xs[4], velocities[4] = -.027, -.085 if case == 'prefix-noise' else -.091
model.position.x, model.velocity.x = xs, velocities
model.action.shouldStop = case == 'model-stop'
for slot, lead in enumerate((sm['radarState'].leadOne, sm['radarState'].leadTwo)):
if lead.present:
raw = model.leadsV3[slot]
offset = .4 if case == 'distinct' and slot == 1 else 0.
raw.x = [x - raw.x[0] + 6.02 + offset for x in raw.x]
if (case in ('duplicate', 'distinct') and slot == 1) or (case == 'weak-primary' and slot == 0):
raw.prob = .92
lead.from_dict(get_RadarState_from_vision(raw, car.vEgo, model.velocity.x[0], raw.prob))
if case == 'no-lead':
lead.present = False
results.append(owner.sample(sm, cp, planner, detector, now_ns=now, drive_id=green.MONO-1_000_000_000))
assert not any(results[:10])
assert results[10:] == [case in ('matched-turn', 'duplicate', 'prefix-noise')] * 3
+5 -1
View File
@@ -213,7 +213,7 @@ def restore_snapshot(controller, vm, snapshot):
setattr(obj, name, _decode(values, path, old)) setattr(obj, name, _decode(values, path, old))
def frame_input(cs, vm, params, *, active, safety_limited, desired_curvature, curvature_limited, lat_delay): def frame_input(cs, vm, params, *, active, safety_limited, desired_curvature, curvature_limited, lat_delay, capture_turn_signals=False):
values = [(name, _numeric(getattr(cs, name))) for name in _CS_FIELDS] values = [(name, _numeric(getattr(cs, name))) for name in _CS_FIELDS]
values += [ values += [
('gearShifter', float(cs.gearShifter.raw if hasattr(cs.gearShifter, 'raw') else int(cs.gearShifter))), ('gearShifter', float(cs.gearShifter.raw if hasattr(cs.gearShifter, 'raw') else int(cs.gearShifter))),
@@ -226,6 +226,8 @@ def frame_input(cs, vm, params, *, active, safety_limited, desired_curvature, cu
('lat_delay', _numeric(lat_delay)), ('lat_delay', _numeric(lat_delay)),
] ]
values += [('vm.' + name, _numeric(getattr(vm, name))) for name in _VM_FIELDS] values += [('vm.' + name, _numeric(getattr(vm, name))) for name in _VM_FIELDS]
if capture_turn_signals:
values.extend((('leftBlinker', bool(cs.leftBlinker)), ('rightBlinker', bool(cs.rightBlinker))))
if len(values) > MAX_FRAME_VALUES: if len(values) > MAX_FRAME_VALUES:
raise ValueError('frame primitive budget') raise ValueError('frame primitive budget')
return tuple(values) return tuple(values)
@@ -436,6 +438,8 @@ def _car_state(values, *, first_segment_words=None):
for name in _CS_FIELDS: for name in _CS_FIELDS:
setattr(cs, name, bool(values[name]) if name in ('steeringPressed', 'standstill', 'steerFaultTemporary', 'steerFaultPermanent') else values[name]) setattr(cs, name, bool(values[name]) if name in ('steeringPressed', 'standstill', 'steerFaultTemporary', 'steerFaultPermanent') else values[name])
cs.gearShifter = int(values['gearShifter']) cs.gearShifter = int(values['gearShifter'])
cs.leftBlinker = bool(values.get('leftBlinker', False))
cs.rightBlinker = bool(values.get('rightBlinker', False))
return cs return cs
@@ -671,6 +671,7 @@ class GlobalRuntime:
desired_curvature=desired_curvature, desired_curvature=desired_curvature,
curvature_limited=curvature_limited, curvature_limited=curvature_limited,
lat_delay=lat_delay, lat_delay=lat_delay,
capture_turn_signals=getattr(self.controller, "accord_center_friction", False),
) + ( ) + (
('control_frame', float(self.frame_sequence)), ('control_frame', float(self.frame_sequence)),
('raw_model_curvature', float(raw_model_curvature)), ('raw_model_curvature', float(raw_model_curvature)),
@@ -114,6 +114,7 @@ SEQUENCE = (
class TestIoniq6ControllerReplay(unittest.TestCase): class TestIoniq6ControllerReplay(unittest.TestCase):
@mock.patch("openpilot.starpilot.lateral.ioniq6_policy.IONIQ_6_STANDARD_HIGHWAY_TRANSITION_EXTRA_TAPER", 0.0)
@mock.patch("openpilot.starpilot.lateral.ioniq6_policy.IONIQ_6_STANDARD_HIGHWAY_FRICTION_THRESHOLD_INCREASE", 0.0, create=True) @mock.patch("openpilot.starpilot.lateral.ioniq6_policy.IONIQ_6_STANDARD_HIGHWAY_FRICTION_THRESHOLD_INCREASE", 0.0, create=True)
@mock.patch("openpilot.starpilot.lateral.ioniq6_policy.IONIQ_6_STANDARD_FRICTION_THRESHOLD_INCREASE", 0.0) @mock.patch("openpilot.starpilot.lateral.ioniq6_policy.IONIQ_6_STANDARD_FRICTION_THRESHOLD_INCREASE", 0.0)
def test_frozen_stateful_controller_trace(self): def test_frozen_stateful_controller_trace(self):
@@ -130,6 +131,7 @@ class TestIoniq6ControllerReplay(unittest.TestCase):
_assert_rows(self, actual, expected) _assert_rows(self, actual, expected)
@mock.patch("openpilot.starpilot.lateral.ioniq6_policy.IONIQ_6_2025_HIGHWAY_FRICTION_THRESHOLD_INCREASE", 0.0) @mock.patch("openpilot.starpilot.lateral.ioniq6_policy.IONIQ_6_2025_HIGHWAY_FRICTION_THRESHOLD_INCREASE", 0.0)
@mock.patch("openpilot.starpilot.lateral.ioniq6_policy.IONIQ_6_STANDARD_HIGHWAY_TRANSITION_EXTRA_TAPER", 0.0)
@mock.patch("openpilot.starpilot.lateral.ioniq6_policy.IONIQ_6_STANDARD_HIGHWAY_FRICTION_THRESHOLD_INCREASE", 0.0, create=True) @mock.patch("openpilot.starpilot.lateral.ioniq6_policy.IONIQ_6_STANDARD_HIGHWAY_FRICTION_THRESHOLD_INCREASE", 0.0, create=True)
@mock.patch("openpilot.starpilot.lateral.ioniq6_policy.IONIQ_6_STANDARD_FRICTION_THRESHOLD_INCREASE", 0.0) @mock.patch("openpilot.starpilot.lateral.ioniq6_policy.IONIQ_6_STANDARD_FRICTION_THRESHOLD_INCREASE", 0.0)
def test_extended_frozen_filter_limit_override_and_reset_trace(self): def test_extended_frozen_filter_limit_override_and_reset_trace(self):
@@ -152,6 +154,7 @@ class TestIoniq6ControllerReplay(unittest.TestCase):
_assert_rows(self, actual, expected) _assert_rows(self, actual, expected)
@mock.patch("openpilot.starpilot.lateral.ioniq6_policy.IONIQ_6_2025_HIGHWAY_FRICTION_THRESHOLD_INCREASE", 0.0) @mock.patch("openpilot.starpilot.lateral.ioniq6_policy.IONIQ_6_2025_HIGHWAY_FRICTION_THRESHOLD_INCREASE", 0.0)
@mock.patch("openpilot.starpilot.lateral.ioniq6_policy.IONIQ_6_STANDARD_HIGHWAY_TRANSITION_EXTRA_TAPER", 0.0)
@mock.patch("openpilot.starpilot.lateral.ioniq6_policy.IONIQ_6_STANDARD_HIGHWAY_FRICTION_THRESHOLD_INCREASE", 0.0, create=True) @mock.patch("openpilot.starpilot.lateral.ioniq6_policy.IONIQ_6_STANDARD_HIGHWAY_FRICTION_THRESHOLD_INCREASE", 0.0, create=True)
@mock.patch("openpilot.starpilot.lateral.ioniq6_policy.IONIQ_6_STANDARD_FRICTION_THRESHOLD_INCREASE", 0.0) @mock.patch("openpilot.starpilot.lateral.ioniq6_policy.IONIQ_6_STANDARD_FRICTION_THRESHOLD_INCREASE", 0.0)
def test_actual_torque_parameter_update_recalculates_frozen_pid_limits(self): def test_actual_torque_parameter_update_recalculates_frozen_pid_limits(self):
@@ -173,6 +176,7 @@ class TestIoniq6ControllerReplay(unittest.TestCase):
_assert_rows(self, actual, expected["rows"]) _assert_rows(self, actual, expected["rows"])
@mock.patch("openpilot.starpilot.lateral.ioniq6_policy.IONIQ_6_2025_HIGHWAY_FRICTION_THRESHOLD_INCREASE", 0.0) @mock.patch("openpilot.starpilot.lateral.ioniq6_policy.IONIQ_6_2025_HIGHWAY_FRICTION_THRESHOLD_INCREASE", 0.0)
@mock.patch("openpilot.starpilot.lateral.ioniq6_policy.IONIQ_6_STANDARD_HIGHWAY_TRANSITION_EXTRA_TAPER", 0.0)
@mock.patch("openpilot.starpilot.lateral.ioniq6_policy.IONIQ_6_STANDARD_HIGHWAY_FRICTION_THRESHOLD_INCREASE", 0.0, create=True) @mock.patch("openpilot.starpilot.lateral.ioniq6_policy.IONIQ_6_STANDARD_HIGHWAY_FRICTION_THRESHOLD_INCREASE", 0.0, create=True)
@mock.patch("openpilot.starpilot.lateral.ioniq6_policy.IONIQ_6_STANDARD_FRICTION_THRESHOLD_INCREASE", 0.0) @mock.patch("openpilot.starpilot.lateral.ioniq6_policy.IONIQ_6_STANDARD_FRICTION_THRESHOLD_INCREASE", 0.0)
def test_guarded_extended_trace_preserves_model_pid_inputs_and_manual_surface(self): def test_guarded_extended_trace_preserves_model_pid_inputs_and_manual_surface(self):
@@ -791,198 +791,6 @@ class TestOffroadStore(unittest.TestCase):
self.assertEqual(startup_row(params, scope())[0]['values'], values()) self.assertEqual(startup_row(params, scope())[0]['values'], values())
class TestOffroadReport(unittest.TestCase):
def test_lapped_parked_subscriber_waits_for_real_freshness_and_preserves_safety_refusals(self):
from types import SimpleNamespace
from openpilot.starpilot.flm.offroad_daemon import parked_status, wait_for_parked
def fixture(refresh=True):
now = [100.0]
flags = {'IsOffroad': True, 'IsEngaged': False}
params = SimpleNamespace(get_bool=lambda key: flags[key])
class Messages:
def __init__(self):
self.data = {
'deviceState': SimpleNamespace(started=False),
'pandaStates': [SimpleNamespace(ignitionLine=False, ignitionCan=False, controlsAllowed=False, faults=[])],
'peripheralState': SimpleNamespace(),
}
self.seen = dict.fromkeys(self.data, True)
self.alive = dict.fromkeys(self.data, True)
self.valid = dict.fromkeys(self.data, True)
self.recv_time = dict.fromkeys(self.data, now[0])
self.alive['pandaStates'] = False
self.recv_time['pandaStates'] = 97.0
self.calls = []
def __getitem__(self, service):
return self.data[service]
def update(self, timeout):
self.calls.append(timeout)
now[0] += timeout / 1000
if timeout and refresh:
self.alive['pandaStates'] = True
self.recv_time['pandaStates'] = now[0]
return now, flags, params, Messages()
now, _, params, sm = fixture()
self.assertFalse(parked_status(sm, params, now=now[0]))
self.assertTrue(wait_for_parked(sm, params, clock=lambda now=now: now[0]))
self.assertEqual(sm.calls, [0, 20])
self.assertTrue(parked_status(sm, params, now=now[0]))
for unavailable in ('no_new_message', 'invalid', 'unseen'):
with self.subTest(unavailable=unavailable):
now, _, params, sm = fixture(refresh=unavailable != 'no_new_message')
if unavailable == 'invalid':
sm.valid['pandaStates'] = False
elif unavailable == 'unseen':
sm.seen['pandaStates'] = False
self.assertFalse(wait_for_parked(sm, params, clock=lambda now=now: now[0]))
self.assertLessEqual(now[0], 100.8)
self.assertLessEqual(len(sm.calls), 40)
for unsafe in ('onroad', 'engaged', 'started', 'ignition', 'controls', 'fault', 'stopped'):
with self.subTest(unsafe=unsafe):
now, flags, params, sm = fixture()
if unsafe == 'onroad':
flags['IsOffroad'] = False
elif unsafe == 'engaged':
flags['IsEngaged'] = True
elif unsafe == 'started':
sm['deviceState'].started = True
elif unsafe == 'ignition':
sm['pandaStates'][0].ignitionCan = True
elif unsafe == 'controls':
sm['pandaStates'][0].controlsAllowed = True
elif unsafe == 'fault':
sm['pandaStates'][0].faults.append('declared-fault')
self.assertFalse(wait_for_parked(sm, params, stopped=lambda unsafe=unsafe: unsafe == 'stopped', clock=lambda now=now: now[0]))
self.assertEqual(sm.calls, [0], 'Actual unsafe state refuses immediately instead of waiting')
def test_completed_drive_reports_every_candidate_without_claiming_application(self):
from openpilot.starpilot.flm.training_report import read_report
from openpilot.starpilot.flm.offroad_worker import qualification_summary
checks = {
'windows': [{'qualified': True}] * 22
+ [
{'qualified': False, 'numerical': {'qualified': False, 'reason': 'original_scored_frame_not_eligible'}},
{
'qualified': False,
'numerical': {'qualified': True},
'registered_encoder': {'qualified': False, 'detail': 'candidate changed an actual limiter/support'},
},
]
}
summary = qualification_summary(checks)
self.assertEqual((summary['passed'], summary['required']), (22, 24))
with tempfile.TemporaryDirectory() as directory:
path = Path(directory) / 'report.json'
report = StatusReport(path=path, clock_ns=lambda: 10_000_000_000)
names = ['highway_center_taper_max', 'turn_in_boost_left', 'unwind_taper_left', 'turn_in_boost_right', 'unwind_taper_right']
suggestions = [{'parameter': name, 'delta': 0.005, 'whole_windows': 9, 'qualification': 'controller_native_checks_not_passed'} for name in names]
recorded = {
'version': 1,
'domain': 'lateral_acceleration',
'samples': 2000,
'windows': 10,
'error_rms': 0.12,
'route': 'declared-completed-drive',
'segment': 0,
'source_start_ns': 1_000_000_000,
'source_end_ns': 2_900_000_000,
'points': [[1_000_000_000 + i * 100_000_000, 0.2, 0.08] for i in range(20)],
'sampling': 'input_ordered_original_endpoints_no_interpolation',
}
report.set(
{
'status': 'collecting',
'reason': 'recorded_tracking_suggestion_not_yet_qualified_for_automatic_application',
'completed_route': 'declared-completed-drive',
'analysis_counts': {'recorded_tracking': 241573},
'suggestions': suggestions,
'suggestion_count': len(suggestions),
'configuration_changed': False,
'recorded_tracking': recorded,
'saved_adjustments': 0,
'qualification_summary': summary,
}
)
report.publish()
current = read_report(path, now_ns=10_000_000_000)['current']
assert current is not None
self.assertEqual([r[0] for r in current['details']['Recorded route suggestions']], names)
self.assertEqual(current['details']['Recorded suggestion count'], 5)
self.assertEqual(current['progress']['samples'], 241573)
self.assertFalse(current['details']['Automatic configuration changed'])
self.assertFalse(current['application']['applied'])
self.assertFalse(current['details']['Physical road improvement proven'])
self.assertEqual(current['details']['Recorded steering response'], recorded)
self.assertEqual(current['details']['Saved route adjustment count'], 0)
self.assertEqual(current['details']['Controller and encoder check windows'], [22, 24])
self.assertEqual(
current['details']['Automatic tune refusal reasons'], [['candidate changed an actual limiter/support', 1], ['original_scored_frame_not_eligible', 1]]
)
def test_typed_current_application_and_completed_analysis_remain_distinct(self):
with tempfile.TemporaryDirectory() as directory:
now = 10_000_000_000
control = ControlEvidence(
identity='unit',
generation=1,
control_ns=now,
state_ns=now,
domain='torque',
stage_revision='',
response_revision='',
requested=0.0,
features=(),
baseline_prediction=0.0,
enabled=True,
manual=False,
active=True,
valid=True,
override=False,
fault=False,
saturated=False,
limited=False,
model_wobble=False,
controller_chatter=False,
route_applied_coordinates=tuple(values(0.01).items()),
route_effect_revision=REVISION,
route_configuration_scope='a' * 64,
)
path = Path(directory) / 'report.json'
report = StatusReport(path=path, clock_ns=lambda: now)
current = {
'status': 'collecting',
'reason': 'declared-unit',
'enabled': True,
'actual_control': control,
'actual_control_ns': now,
'actual_coordinates': control.route_applied_coordinates,
'completed_route': 'declared-unit-route',
'analysis_counts': {'recorded_tracking': 1000, 'qualified_whole_windows': 6},
}
report.set(current)
report.publish()
observed = json.loads(path.read_bytes())['current']
self.assertTrue(observed['application']['applied'])
self.assertEqual(observed['progress']['samples'], 1000)
self.assertFalse(observed['details']['Physical road improvement proven'])
for replacement in (None, replace(control, manual=True), replace(control, limited=True), replace(control, control_ns=now - 100_000_001)):
with self.subTest(control=replacement):
report.next_ns = 0
report.set(dict(current, actual_control=replacement))
report.publish()
self.assertFalse(json.loads(path.read_bytes())['current']['application']['applied'])
class TestOffroadRouteCoverage(unittest.TestCase): class TestOffroadRouteCoverage(unittest.TestCase):
def test_actual_log_metadata_preserves_only_original_inhibited_input_flags(self): def test_actual_log_metadata_preserves_only_original_inhibited_input_flags(self):
from openpilot.cereal import log, messaging from openpilot.cereal import log, messaging
@@ -0,0 +1,204 @@
"""Portable backend contracts. All observations/history here are declared unit fixtures."""
from dataclasses import replace
import json
from pathlib import Path
import tempfile
import unittest
from openpilot.starpilot.flm.fullrate_collector import ControlEvidence
from openpilot.starpilot.flm.offroad_daemon import StatusReport
from openpilot.starpilot.flm.tests.test_offroad_backend import values
from openpilot.starpilot.flm.offroad_surface import REVISION
class TestOffroadReport(unittest.TestCase):
def test_lapped_parked_subscriber_waits_for_real_freshness_and_preserves_safety_refusals(self):
from types import SimpleNamespace
from openpilot.starpilot.flm.offroad_daemon import parked_status, wait_for_parked
def fixture(refresh=True):
now = [100.0]
flags = {'IsOffroad': True, 'IsEngaged': False}
params = SimpleNamespace(get_bool=lambda key: flags[key])
class Messages:
def __init__(self):
self.data = {
'deviceState': SimpleNamespace(started=False),
'pandaStates': [SimpleNamespace(ignitionLine=False, ignitionCan=False, controlsAllowed=False, faults=[])],
'peripheralState': SimpleNamespace(),
}
self.seen = dict.fromkeys(self.data, True)
self.alive = dict.fromkeys(self.data, True)
self.valid = dict.fromkeys(self.data, True)
self.recv_time = dict.fromkeys(self.data, now[0])
self.alive['pandaStates'] = False
self.recv_time['pandaStates'] = 97.0
self.calls = []
def __getitem__(self, service):
return self.data[service]
def update(self, timeout):
self.calls.append(timeout)
now[0] += timeout / 1000
if timeout and refresh:
self.alive['pandaStates'] = True
self.recv_time['pandaStates'] = now[0]
return now, flags, params, Messages()
now, _, params, sm = fixture()
self.assertFalse(parked_status(sm, params, now=now[0]))
self.assertTrue(wait_for_parked(sm, params, clock=lambda now=now: now[0]))
self.assertEqual(sm.calls, [0, 20])
self.assertTrue(parked_status(sm, params, now=now[0]))
for unavailable in ('no_new_message', 'invalid', 'unseen'):
with self.subTest(unavailable=unavailable):
now, _, params, sm = fixture(refresh=unavailable != 'no_new_message')
if unavailable == 'invalid':
sm.valid['pandaStates'] = False
elif unavailable == 'unseen':
sm.seen['pandaStates'] = False
self.assertFalse(wait_for_parked(sm, params, clock=lambda now=now: now[0]))
self.assertLessEqual(now[0], 100.8)
self.assertLessEqual(len(sm.calls), 40)
for unsafe in ('onroad', 'engaged', 'started', 'ignition', 'controls', 'fault', 'stopped'):
with self.subTest(unsafe=unsafe):
now, flags, params, sm = fixture()
if unsafe == 'onroad':
flags['IsOffroad'] = False
elif unsafe == 'engaged':
flags['IsEngaged'] = True
elif unsafe == 'started':
sm['deviceState'].started = True
elif unsafe == 'ignition':
sm['pandaStates'][0].ignitionCan = True
elif unsafe == 'controls':
sm['pandaStates'][0].controlsAllowed = True
elif unsafe == 'fault':
sm['pandaStates'][0].faults.append('declared-fault')
self.assertFalse(wait_for_parked(sm, params, stopped=lambda unsafe=unsafe: unsafe == 'stopped', clock=lambda now=now: now[0]))
self.assertEqual(sm.calls, [0], 'Actual unsafe state refuses immediately instead of waiting')
def test_completed_drive_reports_every_candidate_without_claiming_application(self):
from openpilot.starpilot.flm.training_report import read_report
from openpilot.starpilot.flm.offroad_worker import qualification_summary
checks = {
'windows': [{'qualified': True}] * 22
+ [
{'qualified': False, 'numerical': {'qualified': False, 'reason': 'original_scored_frame_not_eligible'}},
{
'qualified': False,
'numerical': {'qualified': True},
'registered_encoder': {'qualified': False, 'detail': 'candidate changed an actual limiter/support'},
},
]
}
summary = qualification_summary(checks)
self.assertEqual((summary['passed'], summary['required']), (22, 24))
with tempfile.TemporaryDirectory() as directory:
path = Path(directory) / 'report.json'
report = StatusReport(path=path, clock_ns=lambda: 10_000_000_000)
names = ['highway_center_taper_max', 'turn_in_boost_left', 'unwind_taper_left', 'turn_in_boost_right', 'unwind_taper_right']
suggestions = [{'parameter': name, 'delta': 0.005, 'whole_windows': 9, 'qualification': 'controller_native_checks_not_passed'} for name in names]
recorded = {
'version': 1,
'domain': 'lateral_acceleration',
'samples': 2000,
'windows': 10,
'error_rms': 0.12,
'route': 'declared-completed-drive',
'segment': 0,
'source_start_ns': 1_000_000_000,
'source_end_ns': 2_900_000_000,
'points': [[1_000_000_000 + i * 100_000_000, 0.2, 0.08] for i in range(20)],
'sampling': 'input_ordered_original_endpoints_no_interpolation',
}
report.set(
{
'status': 'collecting',
'reason': 'recorded_tracking_suggestion_not_yet_qualified_for_automatic_application',
'completed_route': 'declared-completed-drive',
'analysis_counts': {'recorded_tracking': 241573},
'suggestions': suggestions,
'suggestion_count': len(suggestions),
'configuration_changed': False,
'recorded_tracking': recorded,
'saved_adjustments': 0,
'qualification_summary': summary,
}
)
report.publish()
current = read_report(path, now_ns=10_000_000_000)['current']
assert current is not None
self.assertEqual([r[0] for r in current['details']['Recorded route suggestions']], names)
self.assertEqual(current['details']['Recorded suggestion count'], 5)
self.assertEqual(current['progress']['samples'], 241573)
self.assertFalse(current['details']['Automatic configuration changed'])
self.assertFalse(current['application']['applied'])
self.assertFalse(current['details']['Physical road improvement proven'])
self.assertEqual(current['details']['Recorded steering response'], recorded)
self.assertEqual(current['details']['Saved route adjustment count'], 0)
self.assertEqual(current['details']['Controller and encoder check windows'], [22, 24])
self.assertEqual(
current['details']['Automatic tune refusal reasons'], [['candidate changed an actual limiter/support', 1], ['original_scored_frame_not_eligible', 1]]
)
def test_typed_current_application_and_completed_analysis_remain_distinct(self):
with tempfile.TemporaryDirectory() as directory:
now = 10_000_000_000
control = ControlEvidence(
identity='unit',
generation=1,
control_ns=now,
state_ns=now,
domain='torque',
stage_revision='',
response_revision='',
requested=0.0,
features=(),
baseline_prediction=0.0,
enabled=True,
manual=False,
active=True,
valid=True,
override=False,
fault=False,
saturated=False,
limited=False,
model_wobble=False,
controller_chatter=False,
route_applied_coordinates=tuple(values(0.01).items()),
route_effect_revision=REVISION,
route_configuration_scope='a' * 64,
)
path = Path(directory) / 'report.json'
report = StatusReport(path=path, clock_ns=lambda: now)
current = {
'status': 'collecting',
'reason': 'declared-unit',
'enabled': True,
'actual_control': control,
'actual_control_ns': now,
'actual_coordinates': control.route_applied_coordinates,
'completed_route': 'declared-unit-route',
'analysis_counts': {'recorded_tracking': 1000, 'qualified_whole_windows': 6},
}
report.set(current)
report.publish()
observed = json.loads(path.read_bytes())['current']
self.assertTrue(observed['application']['applied'])
self.assertEqual(observed['progress']['samples'], 1000)
self.assertFalse(observed['details']['Physical road improvement proven'])
for replacement in (None, replace(control, manual=True), replace(control, limited=True), replace(control, control_ns=now - 100_000_001)):
with self.subTest(control=replacement):
report.next_ns = 0
report.set(dict(current, actual_control=replacement))
report.publish()
self.assertFalse(json.loads(path.read_bytes())['current']['application']['applied'])
+5 -4
View File
@@ -102,10 +102,11 @@ class CompanionRegistry:
# The same hotspot peer may rotate credentials (app restart); only a different phone is refused. # The same hotspot peer may rotate credentials (app restart); only a different phone is refused.
if previous and previous['peer'] != peer: if previous and previous['peer'] != peer:
raise FileExistsError('Another phone is sharing data') raise FileExistsError('Another phone is sharing data')
enabled = self.enabled() # The phone's own opt-in (with its disclosure) is consent: a hotspot heartbeat turns sharing on.
if enabled: if not self.enabled():
atomic_json(self.lease_path, {**lease, 'updated': self.clock()}) atomic_json(self.path, {'enabled': True})
return {'ok': True, 'enabled': enabled, 'active': phone_uplink_active(self.status_path, self.clock), atomic_json(self.lease_path, {**lease, 'updated': self.clock()})
return {'ok': True, 'enabled': True, 'active': phone_uplink_active(self.status_path, self.clock),
'protocol': COMPANION_PROTOCOL, 'uploadDenyHosts': UPLOAD_DENY_HOSTS} 'protocol': COMPANION_PROTOCOL, 'uploadDenyHosts': UPLOAD_DENY_HOSTS}
def lease(self): def lease(self):
+44 -2
View File
@@ -1,6 +1,6 @@
"""Bounded Galaxy HTTP connections and shared-source shutdown.""" """Bounded Galaxy HTTP connections and shared-source shutdown."""
from contextlib import ExitStack from contextlib import ExitStack, contextmanager
from dataclasses import dataclass from dataclasses import dataclass
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from functools import lru_cache from functools import lru_cache
@@ -46,7 +46,8 @@ class ReverseProxy:
class _LocalHTTPServer(ThreadingHTTPServer): class _LocalHTTPServer(ThreadingHTTPServer):
"""Bound idle browser connections without blocking other local requests.""" """Bound idle browser connections without blocking other local requests."""
MAX_CONNECTIONS = 8 MAX_CONNECTIONS = 32 # open sockets, one thread each
MAX_ACTIVE_REQUESTS = 8 # requests being handled; idle keep-alive sockets don't count
# comma's own services call back over loopback while a browser request waits on them. # comma's own services call back over loopback while a browser request waits on them.
LOOPBACK_CONNECTIONS = 4 LOOPBACK_CONNECTIONS = 4
REQUEST_TIMEOUT = 4.0 REQUEST_TIMEOUT = 4.0
@@ -54,6 +55,7 @@ class _LocalHTTPServer(ThreadingHTTPServer):
def __init__(self, *args, **kwargs): def __init__(self, *args, **kwargs):
self._slots = threading.BoundedSemaphore(self.MAX_CONNECTIONS) self._slots = threading.BoundedSemaphore(self.MAX_CONNECTIONS)
self._loopback_slots = threading.BoundedSemaphore(self.LOOPBACK_CONNECTIONS) self._loopback_slots = threading.BoundedSemaphore(self.LOOPBACK_CONNECTIONS)
self._active = threading.BoundedSemaphore(self.MAX_ACTIVE_REQUESTS)
self._draining = False self._draining = False
super().__init__(*args, **kwargs) super().__init__(*args, **kwargs)
@@ -94,6 +96,22 @@ class _LocalHTTPServer(ThreadingHTTPServer):
finally: finally:
slots.release() slots.release()
@contextmanager
def request_slot(self, request):
"""Held while one request is handled; loopback skips it because it serves browser requests in flight."""
if self._draining:
yield False
return
if self.loopback(request):
yield True
return
admitted = self._active.acquire(timeout=self.REQUEST_TIMEOUT)
try:
yield admitted
finally:
if admitted:
self._active.release()
def drain_requests(self, timeout: float) -> bool: def drain_requests(self, timeout: float) -> bool:
"""Wait for accepted requests before closing their shared data sources.""" """Wait for accepted requests before closing their shared data sources."""
self._draining = True self._draining = True
@@ -189,6 +207,12 @@ def allowed_authority(host: str, local_address: str, port: int, *, local_hostnam
if local_hostnames is None: if local_hostnames is None:
return False return False
canonical = dns_authority_name(host, port, allow_portless=allow_portless) canonical = dns_authority_name(host, port, allow_portless=allow_portless)
from openpilot.starpilot.galaxy.mdns import own_address, published_record
published = published_record()
# Our mDNS name, with or without :port, on any of our own LAN addresses (port 80 redirects here).
if published is not None and dns_authority_name(host, port, allow_portless=True) == published[0] and \
own_address(local_address):
return True
return canonical is not None and canonical in local_hostnames.names(local_address) return canonical is not None and canonical in local_hostnames.names(local_address)
try: try:
address = ip_address(local_address) address = ip_address(local_address)
@@ -226,6 +250,24 @@ class _LocalHTTPHandler(BaseHTTPRequestHandler):
def log_message(self, format, *args): # noqa: A002 - Match BaseHTTPRequestHandler's keyword signature. def log_message(self, format, *args): # noqa: A002 - Match BaseHTTPRequestHandler's keyword signature.
pass pass
def handle_one_request(self):
slot = getattr(self.server, 'request_slot', None)
if slot is None:
return super().handle_one_request()
try:
# Wait for the next keep-alive request without holding a request slot.
if not self.rfile.peek(1):
self.close_connection = True
return
except TimeoutError:
self.close_connection = True
return
with slot(self.connection) as admitted:
if not admitted:
self.close_connection = True
return
super().handle_one_request()
def handle(self): def handle(self):
try: try:
super().handle() super().handle()
+2 -1
View File
@@ -75,8 +75,9 @@ class LocalAccess:
except (OSError, subprocess.SubprocessError, ValueError, KeyError, TypeError, AttributeError): except (OSError, subprocess.SubprocessError, ValueError, KeyError, TypeError, AttributeError):
reason = 'The comma could not read its network addresses. Check its Network settings and refresh.' reason = 'The comma could not read its network addresses. Check its Network settings and refresh.'
addresses = [] addresses = []
from openpilot.starpilot.galaxy.mdns import published_url
self.cached = {'available': bool(addresses), 'addresses': addresses, self.cached = {'available': bool(addresses), 'addresses': addresses,
'reason': '' if addresses else reason} 'reason': '' if addresses else reason, 'name': published_url(self.port) or ''}
self.expiry = self.clock() + 5.0 self.expiry = self.clock() + 5.0
return self.cached return self.cached
+9 -1
View File
@@ -5,6 +5,7 @@ import signal
import threading import threading
import time import time
from openpilot.starpilot.galaxy.mdns import run as run_mdns
from openpilot.starpilot.galaxy.server import make_server from openpilot.starpilot.galaxy.server import make_server
from openpilot.starpilot.galaxy.server import make_remote_server from openpilot.starpilot.galaxy.server import make_remote_server
from openpilot.starpilot.galaxy.remote import default_remote_pairing, make_gateway_auth_server from openpilot.starpilot.galaxy.remote import default_remote_pairing, make_gateway_auth_server
@@ -126,7 +127,14 @@ def main() -> None:
server.server_close() server.server_close()
raise raise
print(f'Galaxy local/LAN service listening on port {server.server_port}', flush=True) print(f'Galaxy local/LAN service listening on port {server.server_port}', flush=True)
serve_managed(server, extra_servers=(remote_server, auth_server), tunnel=lambda stop: supervise_tunnel(stop, pairing)) mdns_stop = threading.Event()
mdns = threading.Thread(target=run_mdns, args=(mdns_stop, server.server_port), name='galaxy-mdns', daemon=True)
mdns.start()
try:
serve_managed(server, extra_servers=(remote_server, auth_server), tunnel=lambda stop: supervise_tunnel(stop, pairing))
finally:
mdns_stop.set()
mdns.join(timeout=3)
if __name__ == '__main__': if __name__ == '__main__':
+371
View File
@@ -0,0 +1,371 @@
"""Advertise galaxy.local through avahi's D-Bus API, answering with each interface's own address."""
import fcntl
from ipaddress import IPv6Address
import os
from pathlib import Path
import shutil
import socket
import struct
import subprocess
import time
from jeepney import DBusAddress, new_method_call
from jeepney.io.blocking import open_dbus_connection
from jeepney.low_level import HeaderFields, MessageType
from openpilot.starpilot.galaxy.hotspot import INTERFACE as HOTSPOT_INTERFACE
from openpilot.starpilot.galaxy.local_hostnames import lan_address
NAMES = ('galaxy.local',) + tuple(f'galaxy-{n}.local' for n in range(2, 10))
INTERFACES = ('wlan0', 'eth0', HOTSPOT_INTERFACE)
NAME_FILE = Path('/data/galaxy/mdns_name')
IF_INET6 = Path('/proc/net/if_inet6')
SIOCGIFADDR = 0x8915
CHAIN = 'GALAXY_HTTP'
MAX_READ_BYTES = 65536
REFRESH_S = 10.0
ESTABLISH_S = 5.0
RETRY_S = 300.0
CALL_S = 5.0
RESOLVE_S = 1.5
AVAHI = 'org.freedesktop.Avahi'
SERVER = 'org.freedesktop.Avahi.Server'
ENTRY_GROUP = 'org.freedesktop.Avahi.EntryGroup'
PROTO_INET, PROTO_INET6 = 0, 1
PUBLISH_NO_REVERSE = 16
ESTABLISHED = 2
_published = None
_redirected = False
def published_record():
return _published
def published_url(port):
"""Our published name as a link; port-less only while port 80 redirects to Galaxy."""
published = _published
if published is None:
return None
return f'http://{published[0]}/' if _redirected else f'http://{published[0]}:{port}/'
def _ifaddr(sock, name):
return socket.inet_ntoa(fcntl.ioctl(sock.fileno(), SIOCGIFADDR, struct.pack('256s', name.encode()))[20:24])
def interface_addresses(lookup=_ifaddr):
"""Primary IPv4 of each candidate interface, read by ioctl."""
addresses = {}
try:
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as sock:
for name in INTERFACES:
try:
addresses[name] = lookup(sock, name)
except OSError:
continue # interface missing or has no IPv4 address
except OSError:
return {}
return addresses
def _read_text(path, limit=MAX_READ_BYTES):
fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW)
with os.fdopen(fd, 'rb') as handle:
data = handle.read(limit + 1)
if len(data) > limit:
raise ValueError(f'{path} exceeds {limit} bytes')
return data.decode()
def own_address(address):
"""True for this device's current wlan0/eth0/galaxy0 LAN address."""
return lan_address(address) and address in interface_addresses().values()
class Redirect:
"""Redirect port 80 on this device's own LAN addresses to Galaxy; one -d rule each, never forwarded traffic."""
def __init__(self, port, run=subprocess.run, which=shutil.which):
self.port, self.run = port, run
self.firewall = which('iptables-legacy') or which('iptables')
self.ready, self.applied = False, None
def ipt(self, *args, check=True):
if self.firewall is None:
raise OSError('iptables missing')
return self.run(['sudo', '-n', self.firewall, '-w', '2', '-t', 'nat', *args], capture_output=True, timeout=5, check=check)
def sync(self, addresses):
global _redirected
wanted = tuple(sorted(a for a in addresses if lan_address(a)))
if self.firewall is None or wanted == self.applied:
return
try:
if not self.ready:
self.ipt('-N', CHAIN, check=False) # already exists after a restart
jump = ('PREROUTING', '-p', 'tcp', '--dport', '80', '-j', CHAIN)
if self.ipt('-C', *jump, check=False).returncode != 0:
self.ipt('-I', *jump)
self.ready = True
self.ipt('-F', CHAIN)
for address in wanted:
self.ipt('-A', CHAIN, '-d', address, '-p', 'tcp', '-j', 'REDIRECT', '--to-ports', str(self.port))
self.applied, _redirected = wanted, True
except (OSError, subprocess.SubprocessError) as error:
self.applied, _redirected = wanted, False # retried on the next address change, not every poll
_log(f'port 80 redirect failed ({error}); http://galaxy.local needs :{self.port}')
def close(self):
global _redirected
_redirected = False
if not self.ready:
return
try:
self.ipt('-D', 'PREROUTING', '-p', 'tcp', '--dport', '80', '-j', CHAIN, check=False)
self.ipt('-F', CHAIN, check=False)
self.ipt('-X', CHAIN, check=False)
except (OSError, subprocess.SubprocessError) as error:
_log(f'port 80 redirect cleanup failed ({error})')
self.ready, self.applied = False, None
def link_local(interface, path=IF_INET6):
"""The interface's fe80:: address, so AAAA lookups answer at once."""
try:
for line in _read_text(path).splitlines():
fields = line.split()
# address ifindex prefixlen scope flags name; scope 0x20 = link
if len(fields) == 6 and fields[5] == interface and fields[3] == '20':
return str(IPv6Address(bytes.fromhex(fields[0])))
except (OSError, ValueError):
pass
return None
def records(found, ipv6=link_local, index=socket.if_nametoindex):
"""(interface index, protocol, address) for each LAN interface."""
out = []
for name in INTERFACES:
address = found.get(name)
if address is None or not lan_address(address):
continue
try:
number = index(name)
except OSError:
continue
out.append((number, PROTO_INET, address))
address6 = ipv6(name)
if address6 is not None:
out.append((number, PROTO_INET6, address6))
return tuple(out)
class AvahiError(Exception):
def __init__(self, name, message=''):
super().__init__(f'{name}: {message}' if message else name)
self.name = name
@property
def collision(self):
return self.name == 'org.freedesktop.Avahi.CollisionError'
class Avahi:
"""Entry groups belong to this D-Bus connection, so avahi withdraws them if Galaxy dies."""
def __init__(self, connect=lambda: open_dbus_connection(bus='SYSTEM'), stopped=lambda: False):
self.connect, self.stopped, self.connection = connect, stopped, None
def call(self, path, interface, member, signature=None, body=()):
if self.connection is None:
self.connection = self.connect()
address = DBusAddress(path, bus_name=AVAHI, interface=interface)
message = new_method_call(address, member, signature, body) if signature else new_method_call(address, member)
try:
reply = self.connection.send_and_get_reply(message, timeout=CALL_S)
except OSError:
self.close()
raise
if reply.header.message_type == MessageType.error:
raise AvahiError(str(reply.header.fields.get(HeaderFields.error_name, member)), str(reply.body[0]) if reply.body else '')
return reply.body
def first(self, path, interface, member, kind):
body = self.call(path, interface, member)
if len(body) != 1 or not isinstance(body[0], kind):
raise AvahiError(f'{member} returned {body!r}')
return body[0]
def state(self, group):
return self.first(group, ENTRY_GROUP, 'GetState', int)
def claim(self, name, entries, timeout=ESTABLISH_S, group=None):
"""The committed group once avahi has probed the name, or None if another device holds it; group updates ours in place."""
if group is None:
group = self.first('/', SERVER, 'EntryGroupNew', str)
else:
self.call(group, ENTRY_GROUP, 'Reset')
try:
for number, protocol, address in entries:
self.call(group, ENTRY_GROUP, 'AddAddress', 'iiuss', (number, protocol, PUBLISH_NO_REVERSE, name, address))
self.call(group, ENTRY_GROUP, 'Commit')
deadline = time.monotonic() + timeout
while (state := self.state(group)) < ESTABLISHED and time.monotonic() < deadline and not self.stopped():
time.sleep(0.1)
if state == ESTABLISHED:
return group
except AvahiError as error:
if not error.collision:
self.free(group)
raise
self.free(group)
return None
def free(self, group):
try:
self.call(group, ENTRY_GROUP, 'Free')
except (OSError, AvahiError):
pass # already withdrawn, or the connection is gone and avahi dropped it
def close(self):
if self.connection is not None:
try:
self.connection.close()
except OSError:
pass
self.connection = None
def load_name(path=NAME_FILE):
try:
name = _read_text(path, 64).strip()
except (OSError, ValueError):
return None
return name if name in NAMES else None
def save_name(name, path=NAME_FILE):
try:
tmp = path.with_suffix('.tmp')
tmp.write_text(name + '\n')
os.replace(tmp, path)
except OSError as error:
_log(f'cannot remember {name} ({error})')
def candidates(remembered):
return ((remembered,) if remembered else ()) + tuple(name for name in NAMES if name != remembered)
def held_elsewhere(name, own, run=subprocess.run):
"""True when another device already answers for name; probing alone can miss a responder that doesn't defend."""
try:
out = run(['avahi-resolve', '-4', '-n', name], capture_output=True, text=True, timeout=RESOLVE_S).stdout
except (OSError, subprocess.SubprocessError):
return False
fields = out.split()
return len(fields) == 2 and fields[0] == name and fields[1] not in own
def _claim(avahi, entries, remembered, stop, taken=held_elsewhere, ours=frozenset()):
own = {address for _, _, address in entries} | set(ours) # our earlier addresses can linger in avahi's answers
for name in candidates(remembered):
if stop.is_set():
break
if taken(name, own):
continue
group = avahi.claim(name, entries)
if group is not None:
return name, group
return None, None
def _log(message, warning=True):
from openpilot.common.swaglog import cloudlog
(cloudlog.warning if warning else cloudlog.info)(f'Galaxy mDNS: {message}')
def publish(stop, *, avahi=None, addresses=interface_addresses, ipv6=link_local, index=socket.if_nametoindex, redirect=None,
taken=held_elsewhere, name_file=NAME_FILE, refresh=REFRESH_S, retry=RETRY_S):
"""Keep the first free galaxy[-N].local name on every LAN interface until stop is set."""
global _published
avahi = avahi if avahi is not None else Avahi(stopped=stop.is_set)
group, entries, retry_at, failure = None, (), 0.0, None
remembered, ours = load_name(name_file), set()
def failed(message):
nonlocal failure
if message != failure:
failure = message
_log(f'{message}; retrying every {retry:.0f}s')
try:
while not stop.is_set():
found = addresses()
if redirect is not None:
redirect.sync(found.values())
wanted = records(found, ipv6, index)
lost = False
if group is not None:
try:
lost = avahi.state(group) != ESTABLISHED
except (OSError, AvahiError):
lost = True
if lost and _published is not None:
_log(f'lost {_published[0]}; reclaiming')
if wanted != entries or lost or (group is None and wanted and time.monotonic() >= retry_at):
held = _published[0] if _published is not None and group is not None and not lost and wanted else None
if held is not None:
try:
group = avahi.claim(held, wanted, group=group)
except (OSError, AvahiError):
group = None
if group is not None and held is None:
avahi.free(group)
group = None
_published, entries = None, wanted
if wanted:
name = held if group is not None else None
try:
if name is None:
name, group = _claim(avahi, wanted, remembered, stop, taken, ours)
except (OSError, AvahiError) as error:
failed(f'avahi unavailable ({error})')
else:
if name is None:
failed('every galaxy[-N].local name is taken')
if name is None:
retry_at = time.monotonic() + retry
else:
failure = None
ours.update(address for _, _, address in wanted)
_published = (name, tuple(address for _, protocol, address in wanted if protocol == PROTO_INET))
interfaces = ', '.join(n for n in INTERFACES if found.get(n) in _published[1])
_log(f'published {name} on {interfaces}', warning=False)
if name != remembered:
remembered = name
save_name(name, name_file)
stop.wait(refresh)
finally:
if group is not None:
avahi.free(group)
avahi.close()
_published = None
def run(stop, port):
redirect = Redirect(port)
try:
publish(stop, redirect=redirect)
except Exception:
from openpilot.common.swaglog import cloudlog
cloudlog.exception('Galaxy mDNS: publisher stopped; galaxy.local is offline, the IP address still works')
finally:
redirect.close()
+2 -1
View File
@@ -1776,7 +1776,8 @@ def make_server(*, port=8082, host='127.0.0.1', monitor=None, owner=None, crashe
self.json(404, {'error': 'Not found'}) self.json(404, {'error': 'Not found'})
return return
if path not in ('/api/companion/uplink', '/api/companion/settings', '/api/companion/location', if path not in ('/api/companion/uplink', '/api/companion/settings', '/api/companion/location',
'/api/connect/proxy', '/api/connect/provider', '/api/auth/login', '/api/auth/logout', '/api/settings/preview', '/api/settings/confirm', '/api/settings/mode', '/api/connect/proxy', '/api/connect/provider', '/api/auth/login', '/api/auth/logout',
'/api/settings/preview', '/api/settings/confirm', '/api/settings/mode',
'/api/settings/recovery/preview', '/api/settings/recovery/confirm', '/api/settings/recovery/preview', '/api/settings/recovery/confirm',
'/api/settings/flm-backup/preview', '/api/settings/flm-backup/confirm', '/api/settings/flm-backup/preview', '/api/settings/flm-backup/confirm',
'/api/settings/flm-finding/accept', '/api/settings/flm-finding/accept',
@@ -44,9 +44,6 @@ DESCRIPTIONS = {
'LaneCenteringPauseOnSignal': 'Pauses lane-centering correction while a turn signal is on.', 'LaneCenteringPauseOnSignal': 'Pauses lane-centering correction while a turn signal is on.',
'LaneCenterOffset': 'Moves the lane-centering target left or right of the detected lane center.', 'LaneCenterOffset': 'Moves the lane-centering target left or right of the detected lane center.',
'LaneCenteringE2EAuthority': 'Lets a confident driving-model path reduce lane-centering correction when the model path differs from the lane center.', 'LaneCenteringE2EAuthority': 'Lets a confident driving-model path reduce lane-centering correction when the model path differs from the lane center.',
'ParkedClearance': 'Leaves extra room beside parked cars detected by radar. Adds nothing when no parked car is detected.',
'ParkedClearanceGap': 'The room to aim for beside a parked car. The car moves left only as far as needed to reach it.',
'ParkedClearanceShift': 'The most the car will move left for a parked car, even if the target gap is not reached.',
'LaneCenteringStrength': 'Sets the strength of lane-centering correction. 100% is normal; higher values strengthen it.', 'LaneCenteringStrength': 'Sets the strength of lane-centering correction. 100% is normal; higher values strengthen it.',
'PauseLateralSpeed': 'Pauses steering assistance below this speed. Zero disables the speed-based pause.', 'PauseLateralSpeed': 'Pauses steering assistance below this speed. Zero disables the speed-based pause.',
'PauseLateralOnSignal': 'Limits the low-speed steering pause to times when a turn signal is on.', 'PauseLateralOnSignal': 'Limits the low-speed steering pause to times when a turn signal is on.',
+2 -1
View File
@@ -409,7 +409,8 @@ def _session_key(token: str) -> bytes:
def _projection(row: FeatureRow, default_level: SettingLevel = SettingLevel.SIMPLE) -> dict: def _projection(row: FeatureRow, default_level: SettingLevel = SettingLevel.SIMPLE) -> dict:
return {"id": row.key, "level": row.level if row.level is not None else default_level, "label": row.label, "value": row.value, "choices": list(row.choices), "step": row.step, return {"id": row.key, "level": row.level if row.level is not None else default_level, "label": row.label,
"value": row.value, "choices": list(row.choices), "step": row.step,
"minimum": row.minimum, "maximum": row.maximum, "unit": row.unit, "minimum": row.minimum, "maximum": row.maximum, "unit": row.unit,
"available": row.available, "reason": description(row), "learnedValue": row.learned_value, "available": row.available, "reason": description(row), "learnedValue": row.learned_value,
"page": row.page if row.page in PAGES else "", "action": bool(row.key and row.available and not row.page), "page": row.page if row.page in PAGES else "", "action": bool(row.key and row.available and not row.page),
@@ -73,9 +73,6 @@
"PIPPreviewInvert", "PIPPreviewInvert",
"PIPPreviewShowOnBSM", "PIPPreviewShowOnBSM",
"PIPPreviewShowOnBlinker", "PIPPreviewShowOnBlinker",
"ParkedClearance",
"ParkedClearanceGap",
"ParkedClearanceShift",
"PauseLateralOnSignal", "PauseLateralOnSignal",
"PauseLateralSpeed", "PauseLateralSpeed",
"PromptDistractedVolume", "PromptDistractedVolume",
@@ -1,7 +1,6 @@
"""Shared declared-context HTTP fixture; no physical vehicle evidence.""" """Shared declared-context HTTP fixture; no physical vehicle evidence."""
from pathlib import Path from pathlib import Path
from types import SimpleNamespace
import http.client import http.client
import json import json
import tempfile import tempfile
@@ -30,12 +29,10 @@ class SettingsHttpFixture(unittest.TestCase):
temporary = tempfile.TemporaryDirectory() temporary = tempfile.TemporaryDirectory()
self.addCleanup(temporary.cleanup) self.addCleanup(temporary.cleanup)
self.params = Params(temporary.name) self.params = Params(temporary.name)
native = ToyotaInterface.get_non_essential_params(ToyotaCar.TOYOTA_COROLLA_TSS2) cp = ToyotaInterface.get_non_essential_params(ToyotaCar.TOYOTA_COROLLA_TSS2)
cp = SimpleNamespace(carFingerprint="TOYOTA_COROLLA_TSS2", openpilotLongitudinalControl=True, cp.openpilotLongitudinalControl = True
pcmCruise=False, notCar=False, dashcamOnly=False, passive=False, cp.pcmCruise = False
brand="toyota", steerControlType=native.steerControlType, carVin="", cp.transmissionType = car.CarParams.TransmissionType.automatic
lateralTuning=native.lateralTuning, minSteerSpeed=native.minSteerSpeed, safetyConfigs=native.safetyConfigs,
transmissionType=car.CarParams.TransmissionType.automatic)
self.context = MutableContext(cp) self.context = MutableContext(cp)
self.gateway = SettingsGateway(self.params, self.context) self.gateway = SettingsGateway(self.params, self.context)
self.access = GalaxyAccessOwner(Path(temporary.name) / "access") self.access = GalaxyAccessOwner(Path(temporary.name) / "access")
@@ -86,7 +86,7 @@ const settingsView = route.view
const props = {initialPage:'hub',initialSection:null,unauthorized() {}} const props = {initialPage:'hub',initialSection:null,unauthorized() {}}
const original = {...SettingsPage.setup(props), ...props} const original = {...SettingsPage.setup(props), ...props}
Object.assign(original.state, {data:{page:'pip',rows:[{value:'old device value'}]}, Object.assign(original.state, {data:{page:'pip',rows:[{value:'old device value'}]},
section:'visual',query:'camera',searchOpen:true,parents:['hub']}) section:'visual',parents:['hub']})
settingsView.scroll = {x:0,y:720} settingsView.scroll = {x:0,y:720}
SettingsPage.beforeUnmount.call(original) SettingsPage.beforeUnmount.call(original)
assert(!JSON.stringify(settingsView).includes('old device value')) assert(!JSON.stringify(settingsView).includes('old device value'))
@@ -97,8 +97,6 @@ assert.equal(route.view, settingsView)
const restored = {...SettingsPage.setup(props), ...props, mode:'local'} const restored = {...SettingsPage.setup(props), ...props, mode:'local'}
assert.equal(restored.restoredPage, 'pip') assert.equal(restored.restoredPage, 'pip')
assert.equal(restored.state.section, 'visual') assert.equal(restored.state.section, 'visual')
assert.equal(restored.state.query, 'camera')
assert.equal(restored.state.searchOpen, true)
assert.deepEqual(restored.state.parents, ['hub']) assert.deepEqual(restored.state.parents, ['hub'])
assert.equal(restored.state.data, null, 'saved settings are always read again') assert.equal(restored.state.data, null, 'saved settings are always read again')
const positions = [] const positions = []
@@ -22,11 +22,10 @@ assert.equal(states.at(-1).status, "idle") // Hidden or signed-out page cannot r
const mounted = { mode: "local", initialPage: "pip", state: { developerOpen: false }, feed: { start(page) { assert.equal(page, "pip") } } } const mounted = { mode: "local", initialPage: "pip", state: { developerOpen: false }, feed: { start(page) { assert.equal(page, "pip") } } }
SettingsPage.mounted.call(mounted) SettingsPage.mounted.call(mounted)
let returned = 0 let returned = 0
const page = { initialPage: "pip", returnTo: () => returned++, state: { query: "anything", data: { page: "pip" } }, const page = { initialPage: "pip", returnTo: () => returned++, state: { data: { page: "pip" } },
feed: { load() { throw new Error("Root PiP Back must return to Cameras") } } } feed: { load() { throw new Error("Root PiP Back must return to Cameras") } } }
SettingsPage.methods.back.call(page) SettingsPage.methods.back.call(page)
assert.equal(returned, 1) assert.equal(returned, 1)
assert.equal(page.state.query, "")
assert.match(CamerasPage.template, /MenuTile v-for="tool in tools"/) assert.match(CamerasPage.template, /MenuTile v-for="tool in tools"/)
assert.equal(cameraTools.find(tool => tool.path === "/cameras/pip").description, "Adjust the camera crop with a live cabin preview.") assert.equal(cameraTools.find(tool => tool.path === "/cameras/pip").description, "Adjust the camera crop with a live cabin preview.")
@@ -18,10 +18,9 @@ def registry(tmp_path, now=lambda: 100):
def test_opt_in_and_stale_lease(tmp_path): def test_opt_in_and_stale_lease(tmp_path):
now = [100] now = [100]
owner = registry(tmp_path, lambda: now[0]) owner = registry(tmp_path, lambda: now[0])
assert not owner.heartbeat(PAYLOAD, PEER)['enabled'] owner.save({'enabled': False})
assert owner.lease() is None
owner.save({'enabled': True})
assert owner.heartbeat(PAYLOAD, PEER)['enabled'] assert owner.heartbeat(PAYLOAD, PEER)['enabled']
assert owner.enabled()
assert stat.S_IMODE(owner.lease_path.stat().st_mode) == 0o600 assert stat.S_IMODE(owner.lease_path.stat().st_mode) == 0o600
assert owner.snapshot()['connected'] assert owner.snapshot()['connected']
assert 'pass' not in owner.snapshot() assert 'pass' not in owner.snapshot()
@@ -33,15 +32,17 @@ def test_opt_in_and_stale_lease(tmp_path):
@pytest.mark.parametrize('peer', ['127.0.0.1', '192.168.1.2', '172.31.254.1', '172.31.254.0', '172.31.254.255', '::ffff:172.31.254.10']) @pytest.mark.parametrize('peer', ['127.0.0.1', '192.168.1.2', '172.31.254.1', '172.31.254.0', '172.31.254.255', '::ffff:172.31.254.10'])
def test_only_hotspot_peers(tmp_path, peer): def test_only_hotspot_peers(tmp_path, peer):
owner = registry(tmp_path)
with pytest.raises(ValueError): with pytest.raises(ValueError):
registry(tmp_path).heartbeat(PAYLOAD, peer) owner.heartbeat(PAYLOAD, peer)
assert not owner.enabled()
def test_remote_and_conflict_and_disable(tmp_path): def test_remote_and_conflict_and_disable(tmp_path):
owner = registry(tmp_path) owner = registry(tmp_path)
owner.save({'enabled': True})
with pytest.raises(PermissionError): with pytest.raises(PermissionError):
owner.heartbeat(PAYLOAD, PEER, remote=True) owner.heartbeat(PAYLOAD, PEER, remote=True)
assert not owner.enabled()
owner.heartbeat(PAYLOAD, PEER) owner.heartbeat(PAYLOAD, PEER)
with pytest.raises(FileExistsError): with pytest.raises(FileExistsError):
owner.heartbeat(PAYLOAD, '172.31.254.11') owner.heartbeat(PAYLOAD, '172.31.254.11')
@@ -11,8 +11,10 @@ from typing import Any
from urllib.parse import urlsplit from urllib.parse import urlsplit
import pytest import pytest
from unittest.mock import patch
from openpilot.starpilot.galaxy.http_server import _LocalHTTPHandler, _LocalHTTPServer from openpilot.starpilot.galaxy import mdns
from openpilot.starpilot.galaxy.http_server import _LocalHTTPHandler, _LocalHTTPServer, allowed_authority
from openpilot.starpilot.galaxy.replay_http import ReplayHTTP from openpilot.starpilot.galaxy.replay_http import ReplayHTTP
from openpilot.starpilot.galaxy.recording_http import send_recording from openpilot.starpilot.galaxy.recording_http import send_recording
@@ -164,6 +166,52 @@ def test_idle_persistent_connections_release_capacity(server):
connection.close() connection.close()
def test_busy_keepalive_tabs_do_not_hold_request_slots(server, monkeypatch):
"""Two polling tabs' worth of keep-alive sockets must not starve a third tab's first load."""
running, _, _ = server
monkeypatch.setattr(running, 'loopback', lambda request: False)
held = []
try:
for _ in range(running.MAX_ACTIVE_REQUESTS + 4):
connection = http.client.HTTPConnection('127.0.0.1', running.server_port, timeout=2)
held.append(connection)
connection.request('GET', '/poll')
assert connection.getresponse().read() == b'ok'
started = time.monotonic()
with closing(http.client.HTTPConnection('127.0.0.1', running.server_port, timeout=2)) as opening:
opening.request('GET', '/css/galaxy.css')
assert opening.getresponse().read() == b'ok'
assert time.monotonic() - started < 1
# The held sockets are still usable keep-alive connections.
for connection in held:
connection.request('GET', '/poll')
assert connection.getresponse().read() == b'ok'
finally:
for connection in held:
connection.close()
def test_requests_in_flight_are_bounded(server, monkeypatch):
running, _, _ = server
monkeypatch.setattr(running, 'loopback', lambda request: False)
for _ in range(running.MAX_ACTIVE_REQUESTS):
assert running._active.acquire(blocking=False)
monkeypatch.setattr(running, 'REQUEST_TIMEOUT', .2)
try:
with closing(socket.create_connection(('127.0.0.1', running.server_port), timeout=2)) as waiting:
waiting.sendall(b'GET /blocked HTTP/1.1\r\nHost: 127.0.0.1\r\n\r\n')
try:
assert waiting.recv(64) == b''
except ConnectionResetError:
pass
finally:
for _ in range(running.MAX_ACTIVE_REQUESTS):
running._active.release()
with closing(http.client.HTTPConnection('127.0.0.1', running.server_port, timeout=2)) as later:
later.request('GET', '/after')
assert later.getresponse().read() == b'ok'
def test_full_browser_pool_still_serves_comma_services(server): def test_full_browser_pool_still_serves_comma_services(server):
running, _, _ = server running, _, _ = server
held = [] held = []
@@ -223,3 +271,23 @@ def test_drain_turns_away_requests_still_waiting_for_capacity(server, monkeypatc
finally: finally:
for connection in held: for connection in held:
connection.close() connection.close()
def test_authority_admits_only_published_mdns_name_on_own_lan_address():
names = SimpleNamespace(names=lambda destination: ())
own = {'wlan0': '192.168.35.249', 'galaxy0': '172.31.254.1'}
with patch.object(mdns, '_published', ('galaxy-2.local', '192.168.35.249')), \
patch.object(mdns, 'interface_addresses', return_value=own):
assert allowed_authority('galaxy-2.local:8082', '192.168.35.249', 8082, local_hostnames=names)
assert allowed_authority('GALAXY-2.local.:8082', '192.168.35.249', 8082, local_hostnames=names)
# Port 80 is redirected to Galaxy, so the browser sends no port.
assert allowed_authority('galaxy-2.local', '192.168.35.249', 8082, local_hostnames=names)
# Hotspot clients: REDIRECT rewrites the destination to galaxy0's address.
assert allowed_authority('galaxy-2.local', '172.31.254.1', 8082, local_hostnames=names)
assert not allowed_authority('galaxy-2.local:9999', '192.168.35.249', 8082, local_hostnames=names)
assert not allowed_authority('galaxy.local', '192.168.35.249', 8082, local_hostnames=names)
assert not allowed_authority('galaxy-2.local', '10.228.238.20', 8082, local_hostnames=names)
assert not allowed_authority('galaxy-2.local', '127.0.0.1', 8082, local_hostnames=names)
assert not allowed_authority('galaxy-2.local', '100.64.1.5', 8082, local_hostnames=names)
assert not allowed_authority('galaxy-2.local', '192.168.35.249', 8082, local_hostnames=None)
assert not allowed_authority('galaxy-2.local', '192.168.35.249', 8082, local_hostnames=names)
@@ -10,6 +10,12 @@ assert.equal(validLocalAccess({ available: false, addresses: [], reason: 'No act
assert.equal(validLocalAccess({ ...snapshot, addresses: [{ ...snapshot.addresses[0], url: 'javascript:alert(1)' }] }), false) assert.equal(validLocalAccess({ ...snapshot, addresses: [{ ...snapshot.addresses[0], url: 'javascript:alert(1)' }] }), false)
assert.equal(validLocalAccess({ ...snapshot, addresses: [{ ...snapshot.addresses[0], url: 'http://password@example.com' }] }), false) assert.equal(validLocalAccess({ ...snapshot, addresses: [{ ...snapshot.addresses[0], url: 'http://password@example.com' }] }), false)
assert.equal(validLocalAccess({ ...snapshot, available: false }), false) assert.equal(validLocalAccess({ ...snapshot, available: false }), false)
assert.equal(validLocalAccess({ ...snapshot, name: 'http://galaxy-2.local/' }), true)
assert.equal(validLocalAccess({ ...snapshot, name: 'http://galaxy.local:8082/' }), true)
assert.equal(validLocalAccess({ ...snapshot, name: '' }), true)
assert.equal(validLocalAccess({ ...snapshot, name: 'javascript:alert(1)' }), false)
assert.equal(validLocalAccess({ ...snapshot, name: 'http://evil.example/' }), false)
assert.equal(validLocalAccess({ ...snapshot, name: { toString: () => 'http://galaxy.local/' } }), false)
const updates = [], requests = [], timers = [] const updates = [], requests = [], timers = []
let auth = 0 let auth = 0
const feed = new LocalAccessFeed({ publish: value => updates.push(value), onUnauthorized: () => auth++, const feed = new LocalAccessFeed({ publish: value => updates.push(value), onUnauthorized: () => auth++,
@@ -1,5 +1,5 @@
import assert from "node:assert/strict" import assert from "node:assert/strict"
import { translateText, localizeDocument } from "../web/js/localization.js" import { translateText, localizeDocument, startLocalization, LANGUAGE_RECHECK_MS, LANGUAGE_RETRY_MS } from "../web/js/localization.js"
assert.equal(translateText(" Home\n", { Home: "ホーム" }), " ホーム\n") assert.equal(translateText(" Home\n", { Home: "ホーム" }), " ホーム\n")
assert.equal(translateText("SpeedLimitController", {}), "SpeedLimitController") assert.equal(translateText("SpeedLimitController", {}), "SpeedLimitController")
@@ -67,3 +67,38 @@ const hiddenNative = new Element("select", {hidden:""}, [new Element("option", {
localizeDocument(hiddenNative, {language:"ja",messages:{Save:"保存"}}) localizeDocument(hiddenNative, {language:"ja",messages:{Save:"保存"}})
assert.equal(hiddenText.nodeValue,"Save","GalaxySelect must retain canonical hidden option labels for sync()") assert.equal(hiddenText.nodeValue,"Save","GalaxySelect must retain canonical hidden option labels for sync()")
assert.equal(translateText('Reset Language to default', {Language:'Sprache','Reset {label} to default':'{label} zurücksetzen'}),'Sprache zurücksetzen') assert.equal(translateText('Reset Language to default', {Language:'Sprache','Reset {label} to default':'{label} zurücksetzen'}),'Sprache zurücksetzen')
{
// Poll the language once a minute after a confirmed load; retry quickly only while it cannot be read.
const delays = [], pending = [], listeners = {}
const realSetTimeout = globalThis.setTimeout, realClearTimeout = globalThis.clearTimeout
globalThis.MutationObserver = class { observe() {} disconnect() {} }
globalThis.setTimeout = (fn, ms) => { if (ms === LANGUAGE_RETRY_MS || ms === LANGUAGE_RECHECK_MS) { delays.push(ms); pending.push(fn); return pending.length } return realSetTimeout(fn, ms) }
globalThis.clearTimeout = id => { if (typeof id !== "number" || id > 1000) realClearTimeout(id) }
const visibility = { visibilityState: "visible", addEventListener: (name, fn) => { listeners[name] = fn }, removeEventListener: name => { delete listeners[name] } }
globalThis.document = visibility
const responses = [true, true, false]
let calls = 0
const fetcher = async () => {
calls++
if (!responses.shift()) throw new Error("offline")
return new Response(JSON.stringify({ language: "en", messages: {} }), { status: 200, headers: { "Content-Type": "application/json" } })
}
const root = new Element("main", {}, [text("Home")])
const settle = () => new Promise(resolve => realSetTimeout(resolve, 20))
const stop = startLocalization(root, fetcher)
await settle()
assert.deepEqual(delays, [LANGUAGE_RECHECK_MS], "a confirmed language is rechecked once a minute, not every 2 s")
listeners.visibilitychange()
await settle()
assert.equal(calls, 2, "showing the tab again rechecks at once")
assert.equal(delays.at(-1), LANGUAGE_RECHECK_MS)
pending.at(-1)()
await settle()
assert.equal(calls, 3)
assert.equal(delays.at(-1), LANGUAGE_RETRY_MS, "an unreadable language retries quickly")
stop()
assert.equal(listeners.visibilitychange, undefined)
globalThis.setTimeout = realSetTimeout; globalThis.clearTimeout = realClearTimeout
delete globalThis.document; delete globalThis.MutationObserver
}
@@ -85,8 +85,10 @@ class CleanStageRequestTest(unittest.TestCase):
class LogRelayStagerTest(unittest.TestCase): class LogRelayStagerTest(unittest.TestCase):
def test_stages_starport_connection_and_controller_bundles(self): def test_stages_starport_connection_and_controller_bundles(self):
calls = [] calls = []
allow_response = threading.Event()
def fake_post(url, data, headers, allow_redirects, timeout): def fake_post(url, data, headers, allow_redirects, timeout):
assert allow_response.wait(5)
calls.append({"url": url, "data": data, "headers": headers, "allow_redirects": allow_redirects, "timeout": timeout}) calls.append({"url": url, "data": data, "headers": headers, "allow_redirects": allow_redirects, "timeout": timeout})
response = Mock(status_code=200) response = Mock(status_code=200)
response.json.return_value = {"claimUrl": VALID_CLAIM} response.json.return_value = {"claimUrl": VALID_CLAIM}
@@ -115,8 +117,12 @@ class LogRelayStagerTest(unittest.TestCase):
] ]
for payload, expected_zip, expected_kind, expected_platform, expected_note in cases: for payload, expected_zip, expected_kind, expected_platform, expected_note in cases:
with self.subTest(kind=expected_kind): with self.subTest(kind=expected_kind):
started = stager.start(payload) allow_response.clear()
self.assertEqual(started["state"], "staging") try:
started = stager.start(payload)
self.assertEqual(started["state"], "staging")
finally:
allow_response.set()
ready = wait_until(lambda: stager.status() if stager.status()["state"] == "ready" else None) ready = wait_until(lambda: stager.status() if stager.status()["state"] == "ready" else None)
self.assertEqual(ready["claimUrl"], VALID_CLAIM) self.assertEqual(ready["claimUrl"], VALID_CLAIM)
self.assertEqual(ready["kind"], expected_kind) self.assertEqual(ready["kind"], expected_kind)
@@ -0,0 +1,419 @@
"""galaxy[-N].local is claimed per interface, remembered, and withdrawn on loss."""
import subprocess
import tempfile
import threading
import unittest
from pathlib import Path
from types import SimpleNamespace
from unittest.mock import Mock, patch
from jeepney.low_level import HeaderFields, MessageType
from openpilot.starpilot.galaxy import mdns
IFADDRS = {'lo': '127.0.0.1', 'ppp0': '10.228.238.20', 'wlan0': '192.168.35.249', 'galaxy0': '172.31.254.1'}
INDEX = {'wlan0': 12, 'eth0': 3, 'galaxy0': 29}
def ifaddr_lookup(sock, name):
if name not in IFADDRS:
raise OSError(19, 'No such device')
return IFADDRS[name]
def index(name):
if name not in INDEX:
raise OSError(19, 'No such device')
return INDEX[name]
class FakeAvahi:
"""Names other devices hold collide; dropped groups read as not established."""
def __init__(self, taken=(), down=0):
self.taken: set[str] = set(taken)
self.down, self.visible = down, set()
self.claims, self.groups, self.freed, self.updates, self.closed = [], {}, [], [], 0
def claim(self, name, entries, group=None):
if self.down:
self.down -= 1
raise ConnectionRefusedError(111, 'avahi down')
self.claims.append((name, entries))
if name in self.taken:
if group is not None:
self.free(group)
return None
if group is not None:
self.updates.append(group)
return group
group = f'/group/{len(self.claims)}'
self.groups[group] = mdns.ESTABLISHED
return group
def state(self, group):
return self.groups[group]
def free(self, group):
self.freed.append(group)
self.groups.pop(group, None)
def close(self):
self.closed += 1
class Reply:
def __init__(self, *body, error=None):
self.body = body
fields = {HeaderFields.error_name: error} if error else {}
self.header = SimpleNamespace(message_type=MessageType.error if error else MessageType.method_return, fields=fields)
class FakeConnection:
"""Scripted avahi D-Bus replies, keyed by member name."""
def __init__(self, states=(mdns.ESTABLISHED,), fail=None, error='org.freedesktop.Avahi.CollisionError', group=('/Client1/EntryGroup1',)):
self.calls, self.states, self.fail, self.error, self.group, self.closed = [], list(states), fail, error, group, False
def send_and_get_reply(self, message, timeout=None):
member = message.header.fields[HeaderFields.member]
self.calls.append((member, message.body))
if member == self.fail:
return Reply('Local name collision', error=self.error)
if member == 'EntryGroupNew':
return Reply(*self.group)
if member == 'GetState':
return Reply(self.states.pop(0) if len(self.states) > 1 else self.states[0])
return Reply()
def close(self):
self.closed = True
class MdnsTest(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.TemporaryDirectory()
self.name_file = Path(self.tmp.name) / 'mdns_name'
for name, value in (('_published', None), ('_redirected', False)): # module state the publisher and Redirect share
patcher = patch.object(mdns, name, value)
patcher.start()
self.addCleanup(patcher.stop)
def tearDown(self):
self.tmp.cleanup()
def run_publish(self, avahi, address_seq, check=None, ipv6=lambda name: None, retry=0):
stop = threading.Event()
sequence = iter(address_seq)
def addresses():
try:
value = next(sequence)
except StopIteration:
stop.set()
return {}
if check is not None:
check()
return value
mdns.publish(stop, avahi=avahi, addresses=addresses, ipv6=ipv6, index=index, taken=lambda name, own: name in avahi.visible,
name_file=self.name_file, refresh=0, retry=retry)
def names(self, avahi):
return [name for name, _ in avahi.claims]
def test_interface_addresses_skip_missing_and_non_candidate_interfaces(self):
self.assertEqual(mdns.interface_addresses(ifaddr_lookup), {'wlan0': '192.168.35.249', 'galaxy0': '172.31.254.1'})
self.assertEqual(mdns.interface_addresses(Mock(side_effect=OSError)), {})
with patch.object(subprocess, 'run', side_effect=AssertionError('subprocess')):
mdns.interface_addresses(ifaddr_lookup)
def test_each_interface_answers_with_its_own_address(self):
found = {'wlan0': '10.10.99.177', 'galaxy0': '172.31.254.1', 'eth0': '100.64.0.2'}
entries = mdns.records(found, ipv6=lambda name: 'fe80::1' if name == 'wlan0' else None, index=index)
self.assertEqual(entries, ((12, mdns.PROTO_INET, '10.10.99.177'), (12, mdns.PROTO_INET6, 'fe80::1'),
(29, mdns.PROTO_INET, '172.31.254.1')))
self.assertEqual(mdns.records({'wlan0': '10.10.99.177', 'galaxy0': '172.31.254.1'}, ipv6=lambda name: None,
index=lambda name: index(name) if name == 'galaxy0' else (_ for _ in ()).throw(OSError())),
((29, mdns.PROTO_INET, '172.31.254.1'),))
def test_first_device_gets_galaxy_local(self):
avahi, seen = FakeAvahi(), []
self.run_publish(avahi, [{'wlan0': '192.168.1.5', 'galaxy0': '172.31.254.1'}] * 2,
check=lambda: seen.append(mdns.published_record()))
self.assertEqual(self.names(avahi), ['galaxy.local'])
self.assertEqual(seen[-1], ('galaxy.local', ('192.168.1.5', '172.31.254.1')))
self.assertIsNone(mdns.published_record())
self.assertEqual(avahi.freed, ['/group/1'])
self.assertEqual(avahi.closed, 1)
self.assertEqual(self.name_file.read_text().strip(), 'galaxy.local')
def test_collision_walks_to_next_name_and_remembers_it(self):
avahi = FakeAvahi(taken={'galaxy.local'})
self.run_publish(avahi, [{'wlan0': '192.168.1.6'}])
self.assertEqual(self.names(avahi), ['galaxy.local', 'galaxy-2.local'])
self.assertEqual(mdns.load_name(self.name_file), 'galaxy-2.local')
# Next boot keeps galaxy-2 even when galaxy.local is free.
avahi = FakeAvahi()
self.run_publish(avahi, [{'wlan0': '192.168.1.6'}])
self.assertEqual(self.names(avahi), ['galaxy-2.local'])
def test_remembered_name_taken_falls_back_to_first_free(self):
mdns.save_name('galaxy-2.local', self.name_file)
avahi = FakeAvahi(taken={'galaxy-2.local'})
self.run_publish(avahi, [{'wlan0': '192.168.1.6'}])
self.assertEqual(self.names(avahi), ['galaxy-2.local', 'galaxy.local'])
self.assertEqual(mdns.load_name(self.name_file), 'galaxy.local')
def test_hotspot_coming_up_republishes_same_name_with_its_address(self):
avahi = FakeAvahi()
self.run_publish(avahi, [{'wlan0': '192.168.1.5'}, {'wlan0': '192.168.1.5', 'galaxy0': '172.31.254.1'}])
self.assertEqual(avahi.claims, [('galaxy.local', ((12, 0, '192.168.1.5'),)),
('galaxy.local', ((12, 0, '192.168.1.5'), (29, 0, '172.31.254.1')))])
self.assertEqual(avahi.updates, ['/group/1'], 'the established group is republished in place')
def test_network_switch_keeps_the_name_even_if_our_old_address_still_answers(self):
avahi = FakeAvahi()
asked = []
def stale_answer(name, own):
asked.append(name)
return name == 'galaxy.local' and '10.10.99.177' not in own # avahi still returns our old work address
stop, steps = threading.Event(), iter([{'wlan0': '10.10.99.177'}, {'wlan0': '172.20.10.4'}])
def addresses():
try:
return next(steps)
except StopIteration:
stop.set()
return {}
mdns.publish(stop, avahi=avahi, addresses=addresses, ipv6=lambda name: None, index=index, taken=stale_answer,
name_file=self.name_file, refresh=0, retry=0)
self.assertEqual(self.names(avahi), ['galaxy.local', 'galaxy.local'])
self.assertEqual(asked, ['galaxy.local'], 'an in-place update never re-checks a name we hold')
self.assertEqual(mdns.load_name(self.name_file), 'galaxy.local')
def test_our_earlier_addresses_never_count_as_another_device(self):
run = Mock(return_value=SimpleNamespace(stdout='galaxy.local\t10.10.99.177\n'))
avahi = FakeAvahi()
taken = lambda name, own: mdns.held_elsewhere(name, own, run) # noqa: E731
entries = ((12, 0, '172.20.10.4'),)
self.assertEqual(mdns._claim(avahi, entries, None, threading.Event(), taken, {'10.10.99.177'})[0], 'galaxy.local')
self.assertEqual(mdns._claim(FakeAvahi(), entries, None, threading.Event(), taken)[0], 'galaxy-2.local')
def test_failed_in_place_update_falls_back_to_a_fresh_claim(self):
avahi = FakeAvahi()
def lose_name_on_update():
if len(avahi.claims) == 1:
avahi.taken.add('galaxy.local')
self.run_publish(avahi, [{'wlan0': '192.168.1.5'}, {'wlan0': '192.168.1.9'}], check=lose_name_on_update)
# update collides, the fresh claim probes galaxy.local once more, then moves on
self.assertEqual(self.names(avahi), ['galaxy.local', 'galaxy.local', 'galaxy.local', 'galaxy-2.local'])
def test_lost_name_is_reclaimed(self):
avahi = FakeAvahi()
def collide_later():
if len(avahi.claims) == 1 and avahi.groups:
avahi.groups['/group/1'] = 3 # another device won the name
self.run_publish(avahi, [{'wlan0': '192.168.1.5'}] * 3, check=collide_later)
self.assertEqual(len(avahi.claims), 2)
def test_names_answered_elsewhere_are_skipped_without_probing(self):
avahi = FakeAvahi()
avahi.visible = {'galaxy.local'}
self.run_publish(avahi, [{'wlan0': '192.168.1.6'}])
self.assertEqual(self.names(avahi), ['galaxy-2.local'])
def test_held_elsewhere_ignores_our_own_addresses(self):
def run(out):
return Mock(return_value=SimpleNamespace(stdout=out))
own = {'192.168.1.6', '172.31.254.1'}
self.assertTrue(mdns.held_elsewhere('galaxy.local', own, run('galaxy.local\t192.168.1.7\n')))
self.assertFalse(mdns.held_elsewhere('galaxy.local', own, run('galaxy.local\t172.31.254.1\n')))
self.assertFalse(mdns.held_elsewhere('galaxy.local', own, run('Failed to resolve host name')))
self.assertFalse(mdns.held_elsewhere('galaxy.local', own, Mock(side_effect=subprocess.TimeoutExpired('x', 1))))
def test_all_names_taken_publishes_nothing(self):
avahi = FakeAvahi(taken=set(mdns.NAMES))
self.run_publish(avahi, [{'wlan0': '192.168.1.5'}])
self.assertEqual(len(avahi.claims), len(mdns.NAMES))
self.assertIsNone(mdns.load_name(self.name_file))
def test_no_lan_address_publishes_nothing(self):
avahi = FakeAvahi()
self.run_publish(avahi, [{}, {'ppp0': '10.228.238.20'}])
self.assertEqual(avahi.claims, [])
def test_avahi_down_logs_once_and_retries(self):
logged = []
avahi = FakeAvahi(down=3)
with patch.object(mdns, '_log', side_effect=lambda message, warning=True: logged.append(message)):
self.run_publish(avahi, [{'wlan0': '192.168.1.5'}] * 5)
self.assertEqual(sum('avahi unavailable' in m for m in logged), 1)
self.assertEqual(self.names(avahi), ['galaxy.local'])
self.assertIn('published galaxy.local on wlan0', logged)
self.assertFalse(any('192.168.1.5' in m for m in logged), 'LAN addresses stay out of swaglog')
def test_retry_waits_after_failure(self):
avahi = FakeAvahi(down=1)
self.run_publish(avahi, [{'wlan0': '192.168.1.5'}] * 3, retry=3600)
self.assertEqual(avahi.claims, [])
def test_stop_wakes_publisher_promptly(self):
stop = threading.Event()
worker = threading.Thread(target=mdns.publish, args=(stop,), kwargs={
'avahi': FakeAvahi(), 'addresses': dict, 'taken': lambda name, own: False, 'name_file': self.name_file, 'refresh': 60})
worker.start()
stop.set()
worker.join(2)
self.assertFalse(worker.is_alive())
def test_avahi_claim_publishes_every_record_then_waits_for_probe(self):
connection = FakeConnection(states=[1, mdns.ESTABLISHED])
avahi = mdns.Avahi(connect=lambda: connection)
entries = ((12, 0, '10.10.99.177'), (12, 1, 'fe80::1'), (29, 0, '172.31.254.1'))
self.assertEqual(avahi.claim('galaxy.local', entries), '/Client1/EntryGroup1')
added = [body for member, body in connection.calls if member == 'AddAddress']
self.assertEqual(added, [(n, p, mdns.PUBLISH_NO_REVERSE, 'galaxy.local', a) for n, p, a in entries])
self.assertEqual([m for m, _ in connection.calls].count('Commit'), 1)
def test_avahi_claim_frees_group_on_collision_or_error(self):
for connection in (FakeConnection(states=[3]), FakeConnection(fail='AddAddress')):
avahi = mdns.Avahi(connect=lambda c=connection: c)
self.assertIsNone(avahi.claim('galaxy.local', ((12, 0, '10.10.99.177'),)))
self.assertEqual(connection.calls[-1][0], 'Free')
def test_avahi_other_errors_are_failures_not_taken_names(self):
connection = FakeConnection(fail='AddAddress', error='org.freedesktop.Avahi.NotPermittedError')
with self.assertRaises(mdns.AvahiError):
mdns.Avahi(connect=lambda: connection).claim('galaxy.local', ((12, 0, '10.10.99.177'),))
self.assertEqual(connection.calls[-1][0], 'Free')
def test_malformed_avahi_reply_is_an_error(self):
for group in ((), (7,)):
with self.assertRaises(mdns.AvahiError):
mdns.Avahi(connect=lambda g=group: FakeConnection(group=g)).claim('galaxy.local', ((12, 0, '10.10.99.177'),))
def test_claim_stops_waiting_for_probe_on_stop(self):
stop = threading.Event()
stop.set()
connection = FakeConnection(states=[1])
self.assertIsNone(mdns.Avahi(connect=lambda: connection, stopped=stop.is_set).claim('galaxy.local', ((12, 0, '10.10.99.177'),)))
self.assertEqual([m for m, _ in connection.calls].count('GetState'), 1)
avahi = FakeAvahi()
self.assertEqual(mdns._claim(avahi, ((12, 0, '10.10.99.177'),), None, stop, lambda name, own: False), (None, None))
self.assertEqual(avahi.claims, [])
def test_claim_with_our_group_resets_it_in_place(self):
connection = FakeConnection()
group = mdns.Avahi(connect=lambda: connection).claim('galaxy.local', ((12, 0, '172.20.10.4'),), group='/Client1/EntryGroup1')
self.assertEqual(group, '/Client1/EntryGroup1')
self.assertEqual([m for m, _ in connection.calls][:3], ['Reset', 'AddAddress', 'Commit'])
self.assertNotIn('EntryGroupNew', [m for m, _ in connection.calls])
self.assertNotIn('Free', [m for m, _ in connection.calls])
def test_avahi_reconnects_after_connection_loss(self):
connections = [Mock(send_and_get_reply=Mock(side_effect=ConnectionResetError())), FakeConnection()]
avahi = mdns.Avahi(connect=lambda: connections.pop(0))
with self.assertRaises(ConnectionResetError):
avahi.state('/group')
self.assertIsNone(avahi.connection)
self.assertEqual(avahi.state('/group'), mdns.ESTABLISHED)
def test_bad_remembered_name_ignored(self):
self.name_file.write_text('evil.example\n')
self.assertIsNone(mdns.load_name(self.name_file))
def test_redirect_targets_only_own_addresses_and_resyncs_on_change(self):
calls = []
def run(cmd, **kwargs):
calls.append(cmd[7:]) # drop sudo -n iptables -w 2 -t nat
return SimpleNamespace(returncode=1 if cmd[7] == '-C' else 0)
redirect = mdns.Redirect(8082, run=run, which=lambda name: f'/usr/sbin/{name}')
redirect.sync(['192.168.35.249', '172.31.254.1'])
self.assertIn(['-I', 'PREROUTING', '-p', 'tcp', '--dport', '80', '-j', 'GALAXY_HTTP'], calls)
self.assertEqual([c for c in calls if c[0] == '-A'], [
['-A', 'GALAXY_HTTP', '-d', '172.31.254.1', '-p', 'tcp', '-j', 'REDIRECT', '--to-ports', '8082'],
['-A', 'GALAXY_HTTP', '-d', '192.168.35.249', '-p', 'tcp', '-j', 'REDIRECT', '--to-ports', '8082']])
calls.clear()
redirect.sync(['172.31.254.1', '192.168.35.249'])
self.assertEqual(calls, []) # unchanged set: no sudo on the poll
redirect.sync(['192.168.35.50', '100.64.0.1'])
self.assertEqual(calls, [['-F', 'GALAXY_HTTP'],
['-A', 'GALAXY_HTTP', '-d', '192.168.35.50', '-p', 'tcp', '-j', 'REDIRECT', '--to-ports', '8082']])
def test_redirect_failure_is_logged_not_retried_every_poll(self):
run = Mock(side_effect=subprocess.TimeoutExpired('sudo', 5))
redirect = mdns.Redirect(8082, run=run, which=lambda name: '/usr/sbin/iptables')
redirect.sync(['192.168.35.249'])
redirect.sync(['192.168.35.249'])
self.assertEqual(run.call_count, 1) # tried once, not on every poll
mdns.Redirect(8082, run=run, which=lambda name: None).sync(['192.168.35.249'])
self.assertEqual(run.call_count, 1)
def test_link_local_reads_proc(self):
proc = Path(self.tmp.name) / 'if_inet6'
proc.write_text('\n'.join(['fe80000000000000020af5fffe66c88a 0c 40 20 80 wlan0',
'2001db80000000000000000000000001 0c 40 00 00 wlan0',
'fe800000000000000000000000000001 1d 40 20 80 galaxy0']) + '\n')
self.assertEqual(mdns.link_local('wlan0', proc), 'fe80::20a:f5ff:fe66:c88a')
self.assertIsNone(mdns.link_local('eth0', proc))
self.assertIsNone(mdns.link_local('wlan0', Path(self.tmp.name) / 'missing'))
def test_published_url_drops_the_port_only_while_port_80_redirects(self):
with patch.object(mdns, '_published', None):
self.assertIsNone(mdns.published_url(8082))
with patch.object(mdns, '_published', ('galaxy-2.local', ('192.168.1.5',))):
run = Mock(return_value=SimpleNamespace(returncode=0))
redirect = mdns.Redirect(8082, run=run, which=lambda name: '/usr/sbin/iptables')
self.assertEqual(mdns.published_url(8082), 'http://galaxy-2.local:8082/')
redirect.sync(['192.168.1.5'])
self.assertEqual(mdns.published_url(8082), 'http://galaxy-2.local/')
redirect.close()
self.assertEqual(mdns.published_url(8082), 'http://galaxy-2.local:8082/')
with patch.object(mdns, '_log'):
mdns.Redirect(8082, run=Mock(side_effect=OSError('denied')), which=lambda name: '/usr/sbin/iptables').sync(['192.168.1.5'])
self.assertEqual(mdns.published_url(8082), 'http://galaxy-2.local:8082/')
def test_redirect_close_removes_rules_once(self):
calls = []
redirect = mdns.Redirect(8082, run=lambda cmd, **kw: calls.append(cmd[7:]) or SimpleNamespace(returncode=0),
which=lambda name: '/usr/sbin/iptables')
redirect.close()
self.assertEqual(calls, []) # never installed: nothing to remove
redirect.sync(['192.168.35.249'])
calls.clear()
redirect.close()
self.assertEqual([c[0] for c in calls], ['-D', '-F', '-X'])
calls.clear()
redirect.close()
self.assertEqual(calls, [])
def test_oversized_name_file_ignored(self):
self.name_file.write_text('galaxy.local' + ' ' * 100)
self.assertIsNone(mdns.load_name(self.name_file))
def test_unexpected_crash_is_logged_and_cleans_up(self):
redirect = Mock()
with patch.object(mdns, 'Redirect', return_value=redirect), \
patch.object(mdns, 'publish', side_effect=RuntimeError('boom')), \
patch('openpilot.common.swaglog.cloudlog.exception') as logged:
mdns.run(threading.Event(), 8082)
logged.assert_called_once()
redirect.close.assert_called_once()
if __name__ == '__main__':
unittest.main()
@@ -280,7 +280,9 @@ class NavigationHttpTest(unittest.TestCase):
self.assertNotIn('Coffee Shop',self.navigation.path.read_text()) self.assertNotIn('Coffee Shop',self.navigation.path.read_text())
self.assertNotIn('pk.synthetic',json.dumps(result)) self.assertNotIn('pk.synthetic',json.dumps(result))
self.assertEqual(self.action('selectPlace',id=identity,searchId=search['searchId'])[0],400) self.assertEqual(self.action('selectPlace',id=identity,searchId=search['searchId'])[0],400)
self.assertEqual(self.action('favorite',destination=result['destination'],label='work')[0],400) status, kept, _ = self.action('favorite',destination=result['destination'],label='work')
self.assertEqual((status,kept['destination']['temporary'],kept['favorites'][0]['name']),(200,True,'Coffee Shop'))
self.assertEqual(self.action('removeFavorite',id=kept['favorites'][0]['id'])[1]['favorites'],[])
status, saved, _ = self.action('favorite',destination={'name':'Work address','latitude':41.,'longitude':-91.},label='work') status, saved, _ = self.action('favorite',destination={'name':'Work address','latitude':41.,'longitude':-91.},label='work')
self.assertEqual(status,200) self.assertEqual(status,200)
self.assertEqual(saved['favorites'][0]['label'],'work') self.assertEqual(saved['favorites'][0]['label'],'work')
@@ -314,17 +316,18 @@ class NavigationHttpTest(unittest.TestCase):
patch('openpilot.starpilot.navigation.owner.response_json', return_value=suggestion)): patch('openpilot.starpilot.navigation.owner.response_json', return_value=suggestion)):
self.assertEqual(self.request('/api/navigation/search',payload=search(),cookie=self.local_cookie)[1]['provider'], 'mapbox') self.assertEqual(self.request('/api/navigation/search',payload=search(),cookie=self.local_cookie)[1]['provider'], 'mapbox')
def test_temporary_search_result_cannot_be_saved(self): def test_search_result_can_be_saved(self):
self.action('configure', patch={'token':'pk.synthetic','enabled':True}) self.action('configure', patch={'token':'pk.synthetic','enabled':True})
search = {'query':'coffee', 'searchId':str(uuid.uuid4()), 'clientId':str(uuid.uuid4())} search = {'query':'coffee', 'searchId':str(uuid.uuid4()), 'clientId':str(uuid.uuid4())}
suggestion = {'suggestions':[{'mapbox_id':'poi/id','name':'Coffee Shop','feature_type':'poi'}]} poi = {'mapbox_id':'poi/id','name':'Coffee Shop','feature_type':'poi'}
with patch('openpilot.starpilot.navigation.owner.response_json',return_value=suggestion) as provider: feature = {'features':[{'properties':poi, 'geometry':{'coordinates':[-90.,40.]}}]}
with patch('openpilot.starpilot.navigation.owner.response_json',side_effect=[{'suggestions':[poi]}, feature]) as provider:
self.assertEqual(self.request('/api/navigation/search',payload=search,cookie=self.local_cookie)[0],200) self.assertEqual(self.request('/api/navigation/search',payload=search,cookie=self.local_cookie)[0],200)
status, body, _ = self.action('favoritePlace',id='poi/id',searchId=search['searchId'],label='home') status, body, _ = self.action('favoritePlace',id='poi/id',searchId=search['searchId'],label='home')
self.assertEqual(status,400) self.assertEqual(status,200)
self.assertIn('cannot be saved',body['error']) self.assertEqual(provider.call_count,2)
self.assertEqual(provider.call_count,1) self.assertEqual([(row['name'], row['label']) for row in body['favorites']], [('Coffee Shop', 'home')])
self.assertEqual(self.navigation.read()['favorites'],[]) self.assertEqual([row['name'] for row in self.navigation.read()['favorites']], ['Coffee Shop'])
def test_status_poll_with_route_key_omits_unchanged_route(self): def test_status_poll_with_route_key_omits_unchanged_route(self):
self.action('configure', patch={'token':'pk.synthetic','enabled':True}) self.action('configure', patch={'token':'pk.synthetic','enabled':True})
@@ -66,7 +66,23 @@ vm.adopt({ ...value, editable: false })
const before = sent.length const before = sent.length
assert.equal(await vm.send({ action: 'cellular', value: false }), false) assert.equal(await vm.send({ action: 'cellular', value: false }), false)
assert.equal(sent.length, before) assert.equal(sent.length, before)
const companion = { protocol: 1, enabled: true, connected: true, active: true, bytes: 13212672 }
globalThis.fetch = async url => ({ ok: true, json: async () => String(url).includes('companion') ? companion : value })
await vm.refresh()
const phoneDetail = () => NetworksPage.computed.phoneDetail.call(vm)
assert.equal(phoneDetail(), "Active · 12.6 MB of the phone's mobile data today")
vm.phone = { ...companion, active: false }
assert.match(phoneDetail(), /^Ready\./)
vm.phone = { ...companion, connected: false }
assert.equal(phoneDetail(), '')
vm.busy = false
globalThis.fetch = async url => String(url).includes('companion') ? { ok: false, status: 500, json: async () => ({ error: 'down' }) } : { ok: true, json: async () => value }
await vm.refresh()
assert.equal(vm.phone, null)
assert.equal(vm.error, '')
assert.ok(NetworksPage.template.includes('Internet from Android app'))
vm.stop() vm.stop()
assert.equal(vm.phone, null)
assert.equal(NetworksPage.components.ConnectionLogs, ConnectionLogs) assert.equal(NetworksPage.components.ConnectionLogs, ConnectionLogs)
assert.ok(NetworksPage.template.includes("<ConnectionLogs v-if=\"mode === 'local'\" panel")) assert.ok(NetworksPage.template.includes("<ConnectionLogs v-if=\"mode === 'local'\" panel"))
@@ -1408,7 +1408,7 @@ for (const invalidOffset of [true, null, "1", NaN, Infinity, -5.1, 5.1]) {
const document = { ...speedAdjustment.document, speedDisplayOffset: invalidOffset } const document = { ...speedAdjustment.document, speedDisplayOffset: invalidOffset }
assert.equal(validDocument(document, speedAdjustment.metadata), false) assert.equal(validDocument(document, speedAdjustment.metadata), false)
} }
assert.ok(SETTINGS_SECTIONS.find(section => section.id === "developer").pages.includes("developer")) assert.ok(SETTINGS_SECTIONS.find(section => section.id === "device").pages.includes("developer"))
// C4 has one locked camera widget covering the road panel. // C4 has one locked camera widget covering the road panel.
@@ -135,10 +135,12 @@ assert.equal(OnroadLayoutPage.methods.projectionLeadInfoRow.call(leadVm).availab
OnroadLayoutPage.methods.setProjectionDisplay.call(leadVm, "leadIndicator", "On") OnroadLayoutPage.methods.setProjectionDisplay.call(leadVm, "leadIndicator", "On")
OnroadLayoutPage.methods.setProjectionLeadInfo.call(leadVm, "Speed") OnroadLayoutPage.methods.setProjectionLeadInfo.call(leadVm, "Speed")
assert.deepEqual([leadVm.state.draft.leadIndicator, leadVm.state.draft.leadInfo], [true, "Speed"]) assert.deepEqual([leadVm.state.draft.leadIndicator, leadVm.state.draft.leadInfo], [true, "Speed"])
assert.deepEqual(OnroadLayoutPage.methods.projectionLeadInfoRow.call(leadVm).choices, ["Off", "Distance", "Speed"]) assert.deepEqual(OnroadLayoutPage.methods.projectionLeadInfoRow.call(leadVm).choices, ["Off", "Distance", "Speed", "Relative speed"])
OnroadLayoutPage.methods.setProjectionLeadInfo.call(leadVm, "Relative speed")
assert.equal(leadVm.state.draft.leadInfo, "Relative speed")
OnroadLayoutPage.methods.setProjectionLeadInfo.call(leadVm, "Both") OnroadLayoutPage.methods.setProjectionLeadInfo.call(leadVm, "Both")
assert.equal(leadVm.state.draft.leadInfo, "Speed") assert.equal(leadVm.state.draft.leadInfo, "Relative speed")
assert.equal(leadChanges.length, 2) assert.equal(leadChanges.length, 3)
assert.equal(validDocument({ ...native.document, signalBorder: true }, native.metadata), false, "the comma screen keeps its C4 settings") assert.equal(validDocument({ ...native.document, signalBorder: true }, native.metadata), false, "the comma screen keeps its C4 settings")
assert.match(OnroadLayoutPage.template, /Personality alerts follow the comma screen setting\./) assert.match(OnroadLayoutPage.template, /Personality alerts follow the comma screen setting\./)
assert.doesNotMatch(OnroadLayoutPage.template, /setProjectionDisplay\('hidePersonalityAlerts', value\)/) assert.doesNotMatch(OnroadLayoutPage.template, /setProjectionDisplay\('hidePersonalityAlerts', value\)/)
@@ -274,8 +274,8 @@ class SettingsGatewayTest(unittest.TestCase):
self.assertNotEqual(first["view"], second["view"]) self.assertNotEqual(first["view"], second["view"])
self.assertEqual(first["rows"], second["rows"]) self.assertEqual(first["rows"], second["rows"])
first_row = first["rows"][0] first_row = first["rows"][0]
self.assertEqual(first_row["value"], "On") self.assertEqual(first_row["value"], "Off")
self.params.put_bool("LaneCentering", True, block=True) self.params.put_bool("LaneCentering", False, block=True)
row = self.page("lane")["rows"][0] row = self.page("lane")["rows"][0]
self.assertEqual(first_row["value"], row["value"]) self.assertEqual(first_row["value"], row["value"])
self.assertNotEqual(first_row["revision"], row["revision"]) self.assertNotEqual(first_row["revision"], row["revision"])
@@ -1300,35 +1300,6 @@ class SettingsGatewayTest(unittest.TestCase):
self.assertTrue(_onroad_preference("lane", key)) self.assertTrue(_onroad_preference("lane", key))
self.assertFalse(_onroad_preference("torque", "reset_profiles")) self.assertFalse(_onroad_preference("torque", "reset_profiles"))
def test_parked_clearance_needs_radar_and_master_switch(self):
def row(label):
page = self.page("lane")
index = next(i for i, item in enumerate(page["rows"]) if item["label"] == label)
return page, index, page["rows"][index]
self.assertFalse(row("Parked car clearance")[2]["available"])
cp = SimpleNamespace(**vars(self.context.value.cp), radarUnavailable=False)
self.context.value = AuthorityContext(True, cp, b"radar")
page, index, toggle = row("Parked car clearance")
self.assertTrue(toggle["available"])
self.assertEqual(toggle["value"], "Off")
self.assertFalse(row("Parked car target gap")[2]["available"])
intent = self.gateway.preview(page["view"], index, 0, self.session, self.generation, value="On")
self.assertTrue(self.gateway.confirm(intent["intent"], self.session, self.generation))
self.assertEqual(Path(self.params.get_param_path("ParkedClearance")).read_bytes(), b"1")
page, index, gap = row("Parked car target gap")
self.assertTrue(gap["available"])
self.assertEqual((gap["value"], gap["minimum"], gap["maximum"], gap["unit"]), ("1.5", 1.0, 2.5, "m"))
intent = self.gateway.preview(page["view"], index, 0, self.session, self.generation, value=1.8)
self.assertTrue(self.gateway.confirm(intent["intent"], self.session, self.generation))
self.assertEqual(Path(self.params.get_param_path("ParkedClearanceGap")).read_bytes(), b"1.8")
from openpilot.starpilot.lateral.parked_runtime import ParkedSettings, read_settings
self.assertEqual(read_settings(self.params), ParkedSettings(True, 1.8))
page, index, shift = row("Parked car max shift")
self.assertEqual((shift["value"], shift["minimum"], shift["maximum"], shift["unit"]), ("0.3", 0.1, 0.8, "m"))
intent = self.gateway.preview(page["view"], index, 0, self.session, self.generation, value=0.45)
self.assertTrue(self.gateway.confirm(intent["intent"], self.session, self.generation))
self.assertEqual(read_settings(self.params), ParkedSettings(True, 1.8, 0.45))
def test_live_lane_rejects_unsupported_vehicle_and_master_dependency(self): def test_live_lane_rejects_unsupported_vehicle_and_master_dependency(self):
self.params.put_bool("LaneCentering", False, block=True) self.params.put_bool("LaneCentering", False, block=True)
tagged, _ = self._live_lane_context() tagged, _ = self._live_lane_context()
@@ -196,8 +196,6 @@ const page = { initialPage: "hub", activeSection: lateral, state: { query: "", d
{ label: "SLC", page: "slc" }, { label: "AOL", page: "aol" }, { label: "Lane", page: "lane" }, { label: "SLC", page: "slc" }, { label: "AOL", page: "aol" }, { label: "Lane", page: "lane" },
] } } } ] } } }
assert.deepEqual(SettingsPage.computed.visibleRows.call(page).map(({ index }) => index), [1, 2]) assert.deepEqual(SettingsPage.computed.visibleRows.call(page).map(({ index }) => index), [1, 2])
page.state.query = "lane"
assert.deepEqual(SettingsPage.computed.visibleRows.call(page).map(({ index }) => index), [2])
// Single-page sections open their controls in one tap, including when moving // Single-page sections open their controls in one tap, including when moving
// from another section's child page. Multi-page sections still use the hub. // from another section's child page. Multi-page sections still use the hub.
@@ -208,7 +206,6 @@ for (const id of ["wheel", "sounds", "device", "visual"]) {
const section = SETTINGS_SECTIONS.find((item) => item.id === id) const section = SETTINGS_SECTIONS.find((item) => item.id === id)
SettingsPage.methods.selectSection.call(navigation, section) SettingsPage.methods.selectSection.call(navigation, section)
assert.equal(navigation.state.section, id) assert.equal(navigation.state.section, id)
assert.equal(navigation.state.query, "")
} }
assert.deepEqual(destinations, ["wheel", "sounds", "hub", "hub"]) assert.deepEqual(destinations, ["wheel", "sounds", "hub", "hub"])
navigation.busy = true navigation.busy = true
@@ -221,7 +218,7 @@ for (const id of ["wheel", "sounds"]) {
} }
const deviceData = SETTINGS_SECTIONS.find((item) => item.id === "device") const deviceData = SETTINGS_SECTIONS.find((item) => item.id === "device")
assert.deepEqual(deviceData.pages, ["power", "data", "starport_options", "browser_preferences", "localization"]) assert.deepEqual(deviceData.pages, ["power", "data", "starport_options", "browser_preferences", "localization", "developer"])
assert.equal(SettingsPage.computed.atSectionRoot.call({ activeSection: deviceData, assert.equal(SettingsPage.computed.atSectionRoot.call({ activeSection: deviceData,
state: { data: { page: "hub" } } }), true) state: { data: { page: "hub" } } }), true)
assert.equal(SettingsPage.computed.atSectionRoot.call({ activeSection: deviceData, assert.equal(SettingsPage.computed.atSectionRoot.call({ activeSection: deviceData,
@@ -229,11 +226,11 @@ assert.equal(SettingsPage.computed.atSectionRoot.call({ activeSection: deviceDat
const dataLinks = SettingsPage.computed.visibleRows.call({ initialPage: "hub", activeSection: deviceData, const dataLinks = SettingsPage.computed.visibleRows.call({ initialPage: "hub", activeSection: deviceData,
state: { query: "", data: { page: "hub", rows: [] } } }) state: { query: "", data: { page: "hub", rows: [] } } })
assert.deepEqual(dataLinks.map(({ row }) => row.page), ["power", "data", "starport_options", "browser_preferences", "localization"]) assert.deepEqual(dataLinks.map(({ row }) => row.page), ["power", "data", "starport_options", "browser_preferences", "localization", "developer"])
assert.equal(dataLinks[1].row.label, "Data & Connections") assert.equal(dataLinks[1].row.label, "Data & Connections")
const coolingLinks = SettingsPage.computed.visibleRows.call({ initialPage: "hub", activeSection: deviceData, const coolingLinks = SettingsPage.computed.visibleRows.call({ initialPage: "hub", activeSection: deviceData,
state: { query: "", data: { page: "hub", rows: [], coolingAvailable: true } } }) state: { query: "", data: { page: "hub", rows: [], coolingAvailable: true } } })
assert.deepEqual(coolingLinks.map(({ row }) => row.page), ["power", "data", "starport_options", "browser_preferences", "localization"]) assert.deepEqual(coolingLinks.map(({ row }) => row.page), ["power", "data", "starport_options", "browser_preferences", "localization", "developer"])
assert.equal(coolingLinks[1].row.label, "Data & Connections") assert.equal(coolingLinks[1].row.label, "Data & Connections")
assert.equal(dataLinks[0].row.label, "Power & Cooling") assert.equal(dataLinks[0].row.label, "Power & Cooling")
assert.equal(coolingLinks[0].row.label, "Power & Cooling") assert.equal(coolingLinks[0].row.label, "Power & Cooling")
@@ -1,4 +1,5 @@
from types import SimpleNamespace from types import SimpleNamespace
from typing import cast
import pytest import pytest
@@ -25,7 +26,7 @@ def test_invalid_and_unauthorized_requests_do_not_write(tmp_path):
params = params_at(tmp_path) params = params_at(tmp_path)
for mode in ("developer", "", True, None, {}): for mode in ("developer", "", True, None, {}):
with pytest.raises(ValueError): with pytest.raises(ValueError):
save_mode(params, mode, authorized=lambda: True) save_mode(params, cast(str, mode), authorized=lambda: True)
with pytest.raises(RuntimeError): with pytest.raises(RuntimeError):
save_mode(params, "advanced", authorized=lambda: False) save_mode(params, "advanced", authorized=lambda: False)
assert not (tmp_path / "d" / KEY).exists() assert not (tmp_path / "d" / KEY).exists()
@@ -165,7 +165,7 @@ await revoked.respond(0, { code: "access_unavailable" }, 503)
assert.equal(revoked.unauthorized, 1) assert.equal(revoked.unauthorized, 1)
assert.equal(revoked.states.at(-1).status, "idle") assert.equal(revoked.states.at(-1).status, "idle")
assert.match(SettingsPage.template, /SoundPacks v-if="state\.data\.page === 'sounds'"/) assert.match(SettingsPage.template, /<div v-if="state\.data\.page === 'sounds'"[^>]*><SoundPacks\b/)
const settingsRefresh = { state: { data: { page: "sounds" }, pending: { intent: "open" }, soundChoicesDirty: false }, const settingsRefresh = { state: { data: { page: "sounds" }, pending: { intent: "open" }, soundChoicesDirty: false },
feed: { saving: false, loadCalls: [], load(page, options) { this.loadCalls.push([page, options]) } }, feed: { saving: false, loadCalls: [], load(page, options) { this.loadCalls.push([page, options]) } },
flushSoundChoices: SettingsPage.methods.flushSoundChoices } flushSoundChoices: SettingsPage.methods.flushSoundChoices }
@@ -8,6 +8,8 @@ from typing import Any
import threading import threading
import unittest import unittest
from openpilot.starpilot.ui.feature_settings_state import SettingLevel, is_heading, setting_levels
class TestVehicleNavigation(unittest.TestCase): class TestVehicleNavigation(unittest.TestCase):
def gateway(self, *, supported=True, parked=True, numeric_only=False): def gateway(self, *, supported=True, parked=True, numeric_only=False):
@@ -18,16 +20,21 @@ class TestVehicleNavigation(unittest.TestCase):
gateway = next(node for node in source.body if isinstance(node, ast.ClassDef) and node.name == 'SettingsGateway') gateway = next(node for node in source.body if isinstance(node, ast.ClassDef) and node.name == 'SettingsGateway')
page = next(node for node in gateway.body if isinstance(node, ast.FunctionDef) and node.name == 'page') page = next(node for node in gateway.body if isinstance(node, ast.FunctionDef) and node.name == 'page')
namespace: dict[str, Any] = {'hashlib': hashlib, 'secrets': secrets, 'SettingsUnavailable': RuntimeError, namespace: dict[str, Any] = {'hashlib': hashlib, 'secrets': secrets, 'SettingsUnavailable': RuntimeError,
'_session_key': lambda token: token.encode(), '_projection': lambda row: {}, '_View': lambda *args: args} '_session_key': lambda token: token.encode(), '_projection': lambda row, level: {}, '_View': lambda *args: args,
'is_heading': is_heading, 'setting_levels': setting_levels, 'read_mode': lambda _: {'mode': 'simple'}}
exec(compile(ast.Module(body=constants + [page], type_ignores=[]), 'settings.py', 'exec'), namespace) exec(compile(ast.Module(body=constants + [page], type_ignores=[]), 'settings.py', 'exec'), namespace)
control = SimpleNamespace(choices=('Off', 'On'), page='') def row(page='', choices=()):
states = {name: SimpleNamespace(title=name, subtitle='', parked=parked, rows=()) for name in namespace['PAGES']} return SimpleNamespace(key='', page=page, choices=choices, level=None)
control = row(choices=('Off', 'On'))
states = {name: SimpleNamespace(page=name, title=name, subtitle='', parked=parked, rows=(), level=SettingLevel.SIMPLE,
row_level=lambda row: SettingLevel.SIMPLE) for name in namespace['PAGES']}
pages = ('aol', 'lane_change', 'lane', 'torque', 'torque/developer') pages = ('aol', 'lane_change', 'lane', 'torque', 'torque/developer')
for name in pages: for name in pages:
states[name].rows = (control,) states[name].rows = (control,)
states['torque/developer'].rows = (SimpleNamespace(choices=(), page=''),) if numeric_only else (control,) if supported else () states['torque/developer'].rows = (row(),) if numeric_only else (control,) if supported else ()
states['hub'].rows = tuple(SimpleNamespace(choices=(), page=name) for name in pages) states['hub'].rows = tuple(row(page=name) for name in pages)
owner = SimpleNamespace(views={}, lock=threading.Lock(), clock=lambda: 100., _clean=lambda: None, owner = SimpleNamespace(params=None, views={}, lock=threading.Lock(), clock=lambda: 100., _clean=lambda: None,
_context=lambda page: SimpleNamespace(cp=SimpleNamespace(carFingerprint='TESLA_MODEL_Y'), cp_raw=b'cp'), _context=lambda page: SimpleNamespace(cp=SimpleNamespace(carFingerprint='TESLA_MODEL_Y'), cp_raw=b'cp'),
_state=lambda page, ctx: states[page]) _state=lambda page, ctx: states[page])
return lambda: namespace['page'](owner, 'hub', 'session', b'generation') return lambda: namespace['page'](owner, 'hub', 'session', b'generation')
@@ -7,6 +7,7 @@ import { GxNotice } from "./notice.js"
export function validLocalAccess(value) { export function validLocalAccess(value) {
if (!value || typeof value.available !== "boolean" || typeof value.reason !== "string" || value.reason.length > 1024 || if (!value || typeof value.available !== "boolean" || typeof value.reason !== "string" || value.reason.length > 1024 ||
!Array.isArray(value.addresses) || value.addresses.length > 32 || value.available !== (value.addresses.length > 0)) return false !Array.isArray(value.addresses) || value.addresses.length > 32 || value.available !== (value.addresses.length > 0)) return false
if (value.name !== undefined && (typeof value.name !== "string" || value.name !== "" && !/^http:\/\/galaxy(-[2-9])?\.local(:\d{1,5})?\/$/.test(value.name))) return false
return value.addresses.every(address => { return value.addresses.every(address => {
if (!address || !["interface", "label", "url"].every(key => typeof address[key] === "string" && address[key].length > 0 && address[key].length <= 512)) return false if (!address || !["interface", "label", "url"].every(key => typeof address[key] === "string" && address[key].length > 0 && address[key].length <= 512)) return false
try { try {
@@ -106,7 +107,8 @@ export const LocalAccess = {
<GxNotice v-if="state.error" tone="danger">{{ state.error }}</GxNotice> <GxNotice v-if="state.error" tone="danger">{{ state.error }}</GxNotice>
<template v-else-if="state.data?.available"> <template v-else-if="state.data?.available">
<p>Connect your phone to the Galaxy hotspot or the same network as your comma, then open an address below. No Internet or Galaxy password needed.</p> <p>Connect your phone to the Galaxy hotspot or the same network as your comma, then open an address below. No Internet or Galaxy password needed.</p>
<ul class="gx-stack"><li v-for="address in state.data.addresses" :key="address.interface + address.url"><a :href="address.url" target="_blank" rel="noopener" class="gx-btn gx-btn--tonal gx-wrap">{{ address.label }} · {{ address.url }}</a></li></ul> <ul class="gx-stack"><li v-if="state.data.name"><a :href="state.data.name" target="_blank" rel="noopener" class="gx-btn gx-btn--tonal gx-wrap">This comma · {{ state.data.name }}</a></li><li v-for="address in state.data.addresses" :key="address.interface + address.url"><a :href="address.url" target="_blank" rel="noopener" class="gx-btn gx-btn--tonal gx-wrap">{{ address.label }} · {{ address.url }}</a></li></ul>
<p v-if="state.data.name" class="gx-note">The first comma on a network is galaxy.local; the next ones become galaxy-2.local, galaxy-3.local, and so on.</p>
<p class="gx-note">Use the full http:// address and bookmark it. Allow local-network access if prompted. Your Firestar Link uses Internet instead.</p> <p class="gx-note">Use the full http:// address and bookmark it. Allow local-network access if prompted. Your Firestar Link uses Internet instead.</p>
</template> </template>
<p v-else-if="state.data" class="gx-note" role="status">{{ state.data.reason || 'The comma has no local network address available.' }}</p> <p v-else-if="state.data" class="gx-note" role="status">{{ state.data.reason || 'The comma has no local network address available.' }}</p>

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