mirror of
https://github.com/firestar5683/StarPilot.git
synced 2026-12-02 06:53:40 +08:00
Merge branch 'testing' into HotspotDriveJoin
This commit is contained in:
@@ -218,7 +218,7 @@ jobs:
|
||||
env:
|
||||
RAYLIB_BACKEND: headless
|
||||
STARPILOT_TEST_DIAGNOSTICS: ci-results/host-test-diagnostics/unittest
|
||||
run: tools/op.sh test --json-output unit-test-results.json
|
||||
run: tools/op.sh test --jobs 2 --json-output unit-test-results.json
|
||||
- name: Test GM vehicle configurations and CAN behavior
|
||||
if: ${{ !cancelled() && steps.build.outcome == 'success' }}
|
||||
timeout-minutes: 5
|
||||
|
||||
@@ -67,6 +67,7 @@ class CANFDLfaStatus:
|
||||
self.display_fault_since_ns = 0
|
||||
self.display_last_active_ns = 0
|
||||
self.popup_last_applied_ns = 0
|
||||
self.ccnc_last_owned_ns = 0
|
||||
|
||||
def update(self, can_packets):
|
||||
boot_clock = getattr(time, 'CLOCK_BOOTTIME', None)
|
||||
@@ -185,6 +186,20 @@ class CANFDLfaStatus:
|
||||
return True
|
||||
return 0 < self.popup_last_applied_ns <= now_ns <= self.popup_last_applied_ns + DISPLAY_RELEASE_NS
|
||||
|
||||
def owns_ccnc_fault_status(self, now_ns, *, healthy=False, qualified_warning=False):
|
||||
body = self.current(now_ns)
|
||||
eps_fresh = 0 < self.eps_observed_ns <= now_ns and now_ns - self.eps_observed_ns <= MAX_AGE_NS
|
||||
indication = ((body[4] >> 6) | ((body[5] & 1) << 2)) if body is not None else 7
|
||||
normal = body is not None and indication < 4 and not (body[6] & 0xF0 or body[7] >> 4 == 15)
|
||||
if (not healthy or body is None or not self.camera_integrity or not eps_fresh or not self.eps_healthy or
|
||||
not (normal or (qualified_warning and self._ownership_warning(body)))):
|
||||
self.ccnc_last_owned_ns = 0
|
||||
return False
|
||||
if qualified_warning:
|
||||
self.ccnc_last_owned_ns = now_ns
|
||||
return True
|
||||
return 0 < self.ccnc_last_owned_ns <= now_ns <= self.ccnc_last_owned_ns + MAX_AGE_NS
|
||||
|
||||
def last_fault(self):
|
||||
body = self.body
|
||||
if body is not None and (body[6] & 0xC0 or body[7] & 0xF0 or ((body[4] >> 6) | ((body[5] & 1) << 2)) >= 4):
|
||||
|
||||
@@ -27,6 +27,7 @@ from opendbc.car.hyundai.ray_pedal import create_ray_pedal_command, ray_pedal_ga
|
||||
from opendbc.car.hyundai.ioniq6_longitudinal import Ioniq6LongitudinalPolicy
|
||||
from opendbc.car.hyundai.ioniq6_bsm import BlindspotStatus
|
||||
from opendbc.car.hyundai.canfd_dash_icons import CanFDDashIcons
|
||||
from opendbc.car.hyundai.canfd_lfa_status import preserves_stock_lfa
|
||||
from opendbc.car.hyundai.classic_scc_aol import qualified as qualified_classic_stock_aol
|
||||
from opendbc.car.hyundai.classic_long_aol import AOL_EXPERIENCE, qualified as qualified_classic_long_aol
|
||||
from opendbc.car.hyundai.canfd_stock_aol import qualified as qualified_canfd_stock_aol, qualified_long as qualified_canfd_long_aol
|
||||
@@ -168,6 +169,7 @@ class CarController(CarControllerBase):
|
||||
not CP.openpilotLongitudinalControl and CP.pcmCruise and
|
||||
int(CP.safetyConfigs[-1].safetyParam) in (0x0811, 0x0891))
|
||||
self.canfd_torque_aol_status = (qualified_canfd_stock_aol(CP) or qualified_canfd_long_aol(CP))
|
||||
self.ccnc_fault_ownership_required = preserves_stock_lfa(CP)
|
||||
self.canfd_dash_icons = CanFDDashIcons() if ioniq6_status or self.canfd_torque_aol_status else None
|
||||
self.classic_dash_icons = CanFDDashIcons() if classic_aol_dash_enabled(CP) else None
|
||||
self.classic_lfa_icon = None
|
||||
@@ -419,6 +421,7 @@ class CarController(CarControllerBase):
|
||||
_projection = self.learning_projection_observer
|
||||
can_sends = []
|
||||
stock_popup_owned = False
|
||||
stock_ccnc_owned = False
|
||||
canfd_lfa_icon = (self.canfd_dash_icons.update(self.frame, CC.enabled, CC.latActive)
|
||||
if self.canfd_dash_icons is not None else None)
|
||||
|
||||
@@ -548,6 +551,9 @@ class CarController(CarControllerBase):
|
||||
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,
|
||||
qualified_warning=stock_owned_status)
|
||||
if ccnc_non_lka:
|
||||
stock_ccnc_owned = stock_source.owns_ccnc_fault_status(clock_boot_ns(), healthy=display_healthy,
|
||||
qualified_warning=stock_owned_status)
|
||||
damping_source = getattr(CS, "stock_lkas_damping", None)
|
||||
can_sends.extend(hyundaicanfd.create_steering_messages(self.packer, self.CP, self.CAN,
|
||||
steering_status_active, apply_steer_req, apply_torque,
|
||||
@@ -586,7 +592,8 @@ class CarController(CarControllerBase):
|
||||
can_sends.extend(hyundaicanfd.create_ccnc(self.packer, self.CAN, self.CP.openpilotLongitudinalControl,
|
||||
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.is_metric, CS.out, CS.out.cruiseState.available, CC.latActive))
|
||||
CS.is_metric, CS.out, CS.out.cruiseState.available, CC.latActive,
|
||||
owned_lfa_status=(stock_ccnc_owned if self.ccnc_fault_ownership_required else None)))
|
||||
self.last_ccnc_161_ts_ns = CS.ccnc_161_ts_ns
|
||||
self.last_ccnc_162_ts_ns = CS.ccnc_162_ts_ns
|
||||
else:
|
||||
|
||||
@@ -327,12 +327,13 @@ def create_ioniq6_blindspot_status(counter: int, status: BlindspotStatus, *, bus
|
||||
|
||||
# Source-derived CCNC camera display transform; the repository MIT notice applies.
|
||||
def create_ccnc(packer, CAN, openpilot_longitudinal, enabled, hud, left_blinker, right_blinker, msg_161, msg_162, msg_1b5,
|
||||
is_metric, out, main_cruise_enabled, lfa_icon):
|
||||
if lfa_icon:
|
||||
is_metric, out, main_cruise_enabled, lfa_icon, *, owned_lfa_status=None):
|
||||
if owned_lfa_status or (owned_lfa_status is None and lfa_icon):
|
||||
# The host owns lateral; keep unrelated faults and obstruction warnings.
|
||||
for field in ("FAULT_LSS", "FAULT_HDA", "FAULT_DAS", "FAULT_LFA", "FAULT_DAW"):
|
||||
if msg_162.get(field) == 1:
|
||||
msg_162[field] = 0
|
||||
if lfa_icon:
|
||||
if msg_161.get("ALERTS_2") == 5:
|
||||
msg_161.update({"ALERTS_2": 0, "SOUNDS_2": 0})
|
||||
if msg_161.get("ALERTS_3") == 17:
|
||||
|
||||
@@ -7,7 +7,7 @@ from opendbc.car import Bus, gen_empty_fingerprint, structs
|
||||
from opendbc.car.hyundai.canfd_lfa_status import CANFDClusterStatus, CANFDLfaStatus, preserves_stock_lfa
|
||||
from opendbc.car.hyundai.hyundaicanfd import CLUSTER_CONTROL_MASK, CanBus, create_lfahda_cluster, hkg_can_fd_checksum
|
||||
from opendbc.car.hyundai.interface import CarInterface
|
||||
from opendbc.car.hyundai.values import CAR, DBC
|
||||
from opendbc.car.hyundai.values import CAR, DBC, HyundaiFlags
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
@@ -389,6 +389,10 @@ def test_actual_interface_preserves_body_icons_cadence_and_identical_steering(ca
|
||||
_, original = reference.apply(command.as_reader(), clock[0])
|
||||
assert [p for p in own if p[0] == 0x12A] == [p for p in original if p[0] == 0x12A]
|
||||
messages = [p for p in own if p[0] == 0x1E0]
|
||||
if cp.flags & HyundaiFlags.CCNC:
|
||||
assert not messages
|
||||
assert not any(p[0] in (0x161, 0x162) for p in own)
|
||||
continue
|
||||
assert len(messages) == int(tick % 5 == 0)
|
||||
if messages:
|
||||
original_cluster = next(p for p in original if p[0] == 0x1E0)
|
||||
@@ -862,3 +866,124 @@ def test_same_batch_ownership_requires_valid_ordered_healthy_predecessor(failure
|
||||
owned = source.owns_display_status(tick >= 2, clock[0], healthy=failure != 'host_fault')
|
||||
assert owned == (failure == 'none')
|
||||
assert not source.owns_display_status(False, clock[0] + 3_000_000_000, healthy=True)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('car', (CAR.HYUNDAI_KONA_EV_2ND_GEN, CAR.HYUNDAI_KONA_2ND_GEN, CAR.HYUNDAI_KONA_HEV_2ND_GEN,
|
||||
CAR.HYUNDAI_SANTA_CRUZ_2025, CAR.HYUNDAI_SONATA_2024,
|
||||
CAR.HYUNDAI_SONATA_HEV_2024, CAR.HYUNDAI_TUCSON_2025,
|
||||
CAR.HYUNDAI_TUCSON_HEV_2025, CAR.KIA_K5_2025))
|
||||
@pytest.mark.parametrize('alpha', (False, True))
|
||||
@pytest.mark.parametrize('failure', ('none', 'host_fault', 'eps_fault', 'camera_fault', 'higher_grade'))
|
||||
def test_actual_ccnc_handover_keeps_owned_warning_quiet_and_real_faults_visible(car, alpha, failure, clock):
|
||||
cp = params(car, alpha=alpha)
|
||||
ci = CarInterface(cp)
|
||||
ci.update([])
|
||||
packer = CANPacker(DBC[car][Bus.pt])
|
||||
bus = ci.CC.CAN
|
||||
decoder = CANParser(DBC[car][Bus.pt], [('CCNC_0x161', 0), ('CCNC_0x162', 0)], bus.ECAN)
|
||||
command = structs.CarControl.new_message()
|
||||
fields = ('FAULT_LSS', 'FAULT_HDA', 'FAULT_DAS', 'FAULT_LFA', 'FAULT_DAW')
|
||||
seen = 0
|
||||
for tick in range(100):
|
||||
clock[0] = 40_000_000_000 + tick * 10_000_000
|
||||
command.enabled = command.latActive = 2 <= tick < 30
|
||||
faulted = failure != 'none' and tick >= 40
|
||||
stock = template(packer, bus.CAM, tick % 256, warning=15 if 14 <= tick < 75 else 0,
|
||||
fault=int(faulted and failure == 'camera_fault'))
|
||||
if faulted and failure == 'higher_grade':
|
||||
data = bytearray(stock[1])
|
||||
data[4], data[5] = (data[4] & 0x3F) | 0x40, data[5] | 1
|
||||
data[:2] = hkg_can_fd_checksum(0x12A, None, data).to_bytes(2, 'little')
|
||||
stock = stock[0], bytes(data), stock[2]
|
||||
frames = [p for p in physical_frames(ci, packer, tick, stock) if not (p[0] == 0xEA and p[2] == bus.ECAN)]
|
||||
frames.append(packer.make_can_msg('MDPS', bus.ECAN, {'COUNTER': tick % 256,
|
||||
'MDPS_LkaToiActvSta': int(4 <= tick < 32), 'MDPS_LkaFailSta': int(faulted and failure == 'eps_fault')}))
|
||||
if tick % 5 == 0:
|
||||
faults = dict.fromkeys(fields, int(14 <= tick < 80))
|
||||
frames.extend([packer.make_can_msg('CCNC_0x161', bus.CAM, {'COUNTER': tick // 5 % 256}),
|
||||
packer.make_can_msg('CCNC_0x162', bus.CAM, {'COUNTER': tick // 5 % 256, 'FAULT_FSS': 2, **faults})])
|
||||
state = ci.update([(clock[0], frames)])
|
||||
assert state.canValid
|
||||
if faulted and failure == 'host_fault':
|
||||
ci.CS.out.accFaulted = True
|
||||
_, packets = ci.apply(command.as_reader(), clock[0])
|
||||
display = [p for p in packets if p[0] in (0x161, 0x162)]
|
||||
if not display:
|
||||
continue
|
||||
seen += 1
|
||||
decoder.update([(clock[0], display)])
|
||||
for field in fields:
|
||||
assert decoder.vl['CCNC_0x162'][field] == int(faulted and 14 <= tick < 80), (tick, failure, field)
|
||||
assert decoder.vl['CCNC_0x162']['FAULT_FSS'] == 2
|
||||
assert decoder.vl['CCNC_0x161']['LFA_ICON'] == (2 if command.latActive else 0)
|
||||
assert decoder.vl['CCNC_0x161']['CENTERLINE'] == int(command.latActive)
|
||||
assert seen == 19
|
||||
|
||||
|
||||
@pytest.mark.parametrize('failure', ('expired', 'backward', 'negative', 'host_fault', 'eps_fault', 'stale_eps', 'stale_camera', 'stale_camera_qualified',
|
||||
'camera_crc', 'camera_fault', 'higher_grade', 'unqualified_warning'))
|
||||
def test_ccnc_normal_camera_handover_requires_current_health_and_expires(failure, clock):
|
||||
packer = CANPacker(DBC[CAR.HYUNDAI_KONA_2ND_GEN][Bus.pt])
|
||||
source = CANFDLfaStatus(2)
|
||||
for tick in range(16):
|
||||
clock[0] = 50_000_000_000 + tick * 10_000_000
|
||||
camera = template(packer, 2, tick, warning=15 if tick >= 14 else 0)
|
||||
eps = packer.make_can_msg('MDPS', 0, {'COUNTER': tick, 'MDPS_LkaToiActvSta': int(tick >= 4)})
|
||||
source.update([(clock[0], [eps, camera])])
|
||||
owned = source.owns_display_status(tick >= 2, clock[0], healthy=True)
|
||||
assert source.owns_ccnc_fault_status(clock[0], healthy=True, qualified_warning=owned) == owned
|
||||
assert owned
|
||||
final_owned_ns = clock[0]
|
||||
for tick in range(16, 23):
|
||||
clock[0] += 10_000_000
|
||||
warning = 15 if failure == 'unqualified_warning' else 0
|
||||
camera = template(packer, 2, tick, warning=warning, fault=int(failure == 'camera_fault'))
|
||||
if failure in ('camera_crc', 'higher_grade'):
|
||||
data = bytearray(camera[1])
|
||||
if failure == 'camera_crc':
|
||||
data[0] ^= 1
|
||||
else:
|
||||
data[4], data[5] = (data[4] & 0x3F) | 0x40, data[5] | 1
|
||||
data[:2] = hkg_can_fd_checksum(0x12A, None, data).to_bytes(2, 'little')
|
||||
camera = camera[0], bytes(data), camera[2]
|
||||
eps = packer.make_can_msg('MDPS', 0, {'COUNTER': tick, 'MDPS_LkaFailSta': int(failure == 'eps_fault')})
|
||||
frames = [] if failure == 'stale_eps' else [eps]
|
||||
if failure not in ('stale_camera', 'stale_camera_qualified'):
|
||||
frames.append(camera)
|
||||
source.update([(clock[0], frames)])
|
||||
now = final_owned_ns - 1 if failure == 'backward' else -1 if failure == 'negative' else clock[0]
|
||||
held = source.owns_ccnc_fault_status(now, healthy=failure != 'host_fault',
|
||||
qualified_warning=failure == 'stale_camera_qualified')
|
||||
if failure == 'expired':
|
||||
assert held == (clock[0] - final_owned_ns <= 50_000_000)
|
||||
elif failure in ('stale_eps', 'stale_camera', 'stale_camera_qualified') and tick < 21:
|
||||
continue
|
||||
else:
|
||||
assert not held
|
||||
for tick in range(23, 27):
|
||||
clock[0] += 10_000_000
|
||||
camera = template(packer, 2, tick)
|
||||
eps = packer.make_can_msg('MDPS', 0, {'COUNTER': tick})
|
||||
source.update([(clock[0], [eps, camera])])
|
||||
assert not source.owns_ccnc_fault_status(clock[0], healthy=True, qualified_warning=False)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('fault', range(1, 8))
|
||||
@pytest.mark.parametrize('owned', (False, True))
|
||||
def test_ccnc_fault_handover_preserves_obstruction_and_unknown_codes(fault, owned):
|
||||
from opendbc.car.hyundai.hyundaicanfd import create_ccnc
|
||||
cp = params(CAR.HYUNDAI_KONA_2ND_GEN)
|
||||
bus = CanBus(cp)
|
||||
packer = CANPacker(DBC[cp.carFingerprint][Bus.pt])
|
||||
fields = ('FAULT_LSS', 'FAULT_HDA', 'FAULT_DAS', 'FAULT_LFA', 'FAULT_DAW')
|
||||
original = dict.fromkeys(fields, fault)
|
||||
original.update({'COUNTER': 173, 'FAULT_FCA': 1, 'FAULT_FSS': 2, 'FAULT_ESS': 1, 'FAULT_SCC': 3})
|
||||
messages = create_ccnc(packer, bus, False, False, None, False, False, {'COUNTER': 172}, original.copy(),
|
||||
None, True, None, False, False, owned_lfa_status=owned)
|
||||
decoder = CANParser(DBC[cp.carFingerprint][Bus.pt], [('CCNC_0x161', 0), ('CCNC_0x162', 0)], bus.ECAN)
|
||||
decoder.update([(1_000_000_000, messages)])
|
||||
for field in fields:
|
||||
assert decoder.vl['CCNC_0x162'][field] == (0 if owned and fault == 1 else fault)
|
||||
for field in ('COUNTER', 'FAULT_FCA', 'FAULT_FSS', 'FAULT_ESS', 'FAULT_SCC'):
|
||||
assert decoder.vl['CCNC_0x162'][field] == original[field]
|
||||
assert decoder.vl['CCNC_0x161']['LFA_ICON'] == decoder.vl['CCNC_0x161']['CENTERLINE'] == 0
|
||||
|
||||
@@ -149,7 +149,9 @@ class TestHyundaiFingerprint(unittest.TestCase):
|
||||
self.assertEqual(output_parser.vl["CCNC_0x162"]["COUNTER"], 9)
|
||||
self.assertEqual(output_parser.vl["CCNC_0x161"]["BACKGROUND"], 3)
|
||||
self.assertEqual(output_parser.vl["CCNC_0x162"]["SPEEDLIMIT"], 60)
|
||||
self.assertEqual(output_parser.vl["CCNC_0x162"]["FAULT_DAS"], 0)
|
||||
self.assertTrue(controller.ccnc_fault_ownership_required)
|
||||
self.assertIsNone(state.stock_lfa_status.current(1_000_000_000))
|
||||
self.assertEqual(output_parser.vl["CCNC_0x162"]["FAULT_DAS"], stock_162["FAULT_DAS"])
|
||||
self.assertEqual(output_parser.vl["CCNC_0x162"]["LEAD_DISTANCE"], 47 if alpha_long else 25)
|
||||
for signal, expected in (("ALERTS_3", 7), ("ALERTS_5", 4), ("SOUNDS_3", 5)):
|
||||
self.assertEqual(output_parser.vl["CCNC_0x161"][signal], expected)
|
||||
|
||||
@@ -0,0 +1,170 @@
|
||||
import pytest
|
||||
|
||||
from opendbc.can import CANPacker, CANParser
|
||||
from opendbc.car import Bus, gen_empty_fingerprint, structs
|
||||
from opendbc.car.hyundai.canfd_stock_aol import qualified
|
||||
from opendbc.car.hyundai.hyundaicanfd import CanBus
|
||||
from opendbc.car.hyundai.interface import CarInterface
|
||||
from opendbc.car.hyundai.tests.test_canfd_lfa_status import clock as clock
|
||||
from opendbc.car.hyundai.tests.test_canfd_lfa_status import physical_frames, template
|
||||
from opendbc.car.hyundai.values import CAR, DBC, HyundaiFlags
|
||||
from opendbc.safety.tests.libsafety import libsafety_py
|
||||
|
||||
|
||||
def kona_params(*, pair='both', alpha=False, alternate=False, offset=0, hda2=False):
|
||||
fp = gen_empty_fingerprint()
|
||||
ecan = offset + int(hda2)
|
||||
fp[ecan][0x1AA if alternate else 0x1CF] = 16 if alternate else 8
|
||||
fp[offset + 2][0x1A0] = 32
|
||||
bus = ecan if pair == 'ecan' else offset + 2
|
||||
if pair not in ('none', 'missing_161'):
|
||||
fp[bus][0x161] = 16 if pair == 'short_161' else 32
|
||||
if pair not in ('none', 'missing_162'):
|
||||
fp[bus][0x162] = 16 if pair == 'short_162' else 32
|
||||
if hda2:
|
||||
fp[offset + 2][0x50] = 16
|
||||
return CarInterface.get_params(CAR.HYUNDAI_KONA_EV_2ND_GEN, fp, [], alpha, False, False)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('pair', ('both', 'none', 'missing_161', 'missing_162', 'short_161', 'short_162', 'ecan'))
|
||||
@pytest.mark.parametrize('alpha', (False, True))
|
||||
@pytest.mark.parametrize('alternate', (False, True))
|
||||
@pytest.mark.parametrize('offset', (0, 4))
|
||||
def test_factory_restores_ccnc_profile_for_kona_ev(pair, alpha, alternate, offset):
|
||||
cp = kona_params(pair=pair, alpha=alpha, alternate=alternate, offset=offset)
|
||||
assert cp.flags & HyundaiFlags.CCNC
|
||||
assert cp.pcmCruise and not cp.openpilotLongitudinalControl
|
||||
assert not cp.alphaLongitudinalAvailable
|
||||
expected = 0x409 | (0x20 if alternate else 0)
|
||||
assert cp.safetyConfigs[-1].safetyParam & ~0x800 == expected
|
||||
assert qualified(cp)
|
||||
cp.safetyConfigs[-1].safetyParam |= 0x800
|
||||
assert qualified(cp, marked_only=True)
|
||||
assert CanBus(cp).ECAN == offset
|
||||
|
||||
|
||||
@pytest.mark.parametrize('alpha', (False, True))
|
||||
@pytest.mark.parametrize('alternate', (False, True))
|
||||
def test_hda2_kona_profile_is_unchanged(alpha, alternate):
|
||||
original = kona_params(pair='none', alpha=alpha, alternate=alternate, hda2=True)
|
||||
observed = kona_params(alpha=alpha, alternate=alternate, hda2=True)
|
||||
assert observed.flags & HyundaiFlags.CCNC
|
||||
assert observed.flags == original.flags
|
||||
assert [c.to_dict() for c in observed.safetyConfigs] == [c.to_dict() for c in original.safetyConfigs]
|
||||
|
||||
|
||||
@pytest.mark.parametrize('alpha', (False, True))
|
||||
@pytest.mark.parametrize('failure', ('none', 'eps_fault', 'host_fault', 'camera_fault', 'higher_grade', 'obstruction', 'missing_tracker'))
|
||||
def test_actual_kona_ccnc_sender_uses_qualified_ownership_and_preserves_faults(alpha, failure, clock):
|
||||
cp = kona_params(alpha=alpha)
|
||||
cp.safetyConfigs[-1].safetyParam |= 0x800
|
||||
ci = CarInterface(cp)
|
||||
ci.update([])
|
||||
packer = CANPacker(DBC[CAR.HYUNDAI_KONA_EV_2ND_GEN][Bus.pt])
|
||||
bus = ci.CC.CAN
|
||||
decoder = CANParser(DBC[CAR.HYUNDAI_KONA_EV_2ND_GEN][Bus.pt], [('CCNC_0x161', 0), ('CCNC_0x162', 0)], bus.ECAN)
|
||||
command = structs.CarControl.new_message()
|
||||
seen = 0
|
||||
for tick in range(100):
|
||||
clock[0] = 90_000_000_000 + tick * 10_000_000
|
||||
command.latActive = 2 <= tick < 80
|
||||
faulted = tick >= 40 and failure != 'none'
|
||||
stock = template(packer, bus.CAM, tick, warning=15 if tick >= 14 else 0,
|
||||
fault=int(faulted and failure == 'camera_fault'))
|
||||
if faulted and failure == 'higher_grade':
|
||||
stock = packer.make_can_msg('LFA', bus.CAM, {'COUNTER': tick, 'LKA_SysIndReq': 5, 'LKA_SysWrn': 15})
|
||||
frames = [p for p in physical_frames(ci, packer, tick, stock) if not (p[0] == 0xEA and p[2] == bus.ECAN)]
|
||||
frames.append(packer.make_can_msg('MDPS', bus.ECAN, {'COUNTER': tick, 'MDPS_LkaToiActvSta': int(4 <= tick < 82),
|
||||
'MDPS_LkaFailSta': int(faulted and failure == 'eps_fault')}))
|
||||
if tick % 5 == 0:
|
||||
warning = (2 if faulted and failure == 'obstruction' else 1) if tick >= 15 else 0
|
||||
frames.extend([packer.make_can_msg('CCNC_0x161', bus.CAM, {'COUNTER': tick // 5}),
|
||||
packer.make_can_msg('CCNC_0x162', bus.CAM, {'COUNTER': tick // 5,
|
||||
'FAULT_LSS': warning, 'FAULT_DAS': warning, 'FAULT_FCA': 2})])
|
||||
assert ci.update([(clock[0], frames)]).canValid
|
||||
if faulted and failure == 'host_fault':
|
||||
ci.CS.out.accFaulted = True
|
||||
if faulted and failure == 'missing_tracker':
|
||||
ci.CS.stock_lfa_status = None
|
||||
_, packets = ci.apply(command.as_reader(), clock[0])
|
||||
display = [p for p in packets if p[0] in (0x161, 0x162)]
|
||||
if not display:
|
||||
continue
|
||||
seen += 1
|
||||
decoder.update([(clock[0], display)])
|
||||
expected = (2 if failure == 'obstruction' else 1) if faulted else 0
|
||||
assert decoder.vl['CCNC_0x162']['FAULT_LSS'] == expected
|
||||
assert decoder.vl['CCNC_0x162']['FAULT_DAS'] == expected
|
||||
assert decoder.vl['CCNC_0x162']['FAULT_FCA'] == 2
|
||||
assert decoder.vl['CCNC_0x161']['LFA_ICON'] == (2 if command.latActive else 0)
|
||||
assert seen == 19
|
||||
|
||||
|
||||
@pytest.mark.parametrize('alternate', (False, True))
|
||||
@pytest.mark.parametrize('aol', (False, True))
|
||||
def test_selected_ccnc_native_profile_owns_only_supported_frames(alternate, aol):
|
||||
cp = kona_params(alternate=alternate)
|
||||
if aol:
|
||||
cp.safetyConfigs[-1].safetyParam |= 0x800
|
||||
word = cp.safetyConfigs[-1].safetyParam
|
||||
assert word == (0x429 if alternate else 0x409) | (0x800 if aol else 0)
|
||||
safety = libsafety_py.libsafety
|
||||
safety.set_alternative_experience(0)
|
||||
assert safety.set_safety_hooks(structs.CarParams.SafetyModel.hyundaiCanfd, word) == 0
|
||||
safety.init_tests()
|
||||
packer = CANPacker('hyundai_canfd_generated')
|
||||
for name in ('CCNC_0x161', 'CCNC_0x162'):
|
||||
address, body, bus = packer.make_can_msg(name, 0, {})
|
||||
assert safety.safety_tx_hook(libsafety_py.make_CANPacket(address, bus, body))
|
||||
assert safety.safety_fwd_hook(2, address) == -1
|
||||
assert safety.safety_fwd_hook(2, 0x1A0) == 0
|
||||
assert safety.safety_fwd_hook(0, 0xEA) == 2
|
||||
address, body, bus = packer.make_can_msg('SCC_CONTROL', 0, {'ACCMode': 1, 'aReqValue': 1., 'aReqRaw': 1.})
|
||||
assert not safety.safety_tx_hook(libsafety_py.make_CANPacket(address, bus, body))
|
||||
|
||||
|
||||
@pytest.mark.parametrize('missing', (0x161, 0x162))
|
||||
def test_kona_ccnc_missing_pair_does_not_emit_legacy_or_empty_display(missing, clock):
|
||||
cp = kona_params()
|
||||
ci = CarInterface(cp)
|
||||
ci.update([])
|
||||
packer = CANPacker(DBC[CAR.HYUNDAI_KONA_EV_2ND_GEN][Bus.pt])
|
||||
command = structs.CarControl.new_message(latActive=True)
|
||||
for tick in range(20):
|
||||
clock[0] = 95_000_000_000 + tick * 10_000_000
|
||||
frames = physical_frames(ci, packer, tick, template(packer, ci.CC.CAN.CAM, tick))
|
||||
name = 'CCNC_0x162' if missing == 0x161 else 'CCNC_0x161'
|
||||
frames.append(packer.make_can_msg(name, ci.CC.CAN.CAM, {'COUNTER': tick}))
|
||||
assert ci.update([(clock[0], frames)]).canValid
|
||||
_, packets = ci.apply(command.as_reader(), clock[0])
|
||||
assert any(p[0] == 0x12A for p in packets)
|
||||
assert not any(p[0] in (0x161, 0x162, 0x1E0) for p in packets)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('alpha', (False, True))
|
||||
def test_ccnc_selection_keeps_all_steering_packets_identical(alpha, clock):
|
||||
cp = kona_params(alpha=alpha)
|
||||
cp.safetyConfigs[-1].safetyParam |= 0x800
|
||||
legacy = cp.as_reader().as_builder()
|
||||
legacy.flags = int(legacy.flags) & ~int(HyundaiFlags.CCNC)
|
||||
legacy.safetyConfigs[-1].safetyParam &= ~0x400
|
||||
current, previous = CarInterface(cp), CarInterface(legacy)
|
||||
current.update([])
|
||||
previous.update([])
|
||||
packer = CANPacker(DBC[CAR.HYUNDAI_KONA_EV_2ND_GEN][Bus.pt])
|
||||
command = structs.CarControl.new_message(latActive=True)
|
||||
for tick in range(300):
|
||||
clock[0] = 96_000_000_000 + tick * 10_000_000
|
||||
command.actuators.torque = .2 if tick < 150 else -.2
|
||||
stock = template(packer, current.CC.CAN.CAM, tick % 256, warning=15 if tick >= 14 else 0)
|
||||
frames = [p for p in physical_frames(current, packer, tick, stock) if p[0] not in (0xEA, 0x125)]
|
||||
frames.extend([packer.make_can_msg('MDPS', 0, {'COUNTER': tick % 256, 'MDPS_LkaToiActvSta': int(tick >= 4)}),
|
||||
packer.make_can_msg('STEERING_SENSORS', 0, {'COUNTER': tick % 256, 'STEERING_ANGLE': 95. if tick < 245 else -95.})])
|
||||
if tick % 5 == 0:
|
||||
frames.extend([packer.make_can_msg('CCNC_0x161', 2, {'COUNTER': tick // 5}),
|
||||
packer.make_can_msg('CCNC_0x162', 2, {'COUNTER': tick // 5, 'FAULT_DAS': int(tick >= 15)})])
|
||||
assert current.update([(clock[0], frames)]).canValid
|
||||
assert previous.update([(clock[0], frames)]).canValid
|
||||
_, actual = current.apply(command.as_reader(), clock[0])
|
||||
_, before = previous.apply(command.as_reader(), clock[0])
|
||||
assert [p for p in actual if p[0] == 0x12A] == [p for p in before if p[0] == 0x12A]
|
||||
@@ -389,7 +389,7 @@ class CAR(Platforms):
|
||||
[HyundaiCarDocs("Hyundai Kona Electric (with HDA II, Korea only) 2023", video="https://www.youtube.com/watch?v=U2fOCmcQ8hw",
|
||||
car_parts=CarParts.common([CarHarness.hyundai_r]))],
|
||||
CarSpecs(mass=1740, wheelbase=2.66, steerRatio=13.6, tireStiffnessFactor=0.385),
|
||||
flags=HyundaiFlags.EV | HyundaiFlags.CANFD_NO_RADAR_DISABLE,
|
||||
flags=HyundaiFlags.EV | HyundaiFlags.CANFD_NO_RADAR_DISABLE | HyundaiFlags.CCNC,
|
||||
radar_dbc=HYUNDAI_MRR35_RADAR_DBC,
|
||||
)
|
||||
HYUNDAI_KONA_HEV = HyundaiPlatformConfig(
|
||||
|
||||
@@ -30,7 +30,8 @@ class CarController(CarControllerBase):
|
||||
return
|
||||
self.apply_angle_last = 0
|
||||
self.coop_steer = CooperativeSteeringController()
|
||||
self.coop_enabled = CP.carFingerprint == CAR.TESLA_MODEL_3 and bool(CP.safetyConfigs[0].safetyParam & TeslaSafetyFlags.COOP_STEERING)
|
||||
self.coop_enabled = (CP.carFingerprint in (CAR.TESLA_MODEL_3, CAR.TESLA_MODEL_Y) and
|
||||
bool(CP.safetyConfigs[0].safetyParam & TeslaSafetyFlags.COOP_STEERING))
|
||||
self.steering_limit_info = {}
|
||||
self.packer = CANPacker(dbc_names[Bus.party])
|
||||
self.tesla_can = TeslaCAN(CP, self.packer)
|
||||
|
||||
@@ -32,7 +32,8 @@ class CarState(CarStateBase):
|
||||
self.hands_on_level = 0
|
||||
self.das_control = {}
|
||||
return
|
||||
self.cooperative_steering = CP.carFingerprint == CAR.TESLA_MODEL_3 and bool(CP.safetyConfigs[0].safetyParam & TeslaSafetyFlags.COOP_STEERING)
|
||||
self.cooperative_steering = (CP.carFingerprint in (CAR.TESLA_MODEL_3, CAR.TESLA_MODEL_Y) and
|
||||
bool(CP.safetyConfigs[0].safetyParam & TeslaSafetyFlags.COOP_STEERING))
|
||||
self.can_define = CANDefine(DBC[CP.carFingerprint][Bus.party])
|
||||
self.shifter_values = self.can_define.dv["DI_systemStatus"]["DI_gear"]
|
||||
|
||||
|
||||
@@ -15,7 +15,7 @@ def modern_aol_supported(cp):
|
||||
cp.flags & ~int(TeslaFlags.MISSING_DAS_SETTINGS | TeslaFlags.HAS_VEHICLE_BUS | TeslaFlags.AOL_SCREEN_BUTTON)):
|
||||
return False
|
||||
word = int(cp.safetyConfigs[0].safetyParam)
|
||||
return (word in BASE_WORDS | AOL_WORDS and (not word & 256 or cp.carFingerprint == CAR.TESLA_MODEL_3) and
|
||||
return (word in BASE_WORDS | AOL_WORDS and
|
||||
bool(word & 1) == bool(cp.openpilotLongitudinalControl) and
|
||||
bool(word & 512) == bool(cp.flags & TeslaFlags.AOL_SCREEN_BUTTON) and
|
||||
(not word & 512 or bool(cp.flags & TeslaFlags.HAS_VEHICLE_BUS)))
|
||||
|
||||
@@ -62,10 +62,11 @@ def test_inactive_lateral_resets_override(vehicle_model):
|
||||
@pytest.mark.parametrize(("candidate", "enabled", "expected"), (
|
||||
(CAR.TESLA_MODEL_3, False, False),
|
||||
(CAR.TESLA_MODEL_3, True, True),
|
||||
(CAR.TESLA_MODEL_Y, True, False),
|
||||
(CAR.TESLA_MODEL_Y, False, False),
|
||||
(CAR.TESLA_MODEL_Y, True, True),
|
||||
(CAR.TESLA_MODEL_S_PREAP, True, False),
|
||||
))
|
||||
def test_safety_flag_is_model_3_only(candidate, enabled, expected):
|
||||
def test_safety_flag_is_modern_model_3_y_only(candidate, enabled, expected):
|
||||
params = CarInterface.get_params(candidate, gen_empty_fingerprint(), [], False, False, True)
|
||||
from openpilot.starpilot.car.tesla.coop_preferences import prepare
|
||||
prepare(params, enabled)
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
"""Model Y's real parser/controller stays within the existing native Tesla limits."""
|
||||
import os
|
||||
|
||||
import pytest
|
||||
|
||||
from opendbc.can import CANPacker
|
||||
from opendbc.car import structs
|
||||
from opendbc.car.tesla.carcontroller import CarController
|
||||
from opendbc.car.tesla.interface import CarInterface
|
||||
from opendbc.car.tesla.screen_button import apply_modern_aol, modern_aol_qualified
|
||||
from opendbc.car.tesla.tests.test_screen_button import screen_params
|
||||
from opendbc.car.tesla.values import CAR, DBC
|
||||
from opendbc.safety.tests.libsafety import libsafety_py
|
||||
from openpilot.starpilot.car.tesla.coop_preferences import prepare
|
||||
|
||||
|
||||
@pytest.mark.parametrize('mode', ('stock', 'ordinary', 'screen'))
|
||||
@pytest.mark.parametrize('enabled', (False, True))
|
||||
@pytest.mark.parametrize('long', (False, True))
|
||||
@pytest.mark.parametrize('brake_disengage', (False, True))
|
||||
@pytest.mark.parametrize('speed', (0., 10., 30.))
|
||||
def test_model_y_controller_frames_and_driver_override(mode, enabled, long, brake_disengage, speed):
|
||||
cp = screen_params(CAR.TESLA_MODEL_Y, harness=mode == 'screen', long=long)
|
||||
apply_modern_aol(cp, mode != 'stock', mode == 'screen', brake_disengage)
|
||||
prepare(cp, enabled)
|
||||
assert bool(cp.safetyConfigs[0].safetyParam & 256) is enabled
|
||||
cp.alternativeExperience = 32 if mode != 'stock' else 0
|
||||
assert modern_aol_qualified(cp, marked_only=True) is (mode != 'stock')
|
||||
ci = CarInterface(cp)
|
||||
controller = CarController(DBC[CAR.TESLA_MODEL_Y], cp)
|
||||
assert controller.coop_enabled is enabled
|
||||
assert ci.CS.cooperative_steering is enabled
|
||||
packer = CANPacker('tesla_model3_party')
|
||||
native = libsafety_py.libsafety
|
||||
native.init_tests()
|
||||
native.set_alternative_experience(cp.alternativeExperience)
|
||||
try:
|
||||
result = native.set_safety_hooks(10, cp.safetyConfigs[0].safetyParam)
|
||||
release_long = long and os.environ.get('TESLA_SCREEN_NATIVE_RELEASE') == '1'
|
||||
if release_long and mode != 'stock':
|
||||
assert result == -1
|
||||
return
|
||||
assert result == 0
|
||||
native.set_aol_test_heartbeat(True)
|
||||
cc = structs.CarControl(latActive=True, enabled=True)
|
||||
offsets = []
|
||||
accepted_steering = 0
|
||||
for tick in range(220):
|
||||
now = 1_000_000_000 + tick * 10_000_000
|
||||
native.set_timer(now // 1000)
|
||||
torque = 1.5 if tick < 100 else -1.5 if tick < 210 else 5.01
|
||||
hands = 3 if tick >= 215 else 0
|
||||
messages = (
|
||||
('DAS_control', 2, {}), ('DAS_steeringControl', 2, {}),
|
||||
('SCCM_steeringAngleSensor', 2, {}), ('DAS_status', 2, {}), ('DAS_settings', 2, {}),
|
||||
('DI_speed', 0, {'DI_vehicleSpeed': speed * 3.6}),
|
||||
('ESP_B', 0, {'ESP_vehicleSpeed': speed * 3.6, 'ESP_wheelSpeedsQF': 1, 'ESP_vehicleStandstillSts': int(speed == 0)}),
|
||||
('EPAS3S_sysStatus', 0, {'EPAS3S_internalSAS': 0, 'EPAS3S_eacStatus': 1,
|
||||
'EPAS3S_handsOnLevel': hands, 'EPAS3S_torsionBarTorque': -torque}),
|
||||
('DI_systemStatus', 0, {'DI_gear': 4}), ('ESP_status', 0, {'ESP_driverBrakeApply': 1}),
|
||||
('UI_warning', 0, {'buckleStatus': 1}), ('DI_state', 0, {'DI_cruiseState': 2 if tick >= 12 else 0}),
|
||||
)
|
||||
frames = [packer.make_can_msg(name, bus, values) for name, bus, values in messages]
|
||||
for address, data, bus in frames:
|
||||
assert native.safety_rx_hook(libsafety_py.make_CANPacket(address, bus, data))
|
||||
native.safety_tick()
|
||||
cs = ci.update([(now, frames)])
|
||||
if tick < 14:
|
||||
continue
|
||||
assert cs.canValid and not cs.canTimeout
|
||||
if mode != 'stock':
|
||||
native.aol_set_host_request(1)
|
||||
output, sends = controller.update(cc.as_reader(), ci.CS, now)
|
||||
for address, data, bus in sends:
|
||||
accepted = native.safety_tx_hook(libsafety_py.make_CANPacket(address, bus, data))
|
||||
assert bool(accepted) is not (release_long and address == 0x2B9), (tick, address, output.steeringAngleDeg)
|
||||
accepted_steering += int(address == 0x488)
|
||||
if 30 <= tick < 100:
|
||||
offsets.append(controller.coop_steer.cooperative_offset_deg)
|
||||
if (tick >= 210 and enabled) or tick >= 215:
|
||||
assert cs.steeringDisengage
|
||||
assert not native.get_controls_allowed()
|
||||
assert not controller.steering_limit_info
|
||||
assert accepted_steering > 90
|
||||
assert any(abs(offset) > 0 for offset in offsets) is enabled
|
||||
finally:
|
||||
native.init_tests()
|
||||
native.set_alternative_experience(0)
|
||||
native.set_safety_hooks(0, 0)
|
||||
@@ -473,8 +473,15 @@ def build_priority_tests(site, catalog, core_tests):
|
||||
|
||||
if is_mode:
|
||||
family = src.stem.split("_", 1)[0]
|
||||
family_modules = [name for name in sorted(catalog) if name == f"test_{family}.py" or name.startswith(f"test_{family}_") or
|
||||
(family == "ford" and name == "test_angle_native.py")]
|
||||
aliases = {
|
||||
"hyundai": ("hyundai", "hkg", "ev9", "pe", "ioniq5pe", "ioniq6", "kia", "nexo", "palisade",
|
||||
"classic_scc", "canfd_damping", "prepared_torque_ev"),
|
||||
"volkswagen": ("volkswagen", "meb"),
|
||||
"volvo": ("volvo", "polestar"),
|
||||
"ford": ("ford", "angle_native"),
|
||||
}.get(family, (family,))
|
||||
family_modules = [name for name in sorted(catalog) if any(name == f"test_{alias}.py" or name.startswith(f"test_{alias}_")
|
||||
for alias in aliases)]
|
||||
if family_modules:
|
||||
targets = [test_id for name in family_modules for test_id in catalog[name]]
|
||||
if family == "honda":
|
||||
|
||||
@@ -186,6 +186,26 @@ def test_native_variant(native_variant):
|
||||
self.assertEqual(Counter(ordered), Counter(expected))
|
||||
self.assertEqual(ordered[0], probe)
|
||||
|
||||
def test_vehicle_alias_suites_remain_in_their_mutation_family(self):
|
||||
families = {
|
||||
"hyundai": ("test_hyundai.py", "test_hkg_mode_parity.py", "test_ev9_combined_callers.py", "test_pe_combined_aol.py",
|
||||
"test_ioniq5pe_paired_native.py", "test_ioniq6_native_pedal_order.py", "test_kia_ev6_2025_angle.py",
|
||||
"test_nexo_stock_aol.py", "test_palisade_camera_echo.py", "test_classic_scc_main_ingress.py",
|
||||
"test_canfd_damping_contract.py", "test_prepared_torque_ev_native.py"),
|
||||
"volkswagen": ("test_volkswagen.py", "test_meb_aol.py"),
|
||||
"volvo": ("test_volvo.py", "test_polestar_counters.py"),
|
||||
"ford": ("test_ford.py", "test_angle_native.py"),
|
||||
}
|
||||
catalog = {name: [f"pytest:/tests/{name}::test_guard[DEBUG]", f"pytest:/tests/{name}::test_guard[RELEASE]"]
|
||||
for names in families.values() for name in names}
|
||||
all_targets = [target for targets in catalog.values() for target in targets]
|
||||
for family, names in families.items():
|
||||
with self.subTest(family=family):
|
||||
site = mutation.MutationSite(1, 0, 1, 0, 1, 1, "==", "!=", "comparison",
|
||||
mutation.SAFETY_DIR / f"modes/{family}.h", 1)
|
||||
actual = mutation.build_priority_tests(site, catalog, all_targets)
|
||||
self.assertEqual(Counter(actual), Counter(target for name in names for target in catalog[name]))
|
||||
|
||||
def test_worker_crash_is_infrastructure_error(self):
|
||||
site = self.site()
|
||||
future = Future()
|
||||
|
||||
@@ -50,6 +50,8 @@ A_CRUISE_MAX_BP = [0., 10.0, 25., 40.]
|
||||
J_CRUISE_VALS = [1.6, 1.2, 0.8, 0.6]
|
||||
A_CRUISE_MIN = -0.5
|
||||
CRUISE_ACCEL_RESPONSE_TIME = 2.0
|
||||
SLC_BRAKE_ONSET_JERK = 0.15 # m/s^3: how fast braking may build after an SLC overshoot
|
||||
SLC_BRAKE_ONSET_ACCEL = -0.3 # m/s^2: past this the brakes are engaged and normal jerk resumes
|
||||
CONTROL_N_T_IDX = ModelConstants.T_IDXS[:CONTROL_N]
|
||||
MIN_ALLOW_THROTTLE_SPEED = 2.5
|
||||
NATIVE_ALLOW_THROTTLE_PROBABILITY = 0.4
|
||||
@@ -72,7 +74,7 @@ def get_coast_accel(pitch):
|
||||
def get_cruise_accel(e2e, v_cruise, v_ego, a_cruise_prev, angle_steers, CP, dt, accel_coast, allow_throttle,
|
||||
profile: AppliedProfile | None = None,
|
||||
base_brake_floor: float = A_CRUISE_MIN, selected_acceleration_max: float | None = None, faster_takeoffs: bool = False,
|
||||
*, a_target_prev: float | None = None):
|
||||
*, a_target_prev: float | None = None, ease_slc_braking: bool = False):
|
||||
ceiling = TAKEOFF_ACCEL_MAX if faster_takeoffs else ACCEL_MAX
|
||||
max_accel = ceiling if e2e else get_max_accel(v_ego, faster_takeoffs)
|
||||
if selected_acceleration_max is not None and not e2e:
|
||||
@@ -97,10 +99,16 @@ def get_cruise_accel(e2e, v_cruise, v_ego, a_cruise_prev, angle_steers, CP, dt,
|
||||
speed_error = v_cruise - v_ego
|
||||
if not e2e and not faster_takeoffs and v_ego >= MIN_ALLOW_THROTTLE_SPEED and speed_error > 0.:
|
||||
speed_error /= CRUISE_ACCEL_RESPONSE_TIME
|
||||
elif ease_slc_braking and speed_error < 0.:
|
||||
speed_error /= CRUISE_ACCEL_RESPONSE_TIME # correct an SLC overshoot as gradually as an approach
|
||||
target_accel = np.clip(speed_error, cruise_min, max_accel)
|
||||
j_cruise = np.interp(v_ego, A_CRUISE_MAX_BP, J_CRUISE_VALS)
|
||||
decel_start = a_cruise_prev if a_target_prev is None else min(a_cruise_prev, a_target_prev)
|
||||
target_accel = float(np.clip(target_accel, decel_start - j_cruise * dt, a_cruise_prev + j_cruise * dt))
|
||||
lower = decel_start - j_cruise * dt
|
||||
if ease_slc_braking and decel_start > SLC_BRAKE_ONSET_ACCEL:
|
||||
# Ease braking in from zero so friction brakes engage without a jolt; lifting off the throttle keeps normal jerk.
|
||||
lower = max(lower, min(decel_start, 0.) - SLC_BRAKE_ONSET_JERK * dt)
|
||||
target_accel = float(np.clip(target_accel, lower, a_cruise_prev + j_cruise * dt))
|
||||
|
||||
return target_accel
|
||||
|
||||
@@ -413,7 +421,8 @@ class LongitudinalPlanner:
|
||||
self.a_cruise, steer_angle_without_offset, self.CP, self.dt,
|
||||
accel_coast, self.allow_throttle, cruise_profile,
|
||||
base_brake_floor=global_floor, selected_acceleration_max=selected_acceleration, faster_takeoffs=faster_takeoffs,
|
||||
a_target_prev=self.output_a_target)
|
||||
a_target_prev=self.output_a_target,
|
||||
ease_slc_braking=v_cruise == ceiling.effective_mps and not relevant_lead)
|
||||
if self.button_cruise is not None:
|
||||
button_target = self.button_cruise.sample(
|
||||
sm, now_ns=sample_now_ns, drive_id=drive_id, target_speed=v_cruise,
|
||||
|
||||
@@ -1551,6 +1551,13 @@ class SelfdriveD:
|
||||
if physical_cancel_lateral_allowed(self.CP, CS, intent, native, settings=self.aol_settings,
|
||||
previous=decision, source_ns=source_ns, now_ns=now_ns, axis_session_id=self.aol_session_id):
|
||||
user_disable = any(event.userDisable and event.name != EventName.buttonCancel for event in self.events.to_msg())
|
||||
if user_disable and fresh_successor and self.CP.brand == 'honda':
|
||||
from openpilot.starpilot.car.honda.aol import physical_cancel_lateral_allowed
|
||||
native = current_native(self.sm, self.CP, now_ns=now_ns, axis_session_id=self.aol_session_id)
|
||||
if physical_cancel_lateral_allowed(self.CP, CS, intent, native, settings=self.aol_settings,
|
||||
previous=decision, source_ns=source_ns, now_ns=now_ns, axis_session_id=self.aol_session_id,
|
||||
cancel_samples=getattr(self, 'car_state_envelopes', ())):
|
||||
user_disable = any(event.userDisable and event.name != EventName.buttonCancel for event in self.events.to_msg())
|
||||
if user_disable and fresh_successor and self.ford_source_deadline_supported():
|
||||
from openpilot.starpilot.car.ford.aol import physical_cancel_lateral_allowed
|
||||
native = current_native(self.sm, self.CP, now_ns=now_ns, axis_session_id=self.aol_session_id)
|
||||
@@ -1892,7 +1899,8 @@ class SelfdriveD:
|
||||
honda_cancel_lateral_allowed(self.CP, CS, intent, native,
|
||||
settings=self.aol_settings, previous=getattr(self, 'aol_axis_decision', None),
|
||||
source_ns=getattr(self, 'aol_car_state_log_ns', 0), now_ns=now_ns,
|
||||
axis_session_id=getattr(self, 'aol_session_id', '')) or
|
||||
axis_session_id=getattr(self, 'aol_session_id', ''),
|
||||
cancel_samples=getattr(self, 'car_state_envelopes', ())) or
|
||||
mazda_cancel_lateral_allowed(self.CP, CS, intent, native,
|
||||
settings=self.aol_settings, previous=getattr(self, 'aol_axis_decision', None),
|
||||
source_ns=getattr(self, 'aol_car_state_log_ns', 0), now_ns=now_ns,
|
||||
@@ -2055,7 +2063,8 @@ class SelfdriveD:
|
||||
# Ioniq6 also checks the physical brake before its separately published host sample.
|
||||
# Retain only its already granted LAT; all proof, health and LONG withdrawal gates remain.
|
||||
# The exact vehicle policies and all proof/health checks above remain required.
|
||||
return bool(ordinary_ford or gm_native_accepts_cp(self.CP, native.safetyModel, native.safetyParam) or
|
||||
return bool(ordinary_ford or honda_aol_qualified(self.CP, marked_only=True) or
|
||||
gm_native_accepts_cp(self.CP, native.safetyModel, native.safetyParam) or
|
||||
early_native_long_withdrawal_supported(self.CP) or
|
||||
toyota_longitudinal or
|
||||
not native.pandaInventory[owners[0]].controlsAllowed and
|
||||
|
||||
@@ -31,7 +31,10 @@ class PandadOrder:
|
||||
assert result, self.process.poll()
|
||||
return result
|
||||
|
||||
def step(self, driven, published, now):
|
||||
def step(self, driven, published, now, *, after_health_read=None):
|
||||
health_controls = bool(self.safety.get_controls_allowed()) if after_health_read is not None else None
|
||||
if after_health_read is not None:
|
||||
after_health_read()
|
||||
before = self.status()
|
||||
axis_event = driven['aolAxisState']
|
||||
axis = axis_event.aolAxisState
|
||||
@@ -83,7 +86,7 @@ class PandadOrder:
|
||||
mode,
|
||||
word,
|
||||
32,
|
||||
bool(self.safety.get_controls_allowed()),
|
||||
bool(self.safety.get_controls_allowed()) if health_controls is None else health_controls,
|
||||
not bool(self.safety.safety_config_valid()),
|
||||
False,
|
||||
(int(bool(self.safety.get_relay_malfunction())) | self.reported_diagnostic_mask),
|
||||
|
||||
@@ -4,13 +4,25 @@ from unittest.mock import patch
|
||||
from openpilot.cereal import messaging
|
||||
|
||||
|
||||
def selfdrive_step(sd, published, native, previous_controls, cp, safety, now, *, calibration, driver_lockout=False, driver_monitoring_valid=True):
|
||||
def selfdrive_step(sd, published, native, previous_controls, cp, safety, now, *, calibration, driver_lockout=False,
|
||||
driver_monitoring_valid=True, queued=(), panda_health=None):
|
||||
samples = (*queued, published)
|
||||
cars = iter(sample['carState'] for sample in samples[1:])
|
||||
intents = iter(sample['aolIntentWire'] for sample in samples)
|
||||
|
||||
def receive(sock):
|
||||
if queued and sock is sd.car_state_sock:
|
||||
return next(cars, None)
|
||||
if queued and sock is sd.aol_intent_companion.sock:
|
||||
return next(intents, None)
|
||||
return None
|
||||
|
||||
peers = []
|
||||
for service in sd.sm.data:
|
||||
if service in ('alertDebug', 'lateralManeuverPlan', 'laneChangeAssistWire', 'starpilotLongitudinalPlan'):
|
||||
continue
|
||||
if service == 'aolIntentWire':
|
||||
peers.append(published[service])
|
||||
peers.append(samples[0][service])
|
||||
continue
|
||||
if service == 'aolSafetyWire':
|
||||
peers.append(native.as_reader())
|
||||
@@ -19,6 +31,9 @@ def selfdrive_step(sd, published, native, previous_controls, cp, safety, now, *,
|
||||
if service in previous_controls:
|
||||
peers.append(previous_controls[service])
|
||||
continue
|
||||
if service == 'pandaStates' and panda_health is not None:
|
||||
peers.append(panda_health)
|
||||
continue
|
||||
size = 1 if service == 'pandaStates' else None
|
||||
event = messaging.new_message(service, size, valid=True, logMonoTime=now)
|
||||
value = getattr(event, service)
|
||||
@@ -60,8 +75,8 @@ def selfdrive_step(sd, published, native, previous_controls, cp, safety, now, *,
|
||||
patch('openpilot.selfdrive.selfdrived.selfdrived.time.monotonic_ns', return_value=now),
|
||||
patch('openpilot.selfdrive.selfdrived.selfdrived.time.monotonic', return_value=now / 1e9),
|
||||
patch('openpilot.selfdrive.selfdrived.selfdrived.time.clock_gettime_ns', return_value=now),
|
||||
patch('openpilot.selfdrive.selfdrived.selfdrived.messaging.recv_one_or_none', return_value=None),
|
||||
patch('openpilot.selfdrive.selfdrived.selfdrived.messaging.recv_one', return_value=published['carState']),
|
||||
patch('openpilot.selfdrive.selfdrived.selfdrived.messaging.recv_one_or_none', side_effect=receive),
|
||||
patch('openpilot.selfdrive.selfdrived.selfdrived.messaging.recv_one', return_value=samples[0]['carState']),
|
||||
patch.object(sd.sm, 'update', side_effect=lambda _: sd.sm.update_msgs(now / 1e9, peers)),
|
||||
patch.object(sd.pm, 'send', side_effect=capture),
|
||||
):
|
||||
|
||||
@@ -331,7 +331,8 @@ def test_cancel_retains_existing_native_lateral_only_receipt():
|
||||
|
||||
@pytest.mark.parametrize('mutation', ['none', 'no_latch', 'no_previous', 'lat_denied', 'expired_native',
|
||||
'stale_source', 'session', 'wrong_cp', 'configured_cancel', 'main_off', 'pause', 'eps', 'invalid_can',
|
||||
'no_button', 'protocol', 'inventory'])
|
||||
'no_button', 'protocol', 'inventory', 'buffered', 'buffer_stale', 'buffer_invalid',
|
||||
'buffer_future', 'buffer_no_cancel', 'buffer_can_fault'])
|
||||
def test_honda_cancel_no_entry_exception_requires_existing_current_lateral(mutation):
|
||||
from openpilot.starpilot.car.honda.aol import physical_cancel_lateral_allowed
|
||||
from openpilot.starpilot.aol.runtime import AxisDecision
|
||||
@@ -343,6 +344,20 @@ def test_honda_cancel_no_entry_exception_requires_existing_current_lateral(mutat
|
||||
validUntilMonoTime=NOW + 199_999_500)
|
||||
settings = SimpleNamespace(enabled=True, cancel_actions=(0, 0, 0))
|
||||
previous = AxisDecision(lateral_active=True, native_acknowledged=True)
|
||||
cancel_samples = ()
|
||||
if mutation.startswith('buffer'):
|
||||
sample = messaging.new_message('carState', valid=mutation != 'buffer_invalid', logMonoTime=NOW - 2_000_000)
|
||||
sample.carState = cs.to_dict()
|
||||
cs.buttonEvents = []
|
||||
if mutation == 'buffer_stale':
|
||||
sample.logMonoTime = NOW - 30_000_001
|
||||
if mutation == 'buffer_future':
|
||||
sample.logMonoTime = NOW
|
||||
if mutation == 'buffer_no_cancel':
|
||||
sample.carState.buttonEvents = []
|
||||
if mutation == 'buffer_can_fault':
|
||||
sample.carState.canValid = False
|
||||
cancel_samples = (sample.as_reader(),)
|
||||
if mutation == 'no_latch':
|
||||
intent.allowedLatch = False
|
||||
if mutation == 'no_previous':
|
||||
@@ -374,4 +389,57 @@ def test_honda_cancel_no_entry_exception_requires_existing_current_lateral(mutat
|
||||
if mutation == 'inventory':
|
||||
native = replace(native, pandaInventory=())
|
||||
assert physical_cancel_lateral_allowed(cp, cs, intent, native, settings=settings, previous=previous,
|
||||
source_ns=source, now_ns=NOW, axis_session_id='unit-session') == (mutation == 'none')
|
||||
source_ns=source, now_ns=NOW, axis_session_id='unit-session', cancel_samples=cancel_samples) == (mutation in ('none', 'buffered'))
|
||||
|
||||
|
||||
|
||||
def test_recognized_cancel_retains_intent_across_expired_output_only():
|
||||
cp, cs, sm, native, feedback = fixture(coherent=True, long_allowed=False, brake=False)
|
||||
cs.cruiseState.available = True
|
||||
cs.buttonEvents = [structs.CarState.ButtonEvent(type='cancel', pressed=True)]
|
||||
assert not feedback.observe(sm, cp, cs, NOW, latched=True, cancel_source_ns=NOW)
|
||||
assert feedback.honda_cancel_ns == NOW
|
||||
original = sm['aolAxisState'].validUntilMonoTime
|
||||
cs.buttonEvents = []
|
||||
assert not feedback.observe(sm, cp, cs, NOW + 35_000_000, latched=True)
|
||||
assert feedback.honda_cancel_ns == NOW and sm['aolAxisState'].validUntilMonoTime == original
|
||||
assert original < NOW + 35_000_000
|
||||
assert not native.longitudinalAllowed
|
||||
|
||||
|
||||
@pytest.mark.parametrize('fault', ['no_episode', 'axis_invalid', 'producer_changed', 'explicit_off', 'hard_event',
|
||||
'lat_denied', 'rx_fault', 'expired_original'])
|
||||
def test_cancel_pending_intent_keeps_all_independent_vetoes(fault):
|
||||
cp, cs, sm, native, feedback = fixture(coherent=True, long_allowed=False, brake=False)
|
||||
cs.cruiseState.available = True
|
||||
cs.buttonEvents = [structs.CarState.ButtonEvent(type='cancel', pressed=True)]
|
||||
assert not feedback.observe(sm, cp, cs, NOW, latched=True, cancel_source_ns=NOW)
|
||||
cs.buttonEvents = []
|
||||
now = NOW + 35_000_000
|
||||
if fault == 'no_episode':
|
||||
feedback.honda_cancel_ns = 0
|
||||
elif fault == 'axis_invalid':
|
||||
sm.valid['aolAxisState'] = False
|
||||
elif fault == 'producer_changed':
|
||||
event = sm.messages['aolAxisState'].as_builder()
|
||||
event.aolAxisState.intentProducerSessionId = 'different'
|
||||
sm.messages['aolAxisState'] = event.as_reader()
|
||||
elif fault == 'explicit_off':
|
||||
cs.buttonEvents = [structs.CarState.ButtonEvent(type='lkas', pressed=True)]
|
||||
elif fault == 'hard_event':
|
||||
event = messaging.new_message('onroadEvents', 1, valid=True, logMonoTime=NOW)
|
||||
event.onroadEvents[0].name = 'controlsMismatch'
|
||||
event.onroadEvents[0].immediateDisable = True
|
||||
sm.messages['onroadEvents'] = event.as_reader()
|
||||
elif fault == 'lat_denied':
|
||||
native = replace(native, lateralAllowed=False)
|
||||
elif fault == 'rx_fault':
|
||||
event = sm.messages['pandaStates'].as_builder()
|
||||
event.pandaStates[0].safetyRxChecksInvalid = True
|
||||
sm.messages['pandaStates'] = event.as_reader()
|
||||
else:
|
||||
feedback.honda_cancel_ns = NOW - 201_000_000
|
||||
event = messaging.new_message('aolSafetyWire', 0, valid=True, logMonoTime=native.observedMonoTime)
|
||||
event.aolSafetyWire = encode_safety(native)
|
||||
sm.messages['aolSafetyWire'] = event.as_reader()
|
||||
assert feedback.observe(sm, cp, cs, now, latched=True)
|
||||
|
||||
@@ -90,6 +90,12 @@ class TestHondaCurrentCaller(unittest.TestCase):
|
||||
self.run_current_caller(candidate=CAR.HONDA_CIVIC_BOSCH, word=0,
|
||||
eps_pedal='brake', eps_end=82, eps_brake_end=95)
|
||||
|
||||
def test_alpha_cancel_across_late_host_publication(self):
|
||||
self.run_current_caller(candidate=CAR.HONDA_CIVIC_2022, word=10, alpha=True, hybrid=True, host_scenario='cancel_gap')
|
||||
|
||||
def test_alpha_native_brake_precedes_host_and_health(self):
|
||||
self.run_current_caller(candidate=CAR.HONDA_CIVIC_2022, word=10, alpha=True, hybrid=True, native_brake_first=True)
|
||||
|
||||
def test_diagnostic_during_recovered_reverse(self):
|
||||
self.run_current_caller(candidate=CAR.HONDA_CIVIC_BOSCH, word=0, fault='diagnostic')
|
||||
|
||||
@@ -97,7 +103,8 @@ class TestHondaCurrentCaller(unittest.TestCase):
|
||||
self.run_current_caller(candidate=CAR.HONDA_CIVIC_BOSCH, word=0, fault='relay')
|
||||
|
||||
def run_current_caller(self, *, candidate, word, fault=None, alternate_brake=False, alpha=False, speed_mps=12.5,
|
||||
pedal=False, host_scenario=None, serialized=False, eps_pedal=None, hybrid=False, eps_end=95, eps_repeat=None, eps_brake_end=None):
|
||||
pedal=False, host_scenario=None, serialized=False, eps_pedal=None, hybrid=False, eps_end=95,
|
||||
eps_repeat=None, eps_brake_end=None, native_brake_first=False):
|
||||
safety = libsafety_py.libsafety
|
||||
with (
|
||||
OpenpilotPrefix(),
|
||||
@@ -187,12 +194,13 @@ class TestHondaCurrentCaller(unittest.TestCase):
|
||||
tx_parser = CANParser(tx_dbc.name, tx_messages, ci.CC.CAN.lkas)
|
||||
previous, driven, receipt = structs.CarControl(), {}, None
|
||||
controls_published, controls_latest, driven_new = {}, {}, {}
|
||||
delayed_host = []
|
||||
base = time.monotonic_ns() + 100_000_000
|
||||
try:
|
||||
for tick in range(145):
|
||||
now = base + tick * 10_000_000
|
||||
reengage = host_scenario == 'long_reengage' and tick >= 131
|
||||
cancelled = host_scenario == 'cancel' and tick >= 40
|
||||
cancelled = host_scenario in ('cancel', 'cancel_gap') and tick >= 40
|
||||
if host_scenario == 'settings_off' and tick == 135:
|
||||
from openpilot.starpilot.aol.intent import read_settings
|
||||
saved.put_bool('AlwaysOnLateral', False, block=True)
|
||||
@@ -200,11 +208,12 @@ class TestHondaCurrentCaller(unittest.TestCase):
|
||||
sd.aol_settings = read_settings(saved)
|
||||
# SET press/release is the real first ordinary native grant, preceding engaged HB.
|
||||
eps_active = 80 <= tick < eps_end or eps_repeat is not None and eps_repeat[0] <= tick < eps_repeat[1]
|
||||
brake_active = 50 <= tick < 55 or eps_pedal == 'brake' and (eps_active or eps_brake_end is not None and 80 <= tick < eps_brake_end)
|
||||
brake_active = ((51 if native_brake_first else 50) <= tick < 55 or
|
||||
eps_pedal == 'brake' and (eps_active or eps_brake_end is not None and 80 <= tick < eps_brake_end))
|
||||
incoming = stream.frames(
|
||||
cruise_button=2 if host_scenario == 'cancel' and tick == 40 else
|
||||
cruise_button=2 if host_scenario in ('cancel', 'cancel_gap') and tick == 40 else
|
||||
3 if tick == 20 or host_scenario == 'long_reengage' and tick == 130 else 0,
|
||||
cruise=int(21 <= tick < 50 and not cancelled or reengage),
|
||||
cruise=int(21 <= tick < (51 if native_brake_first else 50) and not cancelled or reengage),
|
||||
brake=brake_active,
|
||||
eps=(2 if eps_pedal else 6) if eps_active else 0,
|
||||
gas=20 if eps_pedal == 'gas' and eps_active else 0,
|
||||
@@ -305,16 +314,31 @@ class TestHondaCurrentCaller(unittest.TestCase):
|
||||
self.assertEqual(cs.gearShifter, structs.CarState.GearShifter.reverse if 110 <= tick < 125 else structs.CarState.GearShifter.drive)
|
||||
self.assertEqual(cs.brakePressed, brake_active)
|
||||
self.assertTrue(cs.cruiseState.available)
|
||||
self.assertEqual(cs.cruiseState.enabled, 21 <= tick < 50 and not cancelled or reengage)
|
||||
self.assertEqual(cs.cruiseState.enabled, 21 <= tick < (51 if native_brake_first else 50) and not cancelled or reengage)
|
||||
intent = decode_intent(published['aolIntentWire'].aolIntentWire)
|
||||
self.assertIsNotNone(intent)
|
||||
# Initial receipt is unavailable until actual negotiator completes its zero acknowledgment.
|
||||
absent = messaging.new_message('aolSafetyWire', 0, valid=False, logMonoTime=now)
|
||||
current_receipt = receipt if receipt is not None else absent
|
||||
driven_new = selfdrive_step(
|
||||
sd, published, current_receipt, controls_published, cp, safety, now, calibration='calibrated',
|
||||
driver_lockout=host_scenario == 'driver_lockout' and tick >= 135,
|
||||
driver_monitoring_valid=not (host_scenario == 'driver_lockout' and tick >= 140))
|
||||
early_order = None
|
||||
if native_brake_first and tick == 50:
|
||||
def native_brake_edge():
|
||||
physical = stream.frames(cruise=1, brake=True, speed_kph=speed_mps * 3.6)
|
||||
for address, payload, bus in physical:
|
||||
self.assertTrue(safety.safety_rx_hook(libsafety_py.make_CANPacket(address, bus, payload)))
|
||||
self.assertFalse(safety.get_controls_allowed())
|
||||
receipt, early_order = pandad.step(driven, published, now, after_health_read=native_brake_edge)
|
||||
current_receipt = receipt
|
||||
if host_scenario == 'cancel_gap' and 40 <= tick <= 42:
|
||||
delayed_host.append(published)
|
||||
driven_new = {}
|
||||
else:
|
||||
driven_new = selfdrive_step(
|
||||
sd, published, current_receipt, controls_published, cp, safety, now, calibration='calibrated',
|
||||
queued=tuple(delayed_host), panda_health=panda.as_reader() if early_order is not None else None,
|
||||
driver_lockout=host_scenario == 'driver_lockout' and tick >= 135,
|
||||
driver_monitoring_valid=not (host_scenario == 'driver_lockout' and tick >= 140))
|
||||
delayed_host.clear()
|
||||
retained = dict(driven)
|
||||
driven.update(driven_new)
|
||||
for service, event in retained.items():
|
||||
@@ -323,8 +347,8 @@ class TestHondaCurrentCaller(unittest.TestCase):
|
||||
self.assertLessEqual(int(event.logMonoTime), now)
|
||||
# Held producer snapshots are only for native observation. Simulated
|
||||
# receivers get each actual new publication once, never a restamp.
|
||||
order = None
|
||||
if tick % 10 == 0:
|
||||
order = early_order
|
||||
if tick % 10 == 0 and early_order is None:
|
||||
receipt, order = pandad.step(driven, published, now)
|
||||
feed(controls, now, tick, enabled=sd.enabled, active=sd.active)
|
||||
plan = messaging.new_message('longitudinalPlan', valid=True, logMonoTime=now)
|
||||
@@ -413,7 +437,7 @@ class TestHondaCurrentCaller(unittest.TestCase):
|
||||
if not previous.latActive:
|
||||
self.assertEqual((tx['torque'], tx['request']), (0, False), row)
|
||||
else:
|
||||
if (alpha and address in (0x1DF, 0x1C8) or pedal and address == 0x200) and tick == (40 if host_scenario == 'cancel' else 50):
|
||||
if (alpha and address in (0x1DF, 0x1C8) or pedal and address == 0x200) and tick == (40 if host_scenario in ('cancel', 'cancel_gap') else 50):
|
||||
# Card applies the prior Controls envelope. Cancel or brake has
|
||||
# already revoked LONG; the native hook must reject this
|
||||
# in-flight positive command before the new envelope arrives.
|
||||
@@ -481,10 +505,22 @@ class TestHondaCurrentCaller(unittest.TestCase):
|
||||
if host_scenario == "long_reengage" and tick == 144:
|
||||
self.assertTrue(command.latActive and command.longActive, row)
|
||||
self.assertEqual(row["permission"], 3, row)
|
||||
if host_scenario == 'cancel_gap' and tick >= 40:
|
||||
self.assertEqual(intent.allowedLatch, not 110 <= tick < 125, row)
|
||||
self.assertFalse(command.longActive, row)
|
||||
if tick == 43:
|
||||
self.assertFalse(previous.latActive or previous.longActive, row)
|
||||
if tick >= 44:
|
||||
self.assertNotIn('controlsMismatch', row['events'], row)
|
||||
if native_brake_first and tick == 50:
|
||||
self.assertTrue(receipt is not None and early_order is not None, row)
|
||||
self.assertTrue(intent.allowedLatch and command.latActive, row)
|
||||
self.assertFalse(command.longActive, row)
|
||||
self.assertNotIn('controlsMismatch', row['events'], row)
|
||||
if cancelled and tick >= 42:
|
||||
self.assertTrue(card.aol_card_intent.allowed_latch and intent.lateralArmed, row)
|
||||
self.assertFalse(command.longActive or row['permission'] & 2, row)
|
||||
if tick < 80 or 105 <= tick < 110 or tick >= 135:
|
||||
if (tick < 80 or 105 <= tick < 110 or tick >= 135) and not (host_scenario == 'cancel_gap' and 42 <= tick <= 43):
|
||||
self.assertTrue(command.latActive and row['permission'] & 1, row)
|
||||
if (95 <= tick < 105 or 125 <= tick < 135) and not row['permission'] & 1:
|
||||
self.assertFalse(command.latActive, row)
|
||||
@@ -508,4 +544,3 @@ class TestHondaCurrentCaller(unittest.TestCase):
|
||||
finally:
|
||||
pandad.close()
|
||||
card.vehicle_startup.close()
|
||||
|
||||
|
||||
@@ -24,8 +24,7 @@ def _configured_transport_native(sm, cp, session, now_ns, native=None, *, requir
|
||||
return None
|
||||
if coherent and (not validated_here and not native_inventory_matches_cp(native, cp) or
|
||||
any(p.safetyRxChecksInvalid or p.heartbeatLost or blocking_fault_mask(p.faults, cp) or
|
||||
(require_longitudinal and native.requestedLongitudinal and str(config.safetyModel) not in ('silent', 'noOutput') and
|
||||
not p.controlsAllowed)
|
||||
(require_longitudinal and native.requestedLongitudinal and str(config.safetyModel) not in ('silent', 'noOutput') and not p.controlsAllowed)
|
||||
for p, config in zip(native.pandaInventory, cp.safetyConfigs, strict=True))):
|
||||
return None
|
||||
# v2: producer-read 200ms lease; separate BOOTTIME veto.
|
||||
@@ -303,8 +302,7 @@ class TransportPauseFeedback:
|
||||
(gm_pedal or classic_brake) and event.name == log.OnroadEvent.EventName.pedalPressed or
|
||||
volkswagen_withdrawal and event.name in (log.OnroadEvent.EventName.buttonCancel, log.OnroadEvent.EventName.pcmDisable) or
|
||||
ford_withdrawal and event.name in (log.OnroadEvent.EventName.pedalPressed, log.OnroadEvent.EventName.pcmDisable,
|
||||
log.OnroadEvent.EventName.buttonCancel))
|
||||
for event in sm['onroadEvents'])):
|
||||
log.OnroadEvent.EventName.buttonCancel)) for event in sm['onroadEvents'])):
|
||||
return None
|
||||
native = independent_lateral_health(sm, cp, cs, self.session, now_ns)
|
||||
# Brake health may precede axis status.
|
||||
@@ -331,8 +329,7 @@ class TransportPauseFeedback:
|
||||
native.observedMonoTime < self.lateral_native_ns or
|
||||
(native.pandaSerial, tuple(slot.hardwareSerial for slot in native.pandaInventory)) != self.lateral_inventory):
|
||||
return None
|
||||
owners = [index for index, config in enumerate(cp.safetyConfigs)
|
||||
if str(config.safetyModel) not in ('silent', 'noOutput')]
|
||||
owners = [index for index, config in enumerate(cp.safetyConfigs) if str(config.safetyModel) not in ('silent', 'noOutput')]
|
||||
if not (len(owners) == 1 and (early_long or not native.pandaInventory[owners[0]].controlsAllowed and
|
||||
not sm['pandaStates'][owners[0]].controlsAllowed)):
|
||||
return None
|
||||
@@ -397,8 +394,7 @@ class TransportPauseFeedback:
|
||||
return False
|
||||
# Pre-event SOFT: intent only, original 30ms join; no reanchoring.
|
||||
axis_first = bool(str(axis.faultReason) == 'availabilityPause' and
|
||||
not (axis.lateralActive or axis.longitudinalActive or axis.desiredLateral or
|
||||
axis.desiredLongitudinal or axis.nativeAcknowledged) and
|
||||
not (axis.lateralActive or axis.longitudinalActive or axis.desiredLateral or axis.desiredLongitudinal or axis.nativeAcknowledged) and
|
||||
prior is not None and prior[5] == 'none' and prior[11] and prior[13] and
|
||||
(prior[9] or self.ordinary_warning_retained and not prior[10] and not prior[12]) and
|
||||
prior[14:16] == (producer, self.availability_epoch) and
|
||||
@@ -592,8 +588,7 @@ class TransportPauseFeedback:
|
||||
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)
|
||||
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
|
||||
@@ -607,8 +602,7 @@ class TransportPauseFeedback:
|
||||
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)):
|
||||
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)
|
||||
@@ -644,8 +638,7 @@ class TransportPauseFeedback:
|
||||
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))
|
||||
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
|
||||
@@ -706,8 +699,7 @@ class TransportPauseFeedback:
|
||||
not sm.seen['onroadEvents'] or not sm.valid['onroadEvents'] or not sm.alive['onroadEvents'] or
|
||||
now_ns-event_ns > 1_500_000_000 or
|
||||
not any(str(e.name)in temporary_names for e in events) or
|
||||
any(e.immediateDisable or e.softDisable and str(e.name)!='steerTempUnavailable' or
|
||||
e.userDisable and str(e.name)!='pcmDisable' or
|
||||
any(e.immediateDisable or e.softDisable and str(e.name)!='steerTempUnavailable' or e.userDisable and str(e.name)!='pcmDisable' or
|
||||
str(e.name)not in (*temporary_names,'pcmDisable','gasPressedOverride','steerOverride') for e in events)):
|
||||
return False
|
||||
native = _configured_transport_native(sm,cp,self.session,now_ns,allow_restricted_lateral=True)
|
||||
@@ -727,12 +719,12 @@ class TransportPauseFeedback:
|
||||
|
||||
if (not qualified(cp, marked_only=True) or not latched or self.failed or self.paused or self.pending_event or
|
||||
not self.session or str(axis.sessionId) != self.session or
|
||||
not self.healthy_feedback_ns or not 0 <= now_ns - self.healthy_feedback_ns <= AXIS_MAX_AGE_NS or
|
||||
not self.healthy_feedback_ns or
|
||||
not 0 <= now_ns - self.healthy_feedback_ns <= (SAFETY_MAX_AGE_NS if started else AXIS_MAX_AGE_NS) or
|
||||
not 0 < source_ns <= now_ns or now_ns - source_ns > SAFETY_MAX_AGE_NS or
|
||||
(not started and now_ns - source_ns > AXIS_MAX_AGE_NS) or
|
||||
cs.accFaulted or cs.seatbeltUnlatched or
|
||||
cs.gearShifter not in (car.CarState.GearShifter.drive, car.CarState.GearShifter.sport,
|
||||
car.CarState.GearShifter.low, car.CarState.GearShifter.brake) or
|
||||
cs.gearShifter not in (car.CarState.GearShifter.drive, car.CarState.GearShifter.sport, car.CarState.GearShifter.low, car.CarState.GearShifter.brake) or
|
||||
str(axis.faultReason) != 'none' or not axis.desiredLateral or not axis.lateralActive or
|
||||
(not axis.nativeAcknowledged and (axis.desiredLongitudinal or axis.longitudinalActive)) or
|
||||
not 0 < axis.sourceCarStateMonoTime <= axis.observedMonoTime or
|
||||
@@ -820,8 +812,7 @@ class TransportPauseFeedback:
|
||||
for p, c in zip(pandas, cp.safetyConfigs, strict=True))
|
||||
raw_withdrawal = bool((self.longitudinal_cancel_ns or fresh_cancel) and
|
||||
0 < native.sourcePandaStatesMonoTime < stamp and
|
||||
all(not p.controlsAllowed for p, c in zip(pandas, cp.safetyConfigs, strict=True)
|
||||
if str(c.safetyModel) not in ('silent', 'noOutput')))
|
||||
all(not p.controlsAllowed for p, c in zip(pandas, cp.safetyConfigs, strict=True) if str(c.safetyModel) not in ('silent', 'noOutput')))
|
||||
if withdrawal_required and native.longitudinalAllowed and not raw_withdrawal:
|
||||
return None
|
||||
return native if current_pandas else None
|
||||
@@ -893,8 +884,7 @@ class TransportPauseFeedback:
|
||||
event.userDisable and not event.softDisable and not event.immediateDisable)]
|
||||
if cp.brand == 'gm':
|
||||
from openpilot.starpilot.car.gm.aol import gm_lateral_pedal_source_zero
|
||||
if gm_lateral_pedal_source_zero(self, cp, cs, axis, native, now_ns,
|
||||
producer=intent_producer_session):
|
||||
if gm_lateral_pedal_source_zero(self, cp, cs, axis, native, now_ns, producer=intent_producer_session):
|
||||
events = [event for event in events if not (event.name == log.OnroadEvent.EventName.pedalPressed and
|
||||
event.userDisable and not event.softDisable and not event.immediateDisable)]
|
||||
event_ns = int(sm.logMonoTime['onroadEvents'])
|
||||
@@ -906,8 +896,7 @@ class TransportPauseFeedback:
|
||||
issue = live_event and (availability_only(events) or host_source_off and host_source_availability_only(events))
|
||||
if reason not in ('none', 'availabilityPause') or faults and not issue:
|
||||
return False
|
||||
typed = bool(reason == 'availabilityPause' and not axis.lateralActive and not axis.longitudinalActive and
|
||||
0 < axis.faultEventMonoTime <= stamp)
|
||||
typed = bool(reason == 'availabilityPause' and not axis.lateralActive and not axis.longitudinalActive and 0 < axis.faultEventMonoTime <= stamp)
|
||||
source_expired = bool(typed and axis.sourceCarStateMonoTime == 0)
|
||||
continuing_intent = bool(source_expired and self.retention_verified and issue)
|
||||
if source_expired and not (0 < self.lateral_source_ns <= now_ns and
|
||||
@@ -970,8 +959,7 @@ class TransportPauseFeedback:
|
||||
not faults[0].softDisable or faults[0].userDisable or faults[0].immediateDisable or
|
||||
any(event.noEntry and event.name != log.OnroadEvent.EventName.selfdrivedLagging for event in events)):
|
||||
return False
|
||||
elif (axis.desiredLongitudinal or axis.longitudinalActive or
|
||||
not self.retention_event_ns < event_ns or faults):
|
||||
elif (axis.desiredLongitudinal or axis.longitudinalActive or not self.retention_event_ns < event_ns or faults):
|
||||
return False
|
||||
native = _healthy_transport_native(sm, cp, cs, self.session, now_ns)
|
||||
return bool(native is not None and native.requestedLateral and native.lateralAllowed and
|
||||
@@ -1032,8 +1020,7 @@ class TransportPauseFeedback:
|
||||
int(axis.observedMonoTime) != stamp or not 0 < axis.sourceCarStateMonoTime <= stamp <= now_ns or
|
||||
not 0 <= axis.validUntilMonoTime - stamp <= AXIS_MAX_AGE_NS or
|
||||
now_ns - axis.sourceCarStateMonoTime > SAFETY_MAX_AGE_NS or
|
||||
not (stamp - axis.sourceCarStateMonoTime > AXIS_MAX_AGE_NS or now_ns > axis.validUntilMonoTime or
|
||||
held and output_missing or gas_source) or
|
||||
not (stamp - axis.sourceCarStateMonoTime > AXIS_MAX_AGE_NS or now_ns > axis.validUntilMonoTime or held and output_missing or gas_source) or
|
||||
not producer or getattr(axis, 'intentProducerSessionId', '') != producer or
|
||||
producer != self.availability_producer or
|
||||
int(getattr(axis, 'intentIntegrityEpoch', 0)) != self.availability_epoch):
|
||||
@@ -1088,8 +1075,7 @@ class TransportPauseFeedback:
|
||||
if not stock_lateral_off(cp, cs, native):
|
||||
return False
|
||||
if self.retention_started_ns:
|
||||
if (self.retention_event_ns != event_ns or
|
||||
not 0 <= now_ns - self.retention_started_ns <= AXIS_MAX_AGE_NS):
|
||||
if (self.retention_event_ns != event_ns or not 0 <= now_ns - self.retention_started_ns <= AXIS_MAX_AGE_NS):
|
||||
return False
|
||||
else:
|
||||
self.retention_started_ns = now_ns
|
||||
@@ -1116,8 +1102,7 @@ class TransportPauseFeedback:
|
||||
return False
|
||||
event_ns = int(sm.logMonoTime['onroadEvents'])
|
||||
faults = [event for event in sm['onroadEvents'] if event.immediateDisable or event.softDisable]
|
||||
isolated = bool(len(faults) == 1 and faults[0].name == log.OnroadEvent.EventName.controlsMismatch and
|
||||
faults[0].immediateDisable)
|
||||
isolated = bool(len(faults) == 1 and faults[0].name == log.OnroadEvent.EventName.controlsMismatch and faults[0].immediateDisable)
|
||||
if (not isolated or not sm.seen['onroadEvents'] or not sm.valid['onroadEvents'] or not sm.alive['onroadEvents'] or
|
||||
not 0 < axis.faultEventMonoTime < event_ns <= now_ns or now_ns - event_ns > AXIS_MAX_AGE_NS):
|
||||
return False
|
||||
@@ -1160,16 +1145,14 @@ class TransportPauseFeedback:
|
||||
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(event.immediateDisable or event.softDisable or event.userDisable and
|
||||
event.name not in (log.OnroadEvent.EventName.pcmDisable, log.OnroadEvent.EventName.pedalPressed)
|
||||
for event in sm['onroadEvents'])):
|
||||
event.name not in (log.OnroadEvent.EventName.pcmDisable, log.OnroadEvent.EventName.pedalPressed) for event in sm['onroadEvents'])):
|
||||
return False
|
||||
native = _configured_transport_native(sm, cp, self.session, now_ns,
|
||||
require_longitudinal=not pending_stop, allow_restricted_lateral=True)
|
||||
if native is None and combined_stop:
|
||||
newer = _configured_transport_native(sm, cp, self.session, now_ns,
|
||||
require_longitudinal=False, allow_restricted_lateral=True)
|
||||
if (newer is not None and newer.pandaInventory and
|
||||
0 < int(sm.logMonoTime['pandaStates']) < newer.sourcePandaStatesMonoTime and
|
||||
if (newer is not None and newer.pandaInventory and 0 < int(sm.logMonoTime['pandaStates']) < newer.sourcePandaStatesMonoTime and
|
||||
all(slot.controlsAllowed for slot, config in zip(newer.pandaInventory, cp.safetyConfigs, strict=True)
|
||||
if str(config.safetyModel) not in ('silent', 'noOutput'))):
|
||||
native = newer
|
||||
@@ -1215,11 +1198,9 @@ class TransportPauseFeedback:
|
||||
log.OnroadEvent.EventName.pcmDisable)
|
||||
if (not sm.seen['onroadEvents'] or not sm.valid['onroadEvents'] or not sm.alive['onroadEvents'] or
|
||||
not 0 < event_ns == axis.faultEventMonoTime <= stamp or now_ns - event_ns > 1_500_000_000 or
|
||||
any(event.name not in allowed or event.immediateDisable or
|
||||
event.softDisable and event.name != log.OnroadEvent.EventName.wrongGear or
|
||||
any(event.name not in allowed or event.immediateDisable or event.softDisable and event.name != log.OnroadEvent.EventName.wrongGear or
|
||||
event.userDisable and event.name not in (log.OnroadEvent.EventName.reverseGear,
|
||||
log.OnroadEvent.EventName.pedalPressed, log.OnroadEvent.EventName.pcmDisable)
|
||||
for event in sm['onroadEvents'])):
|
||||
log.OnroadEvent.EventName.pedalPressed, log.OnroadEvent.EventName.pcmDisable) for event in sm['onroadEvents'])):
|
||||
return False
|
||||
native = _healthy_transport_native(sm, cp, cs, self.session, now_ns)
|
||||
return bool(native is not None and native.pandaInventory and
|
||||
@@ -1317,8 +1298,7 @@ class TransportPauseFeedback:
|
||||
(axis.sequence > self.sequence or axis.sequence == self.sequence and signature == self.signature))
|
||||
if not current and continuity and cp.brand == 'subaru':
|
||||
from openpilot.starpilot.car.subaru.aol import retain_stopped_intent
|
||||
if retain_stopped_intent(self, sm, cp, cs, axis, now_ns, latched=latched,
|
||||
producer=intent_producer_session, signature=signature):
|
||||
if retain_stopped_intent(self, sm, cp, cs, axis, now_ns, latched=latched, producer=intent_producer_session, signature=signature):
|
||||
return False
|
||||
if not current and continuity and self._inactive_gear_source_gap(sm, cp, cs, axis, stamp, now_ns, latched=latched,
|
||||
producer=intent_producer_session):
|
||||
@@ -1339,16 +1319,14 @@ class TransportPauseFeedback:
|
||||
return True
|
||||
if (cp.brand == 'gm' and current and continuity and latched and not self.failed and
|
||||
not self.ever_lateral_active and not self.pending_event and reason == 'none' and
|
||||
axis.nativeAcknowledged and not any(signature[9:13]) and
|
||||
intent_producer_session and signature[14] == intent_producer_session and
|
||||
axis.nativeAcknowledged and not any(signature[9:13]) and intent_producer_session and signature[14] == intent_producer_session and
|
||||
(self.signature is None or signature[14:16] == self.signature[14:16]) and
|
||||
0 < axis.sourceCarStateMonoTime <= stamp and now_ns - axis.sourceCarStateMonoTime <= AXIS_MAX_AGE_NS):
|
||||
from openpilot.starpilot.car.gm.aol import cold_park_readiness
|
||||
native = _healthy_transport_native(sm, cp, cs, str(axis.sessionId), now_ns)
|
||||
event_ns = int(sm.logMonoTime['onroadEvents'])
|
||||
if (axis.faultEventMonoTime == event_ns and sm.seen['onroadEvents'] and
|
||||
sm.valid['onroadEvents'] and sm.alive['onroadEvents'] and
|
||||
0 < event_ns <= stamp and now_ns - event_ns <= 1_500_000_000 and
|
||||
sm.valid['onroadEvents'] and sm.alive['onroadEvents'] and 0 < event_ns <= stamp and now_ns - event_ns <= 1_500_000_000 and
|
||||
cold_park_readiness(cp, cs, native, sm['onroadEvents'])):
|
||||
self.cold_park_waiting = True
|
||||
self.session = str(axis.sessionId)
|
||||
@@ -1366,34 +1344,28 @@ class TransportPauseFeedback:
|
||||
if (retain_command_pause_intent(self, sm, cp, cs, axis, now_ns, latched=latched, producer=intent_producer_session) or
|
||||
retain_gear_withdrawal_intent(self, sm, cp, cs, axis, now_ns, latched=latched, producer=intent_producer_session)):
|
||||
return False
|
||||
if (cp.brand == 'chrysler' and current and continuity and latched and
|
||||
not self.failed and not self.ever_lateral_active):
|
||||
if (cp.brand == 'chrysler' and current and continuity and latched and not self.failed and not self.ever_lateral_active):
|
||||
from openpilot.starpilot.car.chrysler.aol import cold_calibration_intent_current
|
||||
native = _healthy_transport_native(sm, cp, cs, str(axis.sessionId), now_ns)
|
||||
if cold_calibration_intent_current(self, sm, cp, cs, axis, native, now_ns,
|
||||
pending=startup_calibration_pending, producer=intent_producer_session):
|
||||
if cold_calibration_intent_current(self, sm, cp, cs, axis, native, now_ns, pending=startup_calibration_pending, producer=intent_producer_session):
|
||||
self.session = str(axis.sessionId)
|
||||
self.sequence, self.signature = int(axis.sequence), signature
|
||||
return False
|
||||
if cp.brand == 'hyundai' and current and continuity:
|
||||
from openpilot.starpilot.car.hyundai.aol import retain_stopped_eps_arm
|
||||
if retain_stopped_eps_arm(self, sm, cp, cs, axis, now_ns, latched=latched,
|
||||
arm_ns=main_arm_ns, producer=intent_producer_session):
|
||||
if retain_stopped_eps_arm(self, sm, cp, cs, axis, now_ns, latched=latched, arm_ns=main_arm_ns, producer=intent_producer_session):
|
||||
self.session = str(axis.sessionId)
|
||||
self.sequence, self.signature = int(axis.sequence), signature
|
||||
return False
|
||||
if current and continuity and 0 < main_arm_ns <= now_ns <= main_arm_ns + AXIS_MAX_AGE_NS:
|
||||
from openpilot.starpilot.car.gm.aol import prior_main_off_intent_current
|
||||
if prior_main_off_intent_current(self, sm, cp, cs, axis, now_ns,
|
||||
latched=latched, main_arm_ns=main_arm_ns, producer=intent_producer_session):
|
||||
if prior_main_off_intent_current(self, sm, cp, cs, axis, now_ns, latched=latched, main_arm_ns=main_arm_ns, producer=intent_producer_session):
|
||||
self.sequence, self.signature = int(axis.sequence), signature
|
||||
return False
|
||||
if cp.brand == 'gm' and current and continuity and latched:
|
||||
from openpilot.starpilot.car.gm.aol import cold_gm_main_intent_current
|
||||
native = (_healthy_transport_native(sm, cp, cs, str(axis.sessionId), now_ns)
|
||||
if cp.brand == 'gm' else None)
|
||||
if cold_gm_main_intent_current(self, sm, cp, cs, axis, native, now_ns,
|
||||
producer=intent_producer_session):
|
||||
native = (_healthy_transport_native(sm, cp, cs, str(axis.sessionId), now_ns) if cp.brand == 'gm' else None)
|
||||
if cold_gm_main_intent_current(self, sm, cp, cs, axis, native, now_ns, producer=intent_producer_session):
|
||||
self.session = str(axis.sessionId)
|
||||
self.sequence, self.signature = int(axis.sequence), signature
|
||||
if axis.sourceCarStateMonoTime > 0:
|
||||
@@ -1410,16 +1382,13 @@ class TransportPauseFeedback:
|
||||
native = _healthy_transport_native(sm, cp, cs, str(axis.sessionId), now_ns)
|
||||
event_ns = int(sm.logMonoTime['onroadEvents'])
|
||||
recovering = bool(reason == 'none' and axis.desiredLateral and not axis.desiredLongitudinal and
|
||||
not axis.lateralActive and not axis.longitudinalActive and axis.nativeAcknowledged and
|
||||
0 < self.cold_main_wait_ns <= now_ns and
|
||||
not axis.lateralActive and not axis.longitudinalActive and axis.nativeAcknowledged and 0 < self.cold_main_wait_ns <= now_ns and
|
||||
(self.cold_main_sparse_waiting or now_ns <= self.cold_main_wait_ns + SAFETY_MAX_AGE_NS) and
|
||||
0 < axis.sourceCarStateMonoTime <= stamp and now_ns - axis.sourceCarStateMonoTime <= AXIS_MAX_AGE_NS)
|
||||
if ((reason == 'availabilityPause' and not any(signature[9:13]) or recovering) and
|
||||
intent_producer_session and signature[14] == intent_producer_session and
|
||||
(self.signature is None or signature[14:16] == self.signature[14:16]) and
|
||||
axis.faultEventMonoTime == event_ns and sm.seen['onroadEvents'] and
|
||||
sm.valid['onroadEvents'] and sm.alive['onroadEvents'] and 0 < event_ns <= stamp and
|
||||
now_ns - event_ns <= AXIS_MAX_AGE_NS and
|
||||
(self.signature is None or signature[14:16] == self.signature[14:16]) and axis.faultEventMonoTime == event_ns and sm.seen['onroadEvents'] and
|
||||
sm.valid['onroadEvents'] and sm.alive['onroadEvents'] and 0 < event_ns <= stamp and now_ns - event_ns <= AXIS_MAX_AGE_NS and
|
||||
(axis.sourceCarStateMonoTime != 0 or not (cp.pcmCruise and not cp.openpilotLongitudinalControl) or
|
||||
0 < self.cold_main_source_ns <= stamp <= now_ns <= self.cold_main_source_ns + SAFETY_MAX_AGE_NS) and
|
||||
cold_main_readiness(cp, cs, native, sm['onroadEvents'], recovering=recovering)):
|
||||
@@ -1437,18 +1406,15 @@ class TransportPauseFeedback:
|
||||
axis.nativeAcknowledged and axis.desiredLateral and not axis.lateralActive):
|
||||
event_ns = int(sm.logMonoTime['onroadEvents'])
|
||||
recovery_ahead = bool(sm.seen['onroadEvents'] and sm.valid['onroadEvents'] and
|
||||
sm.alive['onroadEvents'] and 0 < event_ns < axis.faultEventMonoTime <= stamp and
|
||||
now_ns - event_ns <= AXIS_MAX_AGE_NS)
|
||||
sm.alive['onroadEvents'] and 0 < event_ns < axis.faultEventMonoTime <= stamp and now_ns - event_ns <= AXIS_MAX_AGE_NS)
|
||||
if not recovery_ahead:
|
||||
self.failed = True
|
||||
return True
|
||||
if current and continuity and self._angle_stop_intent_current(sm, cp, cs, axis, stamp, now_ns,
|
||||
latched=latched, producer=intent_producer_session):
|
||||
previous = self.signature
|
||||
if (cp.brand == 'hyundai' and not axis.lateralActive and previous is not None and
|
||||
previous[9] and previous[11] and previous[13] and
|
||||
0 < previous[8] <= previous[2] <= now_ns <= previous[4] and
|
||||
now_ns - previous[8] <= AXIS_MAX_AGE_NS):
|
||||
if (cp.brand == 'hyundai' and not axis.lateralActive and previous is not None and previous[9] and previous[11] and previous[13] and
|
||||
0 < previous[8] <= previous[2] <= now_ns <= previous[4] and now_ns - previous[8] <= AXIS_MAX_AGE_NS):
|
||||
self.hkg_eps_join_until_ns = min(previous[4], self.lateral_source_ns + AXIS_MAX_AGE_NS)
|
||||
self.sequence, self.signature = int(axis.sequence), signature
|
||||
return False
|
||||
@@ -1476,8 +1442,7 @@ class TransportPauseFeedback:
|
||||
self.sequence, self.signature = int(axis.sequence), signature
|
||||
return False
|
||||
if (cp.brand == 'ford' and current and continuity and
|
||||
self._ford_gas_release_eps_join_current(sm, cp, cs, axis, stamp, now_ns,
|
||||
latched=latched, producer=intent_producer_session)):
|
||||
self._ford_gas_release_eps_join_current(sm, cp, cs, axis, stamp, now_ns, latched=latched, producer=intent_producer_session)):
|
||||
return False
|
||||
if cp.brand == 'ford' and current and continuity:
|
||||
from openpilot.starpilot.car.ford.physical_pause import retain_physical_pause_intent
|
||||
@@ -1485,8 +1450,7 @@ class TransportPauseFeedback:
|
||||
return False
|
||||
if cp.brand == 'subaru' and current and continuity:
|
||||
from openpilot.starpilot.car.subaru.paused_intent import retain_paused_restriction
|
||||
if retain_paused_restriction(self, sm, cp, cs, axis, stamp, now_ns,
|
||||
latched=latched, producer=intent_producer_session):
|
||||
if retain_paused_restriction(self, sm, cp, cs, axis, stamp, now_ns, latched=latched, producer=intent_producer_session):
|
||||
self.sequence, self.signature = int(axis.sequence), signature
|
||||
return False
|
||||
if current and continuity and self._temporary_steering_intent_current(sm, cp, cs, axis, stamp, now_ns,
|
||||
@@ -1495,14 +1459,12 @@ class TransportPauseFeedback:
|
||||
return False
|
||||
if cp.brand == 'honda' and current and continuity:
|
||||
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):
|
||||
self.sequence, self.signature = int(axis.sequence), signature
|
||||
return False
|
||||
if cp.brand == 'volkswagen' and current and continuity:
|
||||
from openpilot.starpilot.car.volkswagen.aol import retain_reverse_withdrawal
|
||||
if retain_reverse_withdrawal(self, sm, cp, cs, axis, now_ns,
|
||||
latched=latched, producer=intent_producer_session):
|
||||
if retain_reverse_withdrawal(self, sm, cp, cs, axis, 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:
|
||||
@@ -1510,8 +1472,7 @@ class TransportPauseFeedback:
|
||||
from openpilot.starpilot.aol.reverse_intent import retain_reverse_intent
|
||||
|
||||
if retain_reverse_intent(self, sm, cp, cs, axis, now_ns, latched=latched, producer=intent_producer_session,
|
||||
qualified_cp=honda_stock_qualified(cp, marked_only=True),
|
||||
extra_user_events=(log.OnroadEvent.EventName.cruiseDisabled,),
|
||||
qualified_cp=honda_stock_qualified(cp, marked_only=True), extra_user_events=(log.OnroadEvent.EventName.cruiseDisabled,),
|
||||
informational_events=(log.OnroadEvent.EventName.userBookmarkNotPaired,), allow_withdrawal_join=True):
|
||||
return False
|
||||
if cp.brand == 'mazda' and current and continuity:
|
||||
@@ -1559,11 +1520,17 @@ class TransportPauseFeedback:
|
||||
self.lateral_native_ns = int(gas_native.observedMonoTime)
|
||||
self.sequence, self.signature = int(axis.sequence), signature
|
||||
return False
|
||||
honda_driver_pending = bool(cp.brand == 'honda' and not current and continuity and signature == self.signature and
|
||||
(self.honda_brake_ns or self.honda_cancel_ns) and not cs.buttonEvents and
|
||||
cs.cruiseState.available and not cs.doorOpen and not cs.vehicleSensorsInvalid and not cs.steeringDisengage and
|
||||
not cs.regenBraking and
|
||||
sm.seen['aolAxisState'] and sm.valid['aolAxisState'] and sm.alive['aolAxisState'] and
|
||||
axis.qualified and str(axis.faultSessionId) == self.session and cp_identity(cp) == self.cp and
|
||||
0 < stamp == axis.observedMonoTime < axis.validUntilMonoTime < now_ns)
|
||||
brake_native = (self._honda_brake_lateral_current(sm, cp, cs, axis, now_ns,
|
||||
latched=latched, brake_source_ns=brake_source_ns) if current and continuity else None)
|
||||
if brake_native is None and current and continuity:
|
||||
brake_native = self._honda_cancel_lateral_current(sm, cp, cs, axis, now_ns,
|
||||
latched=latched, cancel_source_ns=cancel_source_ns)
|
||||
latched=latched, brake_source_ns=brake_source_ns) if (current or honda_driver_pending) and continuity else None)
|
||||
if brake_native is None and (current or honda_driver_pending) and continuity:
|
||||
brake_native = self._honda_cancel_lateral_current(sm, cp, cs, axis, now_ns, latched=latched, cancel_source_ns=cancel_source_ns)
|
||||
if brake_native is not None:
|
||||
self.healthy_feedback_ns = stamp
|
||||
self.healthy_native_ns = int(brake_native.observedMonoTime)
|
||||
@@ -1620,16 +1587,12 @@ class TransportPauseFeedback:
|
||||
0 < int(sm.logMonoTime['onroadEvents']) <= now_ns and
|
||||
now_ns - int(sm.logMonoTime['onroadEvents']) <= 1_500_000_000 and
|
||||
all(not event.immediateDisable and
|
||||
(not event.softDisable or intent_paused and event.name in
|
||||
(log.OnroadEvent.EventName.wrongGear, log.OnroadEvent.EventName.steerTempUnavailable) or
|
||||
cs.seatbeltUnlatched and event.name == log.OnroadEvent.EventName.seatbeltNotLatched and
|
||||
event.noEntry and not event.userDisable) and
|
||||
(not event.softDisable or intent_paused and event.name in (log.OnroadEvent.EventName.wrongGear, log.OnroadEvent.EventName.steerTempUnavailable) or
|
||||
cs.seatbeltUnlatched and event.name == log.OnroadEvent.EventName.seatbeltNotLatched and event.noEntry and not event.userDisable) and
|
||||
(not event.userDisable or event.name in
|
||||
(log.OnroadEvent.EventName.pcmDisable, log.OnroadEvent.EventName.buttonCancel,
|
||||
log.OnroadEvent.EventName.reverseGear) or intent_paused and
|
||||
(log.OnroadEvent.EventName.pcmDisable, log.OnroadEvent.EventName.buttonCancel, log.OnroadEvent.EventName.reverseGear) or intent_paused and
|
||||
(event.name == log.OnroadEvent.EventName.wrongGear or cp.brand == 'ford' and cs.brakePressed and
|
||||
event.name == log.OnroadEvent.EventName.pedalPressed))
|
||||
for event in sm['onroadEvents']) and
|
||||
event.name == log.OnroadEvent.EventName.pedalPressed)) for event in sm['onroadEvents']) and
|
||||
native is not None and native.pandaInventory and self.healthy_inventory ==
|
||||
(native.pandaSerial, tuple(slot.hardwareSerial for slot in native.pandaInventory)) and
|
||||
not native.requestedLateral and not native.lateralAllowed and
|
||||
@@ -1669,11 +1632,9 @@ class TransportPauseFeedback:
|
||||
self.sequence, self.signature = int(axis.sequence), signature
|
||||
return False
|
||||
transport_healthy = native is not None
|
||||
cancel_native = (self._longitudinal_cancel_current(sm, cp, cs, axis, now_ns, latched=latched,
|
||||
cancel_source_ns=cancel_source_ns)
|
||||
cancel_native = (self._longitudinal_cancel_current(sm, cp, cs, axis, now_ns, latched=latched, cancel_source_ns=cancel_source_ns)
|
||||
if current and continuity and baseline and not transport_healthy else None)
|
||||
if self._event_first_retention(sm, cp, axis, stamp, now_ns, latched=latched,
|
||||
signature=signature, native=native):
|
||||
if self._event_first_retention(sm, cp, axis, stamp, now_ns, latched=latched, signature=signature, native=native):
|
||||
return False
|
||||
current = bool(current and (transport_healthy or cancel_native is not None))
|
||||
if current and baseline and not latched:
|
||||
@@ -1712,8 +1673,7 @@ class TransportPauseFeedback:
|
||||
self.longitudinal_cancel_ns = 0
|
||||
if not current or not continuity or reason not in ('none', 'transportPause'):
|
||||
self.longitudinal_cancel_ns = 0
|
||||
hard = (self.paused or bool(self.pending_event) or reason == 'critical' or
|
||||
bool(self.session and (latched or not continuity)))
|
||||
hard = (self.paused or bool(self.pending_event) or reason == 'critical' or bool(self.session and (latched or not continuity)))
|
||||
self.paused = False
|
||||
self.pending_event = 0
|
||||
self.failed = hard
|
||||
@@ -1730,8 +1690,7 @@ class TransportPauseFeedback:
|
||||
return hard
|
||||
event_ns = int(sm.logMonoTime['onroadEvents'])
|
||||
faults = [e for e in sm['onroadEvents'] if e.immediateDisable or e.softDisable]
|
||||
isolated = bool(len(faults) == 1 and faults[0].name == log.OnroadEvent.EventName.controlsMismatch and
|
||||
faults[0].immediateDisable)
|
||||
isolated = bool(len(faults) == 1 and faults[0].name == log.OnroadEvent.EventName.controlsMismatch and faults[0].immediateDisable)
|
||||
if known and isolated and sm.valid['onroadEvents'] and 0 < axis.faultEventMonoTime < event_ns <= now_ns:
|
||||
if not self.pending_event:
|
||||
self.pending_event = event_ns
|
||||
@@ -1794,11 +1753,9 @@ class TransportPauseFeedback:
|
||||
pending = bool(provenance and axis.faultEventMonoTime > sm.logMonoTime['onroadEvents'])
|
||||
if pending and not self.pending_event:
|
||||
self.pending_event = int(axis.faultEventMonoTime)
|
||||
self.qualified = bool(provenance and
|
||||
axis.faultEventMonoTime == sm.logMonoTime['onroadEvents'] and
|
||||
self.qualified = bool(provenance and axis.faultEventMonoTime == sm.logMonoTime['onroadEvents'] and
|
||||
sm.valid['onroadEvents'] and axis.faultEventMonoTime <= now_ns)
|
||||
if self.pending_event and (axis.faultEventMonoTime != self.pending_event or
|
||||
now_ns - self.pending_event > AXIS_MAX_AGE_NS):
|
||||
if self.pending_event and (axis.faultEventMonoTime != self.pending_event or now_ns - self.pending_event > AXIS_MAX_AGE_NS):
|
||||
self.pending_event = 0
|
||||
self.paused = False
|
||||
self.failed = True
|
||||
|
||||
@@ -106,7 +106,7 @@ def aol_safety_config(CP):
|
||||
|
||||
|
||||
def physical_cancel_lateral_allowed(cp, cs, intent, native, *, settings, previous,
|
||||
source_ns, now_ns, axis_session_id) -> bool:
|
||||
source_ns, now_ns, axis_session_id, cancel_samples=()) -> bool:
|
||||
"""Let the mapped intent owner apply Cancel while retaining a granted LAT axis."""
|
||||
from openpilot.starpilot.aol.intent import ButtonType
|
||||
from openpilot.starpilot.aol.runtime import (AXIS_MAX_AGE_NS, INTENT_MAX_AGE_NS, SAFETY_MAX_AGE_NS,
|
||||
@@ -121,7 +121,10 @@ def physical_cancel_lateral_allowed(cp, cs, intent, native, *, settings, previou
|
||||
intent.validUntilMonoTime - intent.observedMonoTime <= SAFETY_MAX_AGE_NS and
|
||||
cs.canValid and not cs.canTimeout and cs.cruiseState.available and not cs.steerFaultTemporary and
|
||||
not cs.steerFaultPermanent and not cs.accFaulted and not cs.doorOpen and
|
||||
any(event.type == ButtonType.cancel for event in cs.buttonEvents) and
|
||||
(any(event.type == ButtonType.cancel for event in cs.buttonEvents) or
|
||||
any(sample.valid and 0 < sample.logMonoTime <= source_ns and now_ns - sample.logMonoTime <= AXIS_MAX_AGE_NS and
|
||||
sample.carState.canValid and not sample.carState.canTimeout and
|
||||
any(event.type == ButtonType.cancel for event in sample.carState.buttonEvents) for sample in cancel_samples)) and
|
||||
native is not None and native.compatible and int(native.protocolVersion) == 1 and
|
||||
axis_session_id and native.axisSessionId == axis_session_id and native.requestedLateral and native.lateralAllowed and
|
||||
native_accepts_cp(cp, native.safetyModel, native.safetyParam) and native.pandaInventory and
|
||||
@@ -131,4 +134,3 @@ def physical_cancel_lateral_allowed(cp, cs, intent, native, *, settings, previou
|
||||
native.validUntilMonoTime - native.observedMonoTime <= SAFETY_MAX_AGE_NS)
|
||||
except (AttributeError, KeyError, IndexError, TypeError, ValueError, OverflowError):
|
||||
return False
|
||||
|
||||
|
||||
@@ -135,14 +135,16 @@ def retain_stopped_source_feedback(feedback, sm, cp, state, axis, stamp, now_ns,
|
||||
|
||||
|
||||
def retain_paused_restriction(feedback, sm, cp, state, axis, stamp, now_ns, *, latched, producer):
|
||||
if retain_pending_restriction_recovery(feedback, sm, cp, state, axis, stamp, now_ns, latched=latched, producer=producer):
|
||||
return True
|
||||
from openpilot.starpilot.aol.transport_pause import _configured_transport_native
|
||||
previous = feedback.signature
|
||||
if (cp.carFingerprint != CAR.SUBARU_IMPREZA_2020 or not qualified(cp, marked_only=True) or
|
||||
not latched or feedback.failed or feedback.paused or feedback.pending_event or
|
||||
not latched or feedback.failed or feedback.paused or
|
||||
feedback.retention_started_ns or feedback.source_retention_started_ns or not feedback.ever_lateral_active or
|
||||
previous is None or not feedback.session or not producer or
|
||||
previous[0] != previous[7] or previous[0] != feedback.session or previous[5] != 'none' or
|
||||
any(previous[9:13]) or not previous[13] or previous[14:16] != (producer, int(axis.intentIntegrityEpoch)) or
|
||||
previous[10] or previous[12] or previous[9] != previous[11] or not previous[13] or previous[14:16] != (producer, int(axis.intentIntegrityEpoch)) or
|
||||
axis.intentProducerSessionId != producer or str(axis.sessionId) != feedback.session or
|
||||
str(axis.faultReason) != 'none' or str(axis.mode) != 'off' or not axis.nativeAcknowledged or
|
||||
any((axis.desiredLateral, axis.lateralActive, axis.desiredLongitudinal, axis.longitudinalActive)) or
|
||||
@@ -155,13 +157,85 @@ def retain_paused_restriction(feedback, sm, cp, state, axis, stamp, now_ns, *, l
|
||||
not 0 < feedback.healthy_feedback_ns <= now_ns or not feedback.healthy_inventory):
|
||||
return False
|
||||
event_ns = int(sm.logMonoTime['onroadEvents'])
|
||||
restriction = getattr(feedback, 'temporary_eps_event_ns', 0)
|
||||
pending = feedback.pending_event
|
||||
matched = axis.faultEventMonoTime == event_ns <= stamp
|
||||
joined_event = max(axis.faultEventMonoTime, event_ns)
|
||||
joining = bool(0 < restriction and previous[6] in (restriction, pending) and
|
||||
min(axis.faultEventMonoTime, event_ns) in (restriction, pending) and
|
||||
restriction < joined_event <= now_ns and now_ns - joined_event <= AXIS_MAX_AGE_NS and
|
||||
(not pending or joined_event >= pending))
|
||||
if (pending and (not 0 < pending <= now_ns or now_ns - pending > AXIS_MAX_AGE_NS or
|
||||
not (joining or matched and event_ns >= pending))):
|
||||
return False
|
||||
if (not sm.seen['onroadEvents'] or not sm.valid['onroadEvents'] or not sm.alive['onroadEvents'] or
|
||||
not 0 < axis.faultEventMonoTime == event_ns <= stamp 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 not (matched or joining) or
|
||||
any(event.immediateDisable or
|
||||
event.softDisable and event.name != log.OnroadEvent.EventName.steerTempUnavailable or
|
||||
event.userDisable and not (event.name == log.OnroadEvent.EventName.pcmDisable or
|
||||
state.brakePressed and event.name == log.OnroadEvent.EventName.pedalPressed) for event in sm['onroadEvents'])):
|
||||
(state.brakePressed or feedback.subaru_eps_brake_event_ns == event_ns) and
|
||||
event.name == log.OnroadEvent.EventName.pedalPressed) for event in sm['onroadEvents'])):
|
||||
return False
|
||||
native = _configured_transport_native(sm, cp, feedback.session, now_ns, allow_restricted_lateral=True)
|
||||
return bool(native_off(native) and native.observedMonoTime >= feedback.healthy_native_ns and
|
||||
feedback.healthy_inventory == (native.pandaSerial, tuple(slot.hardwareSerial for slot in native.pandaInventory)))
|
||||
if (native is None or not native.pandaInventory or native.requestedLateral != native.lateralAllowed or
|
||||
native.requestedLongitudinal or native.longitudinalAllowed or native.observedMonoTime < feedback.healthy_native_ns or
|
||||
feedback.healthy_inventory != (native.pandaSerial, tuple(slot.hardwareSerial for slot in native.pandaInventory))):
|
||||
return False
|
||||
if matched:
|
||||
feedback.pending_event = 0
|
||||
feedback.temporary_eps_event_ns = event_ns
|
||||
if state.brakePressed:
|
||||
feedback.subaru_eps_brake_event_ns = event_ns
|
||||
else:
|
||||
feedback.pending_event = pending or joined_event
|
||||
feedback.awaiting = True
|
||||
return True
|
||||
|
||||
|
||||
def retain_pending_restriction_recovery(feedback, sm, cp, state, axis, stamp, now_ns, *, latched, producer):
|
||||
"""Complete an existing EPS event join after recovery; never renew authority."""
|
||||
from openpilot.starpilot.aol.transport_pause import _healthy_transport_native, cp_identity
|
||||
previous = feedback.signature
|
||||
pending, restriction = feedback.pending_event, getattr(feedback, 'temporary_eps_event_ns', 0)
|
||||
if (not qualified(cp, marked_only=True) or not cp.pcmCruise or cp.openpilotLongitudinalControl or
|
||||
not latched or feedback.failed or feedback.paused or feedback.retention_started_ns or
|
||||
feedback.source_retention_started_ns or not feedback.ever_lateral_active or
|
||||
previous is None or not feedback.session or cp_identity(cp) != feedback.cp or
|
||||
not 0 < restriction < pending <= now_ns or now_ns - pending > AXIS_MAX_AGE_NS or
|
||||
previous[0] != previous[7] or previous[0] != feedback.session or previous[5] != 'none' or
|
||||
previous[6] not in (restriction, pending) or any(previous[9:13]) or not previous[13] or
|
||||
not producer or previous[14:16] != (producer, int(axis.intentIntegrityEpoch)) or
|
||||
not 0 < previous[8] <= previous[2] <= now_ns <= previous[4] or now_ns - previous[8] > AXIS_MAX_AGE_NS or
|
||||
axis.intentProducerSessionId != producer or str(axis.sessionId) != feedback.session or
|
||||
str(axis.faultSessionId) != feedback.session or str(axis.faultReason) != 'none' or
|
||||
str(axis.mode) != 'off' or not axis.nativeAcknowledged or
|
||||
any((axis.desiredLateral, axis.lateralActive, axis.desiredLongitudinal, axis.longitudinalActive)) or
|
||||
not axis.qualified or not sm.seen['aolAxisState'] or not sm.valid['aolAxisState'] or not sm.alive['aolAxisState'] or
|
||||
axis.sequence < feedback.sequence or
|
||||
not previous[8] <= axis.sourceCarStateMonoTime <= stamp == axis.observedMonoTime <= now_ns <= axis.validUntilMonoTime or
|
||||
axis.validUntilMonoTime - stamp != AXIS_MAX_AGE_NS or now_ns - axis.sourceCarStateMonoTime > AXIS_MAX_AGE_NS or
|
||||
state.steerFaultTemporary or state.steerFaultPermanent or not state.canValid or state.canTimeout or
|
||||
state.accFaulted or state.doorOpen or state.seatbeltUnlatched or state.vehicleSensorsInvalid or
|
||||
state.steeringDisengage or state.buttonEvents or state.regenBraking or
|
||||
state.gearShifter != structs.CarState.GearShifter.drive or not state.cruiseState.available or state.cruiseState.enabled):
|
||||
return False
|
||||
event_ns = int(sm.logMonoTime['onroadEvents'])
|
||||
temporary = (log.OnroadEvent.EventName.steerTempUnavailable, log.OnroadEvent.EventName.steerTempUnavailableSilent)
|
||||
allowed = (*temporary, log.OnroadEvent.EventName.pcmDisable, log.OnroadEvent.EventName.gasPressedOverride,
|
||||
log.OnroadEvent.EventName.steerOverride, log.OnroadEvent.EventName.pedalPressed)
|
||||
if (not sm.seen['onroadEvents'] or not sm.valid['onroadEvents'] or not sm.alive['onroadEvents'] or
|
||||
axis.faultEventMonoTime not in (restriction, pending) or event_ns not in (restriction, pending) or
|
||||
max(axis.faultEventMonoTime, event_ns) != pending or event_ns > stamp or
|
||||
not any(event.name in temporary for event in sm['onroadEvents']) or
|
||||
any(event.name not in allowed or event.immediateDisable or event.softDisable and event.name != temporary[0] or
|
||||
event.userDisable and not (event.name == log.OnroadEvent.EventName.pcmDisable or
|
||||
(state.brakePressed or feedback.subaru_eps_brake_event_ns in (restriction, pending)) and
|
||||
event.name == log.OnroadEvent.EventName.pedalPressed) for event in sm['onroadEvents'])):
|
||||
return False
|
||||
native = _healthy_transport_native(sm, cp, state, feedback.session, now_ns)
|
||||
if (native is None or not native.pandaInventory or native.requestedLateral != native.lateralAllowed or
|
||||
native.requestedLongitudinal or native.longitudinalAllowed or native.observedMonoTime < feedback.healthy_native_ns or
|
||||
feedback.healthy_inventory != (native.pandaSerial, tuple(slot.hardwareSerial for slot in native.pandaInventory))):
|
||||
return False
|
||||
feedback.pending_event = feedback.temporary_eps_event_ns = 0
|
||||
return True
|
||||
|
||||
@@ -199,3 +199,158 @@ def test_paused_restriction_preserves_independent_fault_user_and_authority_vetoe
|
||||
raise AssertionError(fault)
|
||||
assert not retain_paused_restriction(feedback, sm, cp, state, sm['aolAxisState'], stamp, stamp,
|
||||
latched=fault != 'off', producer=PRODUCER)
|
||||
|
||||
|
||||
def recovery_case(order='event-first'):
|
||||
cp, state, feedback, _, _, stamp = stopped_feedback()
|
||||
feedback.temporary_eps_event_ns = stamp
|
||||
feedback.pending_event = stamp + 10_000_000
|
||||
state.gasPressed = True
|
||||
now = stamp + 15_000_000
|
||||
event_stamp = stamp if order == 'axis-first' else feedback.pending_event
|
||||
axis_event = stamp if order == 'event-first' else feedback.pending_event
|
||||
sm, native = sample(cp, now, now, 3, active=False, requested=False, allowed=False, event_stamp=event_stamp)
|
||||
change(sm, 'aolAxisState', lambda a: (setattr(a, 'faultEventMonoTime', axis_event), setattr(a, 'intentIntegrityEpoch', 0)))
|
||||
event = sm.messages['onroadEvents'].as_builder()
|
||||
event.onroadEvents = [{'name': 'pcmDisable', 'userDisable': True},
|
||||
{'name': 'steerTempUnavailableSilent', 'warning': True}, {'name': 'gasPressedOverride', 'overrideLongitudinal': True}]
|
||||
sm.messages['onroadEvents'] = event.as_reader()
|
||||
return cp, state, feedback, sm, native, now
|
||||
|
||||
|
||||
@pytest.mark.parametrize('order', ('event-first', 'axis-first', 'matched'))
|
||||
def test_cleared_subaru_restriction_finishes_pending_join_without_renewing_authority(order):
|
||||
from openpilot.starpilot.car.subaru.paused_intent import retain_pending_restriction_recovery
|
||||
cp, state, feedback, sm, _, now = recovery_case(order)
|
||||
before = leases(feedback), feedback.signature, feedback.healthy_feedback_ns, feedback.healthy_native_ns
|
||||
stamp = sm.logMonoTime['aolAxisState']
|
||||
assert retain_pending_restriction_recovery(feedback, sm, cp, state, sm['aolAxisState'], stamp, now,
|
||||
latched=True, producer=PRODUCER)
|
||||
assert feedback.pending_event == feedback.temporary_eps_event_ns == 0
|
||||
assert (leases(feedback), feedback.signature, feedback.healthy_feedback_ns, feedback.healthy_native_ns) == before
|
||||
assert not sm['aolAxisState'].lateralActive and not sm['aolAxisState'].desiredLongitudinal
|
||||
|
||||
|
||||
@pytest.mark.parametrize('fault', ('permanent', 'temporary', 'can', 'timeout', 'main', 'acc', 'cancel', 'reverse',
|
||||
'regen', 'door', 'belt', 'sensors', 'driver_off', 'long', 'lat', 'ack', 'epoch', 'producer', 'session', 'critical',
|
||||
'native_request', 'native_allow', 'native_long', 'native_fault', 'native_stale', 'native_inventory',
|
||||
'hard_event', 'user_off', 'soft_event', 'failed', 'no_history', 'off', 'new_event', 'no_warning',
|
||||
'no_pending', 'no_restriction', 'stale_source', 'future_source'))
|
||||
def test_pending_subaru_recovery_does_not_bypass_independent_vetoes(fault):
|
||||
from openpilot.starpilot.car.subaru.paused_intent import retain_pending_restriction_recovery
|
||||
cp, state, feedback, sm, native, now = recovery_case()
|
||||
stamp = sm.logMonoTime['aolAxisState']
|
||||
physical = {'permanent': ('steerFaultPermanent', True), 'temporary': ('steerFaultTemporary', True),
|
||||
'can': ('canValid', False), 'timeout': ('canTimeout', True), 'regen': ('regenBraking', True), 'door': ('doorOpen', True),
|
||||
'belt': ('seatbeltUnlatched', True), 'sensors': ('vehicleSensorsInvalid', True), 'driver_off': ('steeringDisengage', True)}
|
||||
if fault in physical:
|
||||
setattr(state, *physical[fault])
|
||||
elif fault in ('main', 'acc'):
|
||||
setattr(state.cruiseState, 'available' if fault == 'main' else 'enabled', fault == 'acc')
|
||||
elif fault == 'cancel':
|
||||
state.buttonEvents = [{'type': 'cancel', 'pressed': True}]
|
||||
elif fault == 'reverse':
|
||||
state.gearShifter = 'reverse'
|
||||
elif fault in ('long', 'lat', 'ack', 'epoch', 'producer', 'session', 'critical', 'stale_source', 'future_source'):
|
||||
field, value = {'long': ('desiredLongitudinal', True), 'lat': ('lateralActive', True), 'ack': ('nativeAcknowledged', False),
|
||||
'epoch': ('intentIntegrityEpoch', 1), 'producer': ('intentProducerSessionId', 'other'), 'session': ('faultSessionId', 'other'),
|
||||
'critical': ('faultReason', 'critical'), 'stale_source': ('sourceCarStateMonoTime', now - 30_000_001),
|
||||
'future_source': ('sourceCarStateMonoTime', now + 1)}[fault]
|
||||
change(sm, 'aolAxisState', lambda a: setattr(a, field, value))
|
||||
elif fault in ('native_request', 'native_allow', 'native_long'):
|
||||
native_change(sm, native, **{{'native_request': 'requestedLateral', 'native_allow': 'lateralAllowed',
|
||||
'native_long': 'longitudinalAllowed'}[fault]: True})
|
||||
elif fault == 'native_fault':
|
||||
native_change(sm, native, pandaInventory=(replace(native.pandaInventory[0], faults=1),))
|
||||
elif fault == 'native_stale':
|
||||
native_change(sm, native, validUntilMonoTime=now - 1)
|
||||
elif fault == 'native_inventory':
|
||||
native_change(sm, native, pandaSerial='other', pandaInventory=(replace(native.pandaInventory[0], hardwareSerial='other'),))
|
||||
elif fault in ('hard_event', 'user_off', 'soft_event'):
|
||||
change(sm, 'onroadEvents', lambda e: (setattr(e[0], 'name', 'controlsMismatch' if fault == 'hard_event' else
|
||||
'buttonCancel' if fault == 'user_off' else 'commIssue'), setattr(e[0],
|
||||
'immediateDisable' if fault == 'hard_event' else 'userDisable' if fault == 'user_off' else 'softDisable', True)))
|
||||
elif fault == 'failed':
|
||||
feedback.failed = True
|
||||
elif fault == 'no_history':
|
||||
feedback.ever_lateral_active = False
|
||||
elif fault == 'new_event':
|
||||
sm.logMonoTime['onroadEvents'] += 1
|
||||
elif fault == 'no_warning':
|
||||
change(sm, 'onroadEvents', lambda e: setattr(e[1], 'name', 'steerOverride'))
|
||||
elif fault == 'no_pending':
|
||||
feedback.pending_event = 0
|
||||
elif fault == 'no_restriction':
|
||||
feedback.temporary_eps_event_ns = 0
|
||||
elif fault != 'off':
|
||||
raise AssertionError(fault)
|
||||
assert not retain_pending_restriction_recovery(feedback, sm, cp, state, sm['aolAxisState'], stamp, now,
|
||||
latched=fault != 'off', producer=PRODUCER)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('axis_first', (False, True))
|
||||
@pytest.mark.parametrize('native_granted', (False, True))
|
||||
def test_paused_subaru_event_join_tracks_reason_without_reanchoring_deadlines(axis_first, native_granted):
|
||||
from openpilot.starpilot.car.subaru.paused_intent import retain_paused_restriction
|
||||
cp, state, feedback, sm, native, stamp = paused_case()
|
||||
if native_granted:
|
||||
native_change(sm, native, requestedLateral=True, lateralAllowed=True)
|
||||
before = leases(feedback), feedback.signature
|
||||
assert retain_paused_restriction(feedback, sm, cp, state, sm['aolAxisState'], stamp, stamp,
|
||||
latched=True, producer=PRODUCER)
|
||||
assert feedback.temporary_eps_event_ns == stamp
|
||||
for age in (10_000_000, 12_000_000):
|
||||
if axis_first:
|
||||
fresh, fresh_native = sample(cp, stamp + age, stamp + age, 3, active=False,
|
||||
requested=native_granted, allowed=native_granted, event_stamp=stamp)
|
||||
change(fresh, 'aolAxisState', lambda a, _age=age: (setattr(a, 'faultEventMonoTime', stamp + _age), setattr(a, 'intentIntegrityEpoch', 0)))
|
||||
sm, native = fresh, fresh_native
|
||||
else:
|
||||
event = messaging.new_message('onroadEvents', 2, valid=True, logMonoTime=stamp + age)
|
||||
event.onroadEvents = [{'name': 'pcmDisable', 'userDisable': True}, {'name': 'steerTempUnavailableSilent', 'warning': True}]
|
||||
sm.messages['onroadEvents'] = event.as_reader()
|
||||
sm.logMonoTime['onroadEvents'] = stamp + age
|
||||
assert retain_paused_restriction(feedback, sm, cp, state, sm['aolAxisState'], sm.logMonoTime['aolAxisState'], stamp + age + 1_000_000,
|
||||
latched=True, producer=PRODUCER)
|
||||
assert feedback.pending_event == stamp + 10_000_000
|
||||
assert (leases(feedback), feedback.signature) == before
|
||||
now = stamp + 20_000_000
|
||||
matched, _ = sample(cp, now, now, 4, active=False, requested=native_granted, allowed=native_granted, event_stamp=now)
|
||||
change(matched, 'aolAxisState', lambda a: setattr(a, 'intentIntegrityEpoch', 0))
|
||||
assert retain_paused_restriction(feedback, matched, cp, state, matched['aolAxisState'], now, now,
|
||||
latched=True, producer=PRODUCER)
|
||||
assert feedback.pending_event == 0 and feedback.temporary_eps_event_ns == now
|
||||
assert (leases(feedback), feedback.signature) == before
|
||||
|
||||
|
||||
def test_paused_subaru_brake_release_joins_only_its_accepted_eps_event():
|
||||
from openpilot.starpilot.car.subaru.paused_intent import retain_paused_restriction
|
||||
cp, state, feedback, sm, _, stamp = paused_case()
|
||||
assert retain_paused_restriction(feedback, sm, cp, state, sm['aolAxisState'], stamp, stamp,
|
||||
latched=True, producer=PRODUCER)
|
||||
assert feedback.subaru_eps_brake_event_ns == stamp
|
||||
state.brakePressed = False
|
||||
event = sm.messages['onroadEvents'].as_builder()
|
||||
event.onroadEvents = [{'name': 'pcmDisable', 'userDisable': True}, {'name': 'pedalPressed', 'userDisable': True},
|
||||
{'name': 'steerTempUnavailableSilent', 'warning': True}]
|
||||
sm.messages['onroadEvents'] = event.as_reader()
|
||||
assert retain_paused_restriction(feedback, sm, cp, state, sm['aolAxisState'], stamp, stamp,
|
||||
latched=True, producer=PRODUCER)
|
||||
feedback.subaru_eps_brake_event_ns = 0
|
||||
assert not retain_paused_restriction(feedback, sm, cp, state, sm['aolAxisState'], stamp, stamp,
|
||||
latched=True, producer=PRODUCER)
|
||||
|
||||
|
||||
def test_recovery_brake_release_preserves_only_a_known_pending_eps_brake():
|
||||
from openpilot.starpilot.car.subaru.paused_intent import retain_pending_restriction_recovery
|
||||
cp, state, feedback, sm, _, now = recovery_case()
|
||||
state.brakePressed = False
|
||||
feedback.subaru_eps_brake_event_ns = feedback.temporary_eps_event_ns
|
||||
event = sm.messages['onroadEvents'].as_builder()
|
||||
event.onroadEvents = [{'name': 'pcmDisable', 'userDisable': True}, {'name': 'steerTempUnavailableSilent', 'warning': True},
|
||||
{'name': 'gasPressedOverride', 'overrideLongitudinal': True}, {'name': 'pedalPressed', 'userDisable': True}]
|
||||
sm.messages['onroadEvents'] = event.as_reader()
|
||||
before = leases(feedback)
|
||||
assert retain_pending_restriction_recovery(feedback, sm, cp, state, sm['aolAxisState'], sm.logMonoTime['aolAxisState'], now,
|
||||
latched=True, producer=PRODUCER)
|
||||
assert leases(feedback) == before
|
||||
|
||||
@@ -29,7 +29,8 @@ def test_actual_full_engage_brake_reverse_temporary_recovery_mainoff(candidate,
|
||||
source_outage=False, vm_angle_handoff=0, crawl=False, eps_brake_join=False,
|
||||
high_angle_guard=False, main_on_brake=False, guard_brake_release=False,
|
||||
stopped_feedback_gap=False, rearm_on_brake=0, main_during_eps=False,
|
||||
angle_continuation=0, stopped_source_gap=False, paused_eps=0):
|
||||
angle_continuation=0, stopped_source_gap=False, paused_eps=0,
|
||||
eps_clear_join=0, eps_clear_axis_first=False):
|
||||
angle_handoff = fixed_angle_handoff or vm_angle_handoff
|
||||
fw = firmware_records(candidate, FW_VERSIONS, 'subaru') if firmware is None else firmware
|
||||
rows = []
|
||||
@@ -84,25 +85,31 @@ def test_actual_full_engage_brake_reverse_temporary_recovery_mainoff(candidate,
|
||||
pending_eps_event = None
|
||||
for elapsed, tick in enumerate(ticks):
|
||||
now = base + elapsed * 10_000_000 + (22_504_479 if deadline_gap and elapsed >= gap_tick else 0)
|
||||
if eps_clear_join and tick >= 102:
|
||||
now -= 1_300_000 # Recorded recovery arrives 8.7 ms after its previous CS.
|
||||
if stopped_feedback_gap and elapsed >= 131:
|
||||
now += 3_919_864
|
||||
cruise = not main_only and (30 <= tick < 110 or tick >= 410)
|
||||
if eps_clear_join and not main_only:
|
||||
cruise = 30 <= tick < 80 or tick >= 410
|
||||
brake = ((stopped_feedback_gap or stopped_source_gap) and 125 <= tick < 135 or 90 <= tick < 110 or eps_brake_join and 225 <= tick < 270 or
|
||||
main_on_brake and 30 <= tick < 55 or guard_brake_release and 225 <= tick < 245 or
|
||||
rearm_on_brake and 345 <= tick < 365)
|
||||
brake = bool(brake or angle_continuation and 70 <= tick < 90)
|
||||
if eps_clear_join and 90 <= tick < 145:
|
||||
brake = eps_clear_join in (5, 6) and 95 <= tick < 102
|
||||
reverse = 150 <= tick < 185
|
||||
temporary = not guard_brake_release and 225 <= tick < 260
|
||||
main = not 310 <= tick < 350 and (tick >= 30 or not main_only)
|
||||
stopped = stop_resume and (125 <= tick < 135 if hard_stop_native_first or host_first_stop else 185 <= tick < 195)
|
||||
first_resume = 145 <= tick < 150 if hard_stop_native_first or host_first_stop else 125 <= tick < 145
|
||||
if paused_eps:
|
||||
if paused_eps or eps_clear_join:
|
||||
first_resume = False # Blinker debounce overlaps the later reverse pause.
|
||||
source_missing = bool(source_outage and 75 <= tick < 81)
|
||||
if paused_eps:
|
||||
brake = bool(paused_eps in (1, 3) and 90 <= tick < 115 or not 90 <= tick < 115 and brake)
|
||||
brake = bool(paused_eps in (1, 3, 5, 6) and 90 <= tick < 115 or not 90 <= tick < 115 and brake)
|
||||
stopped = bool(paused_eps in (1, 3) and 90 <= tick < 115 or stopped)
|
||||
temporary = bool(paused_eps in (3, 4) and 95 <= tick < 111 or temporary)
|
||||
temporary = bool(paused_eps in (3, 4, 6) and 95 <= tick < 111 or temporary)
|
||||
|
||||
values = {
|
||||
'Throttle': {'Throttle_Pedal': 100 if source_outage and 60 <= tick < 90 else 0},
|
||||
@@ -150,10 +157,24 @@ def test_actual_full_engage_brake_reverse_temporary_recovery_mainoff(candidate,
|
||||
if paused_eps:
|
||||
values['Dashlights'] = {'LEFT_BLINKER': int(90 <= tick < 115)}
|
||||
values['Wheel_Speeds'] = dict.fromkeys(('FL', 'FR', 'RL', 'RR'), 0 if stopped else 14.4)
|
||||
values['Brake_Pedal'] = {'Speed': 0 if stopped else 14.4}
|
||||
values['Brake_Pedal'] = {'Speed': 0 if stopped else 2.4 if paused_eps in (5, 6) else 14.4}
|
||||
if paused_eps in (5, 6):
|
||||
values['Wheel_Speeds'] = dict.fromkeys(('FL', 'FR', 'RL', 'RR'), 2.4)
|
||||
values['Steering_Torque']['Steer_Torque_Sensor'] = 119 if 90 <= tick <= 100 else 80 if 101 <= tick < 111 else 0
|
||||
if paused_eps in (1, 2):
|
||||
if paused_eps in (5, 6):
|
||||
values['Steering_Torque']['Steer_Torque_Sensor'] = 119 if 104 <= tick < 106 else 70
|
||||
if paused_eps in (1, 2, 5):
|
||||
values['Brake_Pressure_L_R'] = {'Steering_Angle': 101 if 95 <= tick < 111 else 0}
|
||||
if eps_clear_join:
|
||||
values['Throttle']['Throttle_Pedal'] = 100 if eps_clear_join in (2, 4) and 90 <= tick < 145 else 0
|
||||
values['Dashlights'] = {'LEFT_BLINKER': int(90 <= tick < 101)}
|
||||
values['Brake_Pedal'] = {'Speed': 14.4}
|
||||
values['Wheel_Speeds'] = dict.fromkeys(('FL', 'FR', 'RL', 'RR'), 14.4)
|
||||
values['Steering_Torque']['Steer_Torque_Sensor'] = 119 if 90 <= tick < 96 else 59
|
||||
if eps_clear_join in (1, 2, 5):
|
||||
values['Brake_Pressure_L_R'] = {'Steering_Angle': 101 if 95 <= tick < 102 else 0}
|
||||
else:
|
||||
values['Steering_Torque']['Steer_Warning'] = int(95 <= tick < 102 or temporary)
|
||||
incoming = stream.frames(values, tick=tick)
|
||||
if source_outage:
|
||||
pending_host_can.append((now, incoming))
|
||||
@@ -187,15 +208,23 @@ def test_actual_full_engage_brake_reverse_temporary_recovery_mainoff(candidate,
|
||||
for service in ('onroadEvents', 'selfdriveState', 'aolAxisState'):
|
||||
if service not in driven_new or service not in card.sm.data:
|
||||
continue
|
||||
join_tick = 107 if paused_eps in (5, 6) else 101
|
||||
if (eps_clear_join or paused_eps in (5, 6)) and not eps_clear_axis_first and service == 'aolAxisState' and tick == join_tick:
|
||||
continue
|
||||
if stopped_feedback_gap and service == 'aolAxisState' and 130 <= elapsed < 133:
|
||||
continue
|
||||
if eps_brake_join and service == 'onroadEvents' and tick == 236:
|
||||
if (eps_clear_join or paused_eps in (5, 6)) and eps_clear_axis_first and service == 'onroadEvents' and tick == join_tick:
|
||||
pending_eps_event = driven_new[service]
|
||||
elif eps_brake_join and service == 'onroadEvents' and tick == 236:
|
||||
# Deliver the existing event one Card cycle after its axis update.
|
||||
pending_eps_event = driven_new[service]
|
||||
else:
|
||||
peers.append(driven_new[service])
|
||||
if receipt is not None and (tick % 10 == 1 or hard_stop_receipt and not host_first_stop or host_first_stop and elapsed == 127):
|
||||
peers.append(receipt.as_reader())
|
||||
if paused_eps in (5, 6):
|
||||
# SubMaster delivers the latest publication per service after conflation.
|
||||
peers = list({message.which(): message for message in peers}.values())
|
||||
card.sm.update_msgs((now + 1000) / 1e9, peers)
|
||||
published = {}
|
||||
real_new = messaging.new_message
|
||||
@@ -221,6 +250,8 @@ def test_actual_full_engage_brake_reverse_temporary_recovery_mainoff(candidate,
|
||||
patch('openpilot.selfdrive.car.card.messaging.new_message', side_effect=stamped),
|
||||
patch.object(card.pm, 'send', side_effect=capture),
|
||||
):
|
||||
if eps_clear_join and tick == 102 and candidate == CAR.SUBARU_IMPREZA_2020:
|
||||
assert card.aol_transport_feedback.pending_event > 0, 'EPS_RECOVERY_JOIN_NOT_REPRODUCED'
|
||||
card.step()
|
||||
last_card_published = dict(published)
|
||||
pending_host_can.clear()
|
||||
@@ -322,6 +353,8 @@ def test_actual_full_engage_brake_reverse_temporary_recovery_mainoff(candidate,
|
||||
'tick': tick,
|
||||
'elapsed': elapsed,
|
||||
'clearReason': card.aol_card_intent.latch_clear_reason if card.aol_card_intent is not None else None,
|
||||
'feedbackPending': card.aol_transport_feedback.pending_event if card.aol_transport_feedback is not None else None,
|
||||
'feedbackEPS': card.aol_transport_feedback.temporary_eps_event_ns if card.aol_transport_feedback is not None else None,
|
||||
'mainPending': getattr(card.aol_card_intent, '_pending_main_ns', 0),
|
||||
'mainRestriction': getattr(card.aol_card_intent, '_pending_main_restriction_ns', 0),
|
||||
'mainEvent': getattr(card.aol_card_intent, '_main_event_ns', 0),
|
||||
@@ -378,6 +411,9 @@ def test_actual_full_engage_brake_reverse_temporary_recovery_mainoff(candidate,
|
||||
if paused_eps and 90 <= tick < 115:
|
||||
assert row['cardLatch'] and row['armed'] and not row['lat'] and not row['long'], ('SUBARU_PAUSED_EPS_LOST_INTENT', row)
|
||||
assert all(not frame['request'] and frame['output'] == 0 and frame['nativeAccepted'] for frame in row['steering']), row
|
||||
if eps_clear_join and 100 <= tick < 145:
|
||||
assert row['cardLatch'] and row['armed'] and not row['lat'] and not row['long'], ('SUBARU_EPS_CLEAR_LOST_INTENT', row)
|
||||
assert all(not frame['request'] and frame['output'] == 0 and frame['nativeAccepted'] for frame in row['steering']), row
|
||||
assert not command.longActive, row
|
||||
if 10 <= tick < 30:
|
||||
assert not command.latActive and not bool(intent and intent.allowedLatch) and row['permission'] == 0, row
|
||||
@@ -634,3 +670,30 @@ def test_actual_paused_subaru_restriction_keeps_armed_intent(subaru_native_pair,
|
||||
test_actual_full_engage_brake_reverse_temporary_recovery_mainoff(
|
||||
CAR.SUBARU_IMPREZA_2020, subaru_native_pair, tmp_path, main_only=True,
|
||||
preferences=preferences, paused_eps=restriction)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('recovery', (1, 2, 3, 4, 5, 6),
|
||||
ids=('guard', 'guard-gas', 'raw-eps', 'raw-eps-gas', 'brake-release-guard', 'brake-release-eps'))
|
||||
@pytest.mark.parametrize('axis_first', (False, True), ids=('event-first', 'axis-first'))
|
||||
def test_actual_subaru_eps_clear_during_blinker_pause_keeps_armed_intent(
|
||||
subaru_native_pair, tmp_path, recovery, axis_first, candidate=CAR.SUBARU_IMPREZA_2020):
|
||||
test_actual_full_engage_brake_reverse_temporary_recovery_mainoff(
|
||||
candidate, subaru_native_pair, tmp_path, main_only=candidate in (
|
||||
CAR.SUBARU_IMPREZA_2020, CAR.SUBARU_IMPREZA_2025, CAR.SUBARU_CROSSTREK_2025, CAR.SUBARU_OUTBACK_2023),
|
||||
eps_clear_join=recovery, eps_clear_axis_first=axis_first,
|
||||
preferences={'PauseLateralOnSignal': True, 'PauseLateralSpeed': 100., 'LateralResumeDelay': 0.})
|
||||
|
||||
|
||||
@pytest.mark.parametrize('candidate', (CAR.SUBARU_ASCENT_2023, CAR.SUBARU_LEGACY_2025, CAR.SUBARU_CROSSTREK_2025,
|
||||
CAR.SUBARU_IMPREZA_2025, CAR.SUBARU_FORESTER, CAR.SUBARU_OUTBACK, CAR.SUBARU_OUTBACK_2023))
|
||||
def test_actual_subaru_family_eps_recovery_join(candidate, subaru_native_pair, tmp_path):
|
||||
test_actual_subaru_eps_clear_during_blinker_pause_keeps_armed_intent(subaru_native_pair, tmp_path, 4, axis_first=False, candidate=candidate)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('restriction', (5, 6), ids=('braked-guard', 'braked-eps'))
|
||||
@pytest.mark.parametrize('axis_first', (False, True), ids=('event-first', 'axis-first'))
|
||||
def test_actual_subaru_paused_restriction_event_join(subaru_native_pair, tmp_path, restriction, axis_first):
|
||||
test_actual_full_engage_brake_reverse_temporary_recovery_mainoff(
|
||||
CAR.SUBARU_IMPREZA_2020, subaru_native_pair, tmp_path, main_only=True, paused_eps=restriction,
|
||||
eps_clear_axis_first=axis_first,
|
||||
preferences={'PauseLateralOnSignal': True, 'PauseLateralSpeed': 100., 'LateralResumeDelay': 0.})
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
"""Frozen Model 3 cooperative steering selection."""
|
||||
"""Frozen Model 3/Y cooperative steering selection."""
|
||||
from opendbc.car.tesla.values import CAR, TeslaSafetyFlags, TeslaFlags
|
||||
|
||||
|
||||
def supported(cp):
|
||||
try:
|
||||
if (cp.brand != 'tesla' or cp.carFingerprint != CAR.TESLA_MODEL_3 or cp.passive or cp.dashcamOnly or cp.notCar or
|
||||
if (cp.brand != 'tesla' or cp.carFingerprint not in (CAR.TESLA_MODEL_3, CAR.TESLA_MODEL_Y) or cp.passive or cp.dashcamOnly or cp.notCar or
|
||||
cp.alternativeExperience not in (0, 32) or len(cp.safetyConfigs) != 1 or int(cp.safetyConfigs[0].safetyModel.raw) != 10 or
|
||||
cp.flags & ~int(TeslaFlags.MISSING_DAS_SETTINGS | TeslaFlags.HAS_VEHICLE_BUS | TeslaFlags.AOL_SCREEN_BUTTON)):
|
||||
return False
|
||||
|
||||
@@ -21,7 +21,7 @@ def is_angle_steering_limited(CP, requested_angle: float, car_output, companion,
|
||||
safety_config.safetyParam & TeslaSafetyFlags.COOP_STEERING.value
|
||||
for safety_config in CP.safetyConfigs
|
||||
)
|
||||
if CP.carFingerprint != CAR.TESLA_MODEL_3 or not cooperative_enabled or not output_healthy:
|
||||
if CP.carFingerprint not in (CAR.TESLA_MODEL_3, CAR.TESLA_MODEL_Y) or not cooperative_enabled or not output_healthy:
|
||||
return legacy_limited
|
||||
|
||||
info = companion.steeringLimitInfo
|
||||
|
||||
@@ -15,8 +15,9 @@ from openpilot.starpilot.ui.feature_settings_state import FeatureSettingsRequest
|
||||
|
||||
@pytest.mark.parametrize('long', (False, True))
|
||||
@pytest.mark.parametrize('brake', (False, True))
|
||||
def test_screen_and_cooperative_selection_compose(long, brake):
|
||||
cp = screen_params(long=long)
|
||||
@pytest.mark.parametrize('candidate', (CAR.TESLA_MODEL_3, CAR.TESLA_MODEL_Y))
|
||||
def test_screen_and_cooperative_selection_compose(long, brake, candidate):
|
||||
cp = screen_params(candidate, long=long)
|
||||
prepare(cp, True)
|
||||
apply_screen_button(cp, True, brake)
|
||||
assert cp.safetyConfigs[0].safetyParam == 768 + int(long) + 1024 * brake
|
||||
@@ -30,7 +31,8 @@ def test_screen_and_cooperative_selection_compose(long, brake):
|
||||
|
||||
@pytest.mark.parametrize('enabled,safe,value,expected', ((True,None,b'1',True),(False,None,b'1',False),
|
||||
(True,b'1',b'1',False),(True,None,b'bad',False),(True,None,None,False)))
|
||||
def test_startup_snapshot(tmp_path, enabled, safe, value, expected):
|
||||
@pytest.mark.parametrize('candidate', (CAR.TESLA_MODEL_3, CAR.TESLA_MODEL_Y))
|
||||
def test_startup_snapshot(tmp_path, enabled, safe, value, expected, candidate):
|
||||
saved = Params(str(tmp_path))
|
||||
for key, raw in (('TeslaCoopSteering',value),('SafeMode',safe)):
|
||||
if raw is not None:
|
||||
@@ -40,14 +42,15 @@ def test_startup_snapshot(tmp_path, enabled, safe, value, expected):
|
||||
saved.put_bool(key,raw == b'1',block=True)
|
||||
snapshot = VehicleStartupPreferences.read(saved, enabled=enabled)
|
||||
assert snapshot.tesla_cooperative is expected
|
||||
cp=screen_params()
|
||||
cp=screen_params(candidate)
|
||||
snapshot.prepare(cp)
|
||||
assert bool(cp.safetyConfigs[0].safetyParam & 256) is expected
|
||||
|
||||
|
||||
def test_ui_setting_is_parked_bound_and_requires_startup(tmp_path):
|
||||
@pytest.mark.parametrize('candidate', (CAR.TESLA_MODEL_3, CAR.TESLA_MODEL_Y))
|
||||
def test_ui_setting_is_parked_bound_and_requires_startup(tmp_path, candidate):
|
||||
saved=Params(str(tmp_path))
|
||||
cp=screen_params()
|
||||
cp=screen_params(candidate)
|
||||
parked=True
|
||||
owner=FeatureSettingsOwner(saved,lambda group:parked and group=='parked_preferences',vehicle_fingerprint=lambda:cp.carFingerprint,vehicle_params=lambda:cp)
|
||||
row=owner.tesla_coop.rows(True)[0]
|
||||
@@ -57,12 +60,13 @@ def test_ui_setting_is_parked_bound_and_requires_startup(tmp_path):
|
||||
assert cp.safetyConfigs[0].safetyParam==0
|
||||
parked=False
|
||||
assert not owner.apply(replace(request,expected=b'1',value='Off'))
|
||||
cp.carFingerprint=CAR.TESLA_MODEL_Y
|
||||
cp.carFingerprint=CAR.TESLA_MODEL_X
|
||||
assert not owner.tesla_coop.rows(True)
|
||||
|
||||
|
||||
def test_offset_is_not_saturation_and_invalid_evidence_falls_back():
|
||||
cp=screen_params()
|
||||
@pytest.mark.parametrize('candidate', (CAR.TESLA_MODEL_3, CAR.TESLA_MODEL_Y))
|
||||
def test_offset_is_not_saturation_and_invalid_evidence_falls_back(candidate):
|
||||
cp=screen_params(candidate)
|
||||
prepare(cp,True)
|
||||
output=SimpleNamespace(actuatorsOutput=SimpleNamespace(steeringAngleDeg=4.))
|
||||
info=SimpleNamespace(valid=True,monoTime=100,modelLimitErrorDeg=0.,resumeLimitErrorDeg=0.,cooperativeLimitErrorDeg=0.,combinedLimitErrorDeg=0.,cooperativeOffsetDeg=4.)
|
||||
|
||||
@@ -480,10 +480,11 @@ class SceneProjector:
|
||||
# projecting forward. Use that endpoint only to clear an existing stop;
|
||||
# Curve geometry and cold stop acquisition retain strict validation.
|
||||
stop_horizon = _standstill_clear_horizon(model)
|
||||
# A fresh discrete stop bit can corroborate an existing Ford stopped
|
||||
# hold even when geometry is unavailable. Geometry admission stays strict.
|
||||
# A fresh stop bit can corroborate a Ford hold or re-arm a light just
|
||||
# released at standstill; cold stop acquisition still needs geometry.
|
||||
current_stop = model_should_stop if (stop_horizon is not None or
|
||||
_field(cp, 'carFingerprint') in FORD_STOP_NAMES and _field(car, 'standstill') is True) else None
|
||||
(_field(cp, 'carFingerprint') in FORD_STOP_NAMES or self.stop_detector.released_standstill_light) and
|
||||
_field(car, 'standstill') is True) else None
|
||||
lead = _lead(radar) if radar is not None else None
|
||||
car_valid = speed is not None
|
||||
headway_fresh = (
|
||||
|
||||
@@ -108,16 +108,19 @@ class StopLightDetector:
|
||||
self.standstill_reason: str | None = None
|
||||
self.committed = False
|
||||
self.standstill_committed = False
|
||||
self.released_standstill_light = False
|
||||
self.commit_distance_m = 0.0
|
||||
self.commit_clear_since_s: float | None = None
|
||||
self.last_observed_mono_s: float | None = None
|
||||
self.last_model_tick_mono_s: float | None = None
|
||||
|
||||
def invalidate(self) -> None:
|
||||
committed, distance, stopped = self.committed, self.commit_distance_m, self.standstill_committed
|
||||
committed, distance, stopped, released = (self.committed, self.commit_distance_m,
|
||||
self.standstill_committed, self.released_standstill_light)
|
||||
self.reset()
|
||||
# Missing evidence cannot acquire a stop or prove that a committed one cleared.
|
||||
self.committed, self.commit_distance_m, self.standstill_committed = committed, distance, stopped
|
||||
self.released_standstill_light = released
|
||||
|
||||
def _reset_light(self) -> None:
|
||||
# Retain filter alpha across resets; clear its state and latches.
|
||||
@@ -133,7 +136,16 @@ class StopLightDetector:
|
||||
self.committed = False
|
||||
self.standstill_committed = False
|
||||
self.commit_clear_since_s = None
|
||||
self.released_standstill_light = False
|
||||
return
|
||||
if self.released_standstill_light:
|
||||
if frame.standstill is False:
|
||||
self.released_standstill_light = False
|
||||
elif frame.standstill is True and frame.model_should_stop is True:
|
||||
self.committed = self.standstill_committed = True
|
||||
self.commit_distance_m = 0.0
|
||||
self.standstill_reason = 'light'
|
||||
self.released_standstill_light = False
|
||||
clear_launch = (frame.standstill is True and frame.longitudinal_launch_active is True and
|
||||
frame.longitudinal_stop_active is False and
|
||||
frame.model_should_stop is False and model_stopping is False and frame.forcing_stop is False and
|
||||
@@ -150,14 +162,19 @@ class StopLightDetector:
|
||||
self.commit_distance_m) + STOP_MODEL_RELEASE_MARGIN_M
|
||||
clear = (horizon is not None and model_stopping is False and frame.model_should_stop is False and
|
||||
horizon >= clear_distance)
|
||||
clear_stationary_light = (launch_clear and self.standstill_reason == 'light' and
|
||||
frame.stop_sign_confirmed is False and frame.dashboard_stop_sign is False and
|
||||
frame.lead is not None and frame.lead.present is False)
|
||||
if clear:
|
||||
if self.commit_clear_since_s is None:
|
||||
self.commit_clear_since_s = frame.now_mono_s
|
||||
elif frame.now_mono_s - self.commit_clear_since_s >= 0.5:
|
||||
if clear_stationary_light or (self.commit_clear_since_s is not None and
|
||||
frame.now_mono_s - self.commit_clear_since_s >= 0.5):
|
||||
self.released_standstill_light = clear_stationary_light
|
||||
self.committed = False
|
||||
self.standstill_committed = False
|
||||
self.commit_clear_since_s = None
|
||||
self._reset_light()
|
||||
elif self.commit_clear_since_s is None:
|
||||
self.commit_clear_since_s = frame.now_mono_s
|
||||
else:
|
||||
self.commit_clear_since_s = None
|
||||
|
||||
|
||||
@@ -78,45 +78,11 @@ class RecordedLaunchTests(CemGreenCallerTests):
|
||||
else:
|
||||
self.assertTrue(self.owner.mode.projector.stop_detector.committed, change)
|
||||
|
||||
def test_candidate_clear_dwell_restarts_after_real_stop(self):
|
||||
def test_real_stop_request_remains_after_light_handoff(self):
|
||||
self.prime()
|
||||
samples = json.loads(gzip.decompress((Path(__file__).parent / 'testdata/route160_stationary_launch.json.gz').read_bytes()))
|
||||
frame = next(f for f in samples if f['accel'] > 0.35 and min(f['x']) < -0.02)
|
||||
for stop in [False] * 6 + [True] + [False] * 6:
|
||||
_, _, held, plan = self.cycle(stopped=True, position=frame['x'], velocity=frame['v'], should_stop=stop, desired_accel=frame['accel'])
|
||||
self.assertTrue(held and plan.shouldStop)
|
||||
self.assertLessEqual(plan.aTarget, 0.0)
|
||||
|
||||
|
||||
def test_candidate_numeric_time_and_lead_guards():
|
||||
from copy import deepcopy
|
||||
from types import SimpleNamespace as N
|
||||
from openpilot.selfdrive.modeld.constants import ModelConstants
|
||||
from openpilot.starpilot.conditional_mode.launch_geometry import qualified_launch_horizon
|
||||
|
||||
samples = json.loads(gzip.decompress((Path(__file__).parent / 'testdata/route160_stationary_launch.json.gz').read_bytes()))
|
||||
f = next(f for f in samples if f['accel'] > 0.35 and min(f['x']) < -0.02)
|
||||
model = N(
|
||||
position=N(x=f['x'], t=list(ModelConstants.T_IDXS)),
|
||||
velocity=N(x=f['v'], t=list(ModelConstants.T_IDXS)),
|
||||
action=N(shouldStop=False, desiredAcceleration=f['accel']),
|
||||
)
|
||||
car = N(standstill=True, vEgoRaw=0.0, vEgo=0.0, gasPressed=False, brakePressed=False)
|
||||
assert qualified_launch_horizon(model, car, False) > 54
|
||||
changes = [
|
||||
lambda m: setattr(m.velocity, 't', [0.0] * 33),
|
||||
lambda m: m.position.t.__setitem__(-1, 1000.0),
|
||||
lambda m: setattr(m.action, 'desiredAcceleration', 1000.0),
|
||||
lambda m: m.position.x.__setitem__(20, 0.0),
|
||||
lambda m: m.velocity.x.__setitem__(25, 0.0),
|
||||
lambda m: setattr(m.action, 'shouldStop', True),
|
||||
]
|
||||
for change in changes:
|
||||
m = deepcopy(model)
|
||||
change(m)
|
||||
assert qualified_launch_horizon(m, car, False) is None
|
||||
assert qualified_launch_horizon(model, car, True) is None
|
||||
for name, value in [('standstill', False), ('vEgoRaw', 0.01), ('vEgo', 0.1), ('gasPressed', True), ('brakePressed', True)]:
|
||||
c = deepcopy(car)
|
||||
setattr(c, name, value)
|
||||
assert qualified_launch_horizon(model, c, False) is None
|
||||
_, _, held, plan = self.cycle(stopped=True, position=frame['x'], velocity=frame['v'], should_stop=False, desired_accel=frame['accel'])
|
||||
self.assertFalse(held or plan.shouldStop)
|
||||
_, _, _, plan = self.cycle(stopped=True, position=frame['x'], velocity=frame['v'], should_stop=True, desired_accel=frame['accel'])
|
||||
self.assertTrue(plan.shouldStop)
|
||||
|
||||
@@ -0,0 +1,118 @@
|
||||
from dataclasses import replace
|
||||
|
||||
import pytest
|
||||
from opendbc.car import structs
|
||||
from opendbc.car.hyundai.interface import CarInterface
|
||||
from opendbc.car.hyundai.values import CAR
|
||||
from openpilot.selfdrive.controls.lib.longcontrol import LongControl, LongCtrlState
|
||||
from openpilot.starpilot.conditional_mode.stop import StopFrame, StopLead, StopLightDetector
|
||||
|
||||
|
||||
def held_light():
|
||||
detector = StopLightDetector()
|
||||
detector.committed = detector.standstill_committed = True
|
||||
detector.standstill_reason = 'light'
|
||||
frame = StopFrame(100., 100., 0., 80., 7.7, False, False, False, StopLead(False), True,
|
||||
False, False, 0., False, 'HYUNDAI_IONIQ_6', dashboard_stop_sign=False,
|
||||
pedal_override=False, model_tick_mono_s=100., model_should_stop=False,
|
||||
stationary_launch_clear=True)
|
||||
return detector, frame
|
||||
|
||||
|
||||
def test_qualified_stationary_light_does_not_add_a_countdown():
|
||||
detector, frame = held_light()
|
||||
detector._commit(frame, 80., False, False, .05)
|
||||
assert not detector.committed or detector.standstill_committed
|
||||
assert not detector.committed and not detector.standstill_committed
|
||||
|
||||
|
||||
@pytest.mark.parametrize('changes', [
|
||||
{'model_should_stop': True}, {'forcing_stop': True}, {'stationary_launch_clear': False},
|
||||
{'stop_sign_confirmed': True}, {'dashboard_stop_sign': True},
|
||||
{'lead': StopLead(True)}, {'lead': None}, {'standstill': False},
|
||||
])
|
||||
def test_shortcut_requires_the_existing_clear_light_proof(changes):
|
||||
detector, frame = held_light()
|
||||
detector._commit(replace(frame, **changes), 80., False, False, .05)
|
||||
assert detector.committed
|
||||
|
||||
|
||||
@pytest.mark.parametrize('reason', ['sign', None])
|
||||
def test_nonlight_hold_does_not_receive_the_light_shortcut(reason):
|
||||
detector, frame = held_light()
|
||||
detector.standstill_reason = reason
|
||||
detector._commit(frame, 80., False, False, .05)
|
||||
assert detector.committed
|
||||
|
||||
|
||||
def test_unknown_or_short_geometry_cannot_clear_the_hold():
|
||||
for horizon in (None, 2.):
|
||||
detector, frame = held_light()
|
||||
detector._commit(frame, horizon, None if horizon is None else True, False, .05)
|
||||
assert detector.committed
|
||||
|
||||
|
||||
def test_native_stop_request_still_overrides_a_positive_target():
|
||||
cp = CarInterface.get_non_essential_params(CAR.HYUNDAI_IONIQ_6)
|
||||
cp.openpilotLongitudinalControl = True
|
||||
car = structs.CarState.new_message(vEgo=0., aEgo=0., canValid=True)
|
||||
control = LongControl(cp)
|
||||
control.long_control_state = LongCtrlState.stopping
|
||||
assert control.update(True, car, .35, False, (-3.5, 2.)) > 0.
|
||||
assert control.update(True, car, .35, True, (-3.5, 2.)) <= 0.
|
||||
|
||||
|
||||
def test_retained_renewed_stop_sequence_matches_native_handback():
|
||||
cp = CarInterface.get_non_essential_params(CAR.HYUNDAI_IONIQ_6)
|
||||
cp.openpilotLongitudinalControl = True
|
||||
car = structs.CarState.new_message(vEgo=0., aEgo=0., canValid=True)
|
||||
native, candidate = LongControl(cp), LongControl(cp)
|
||||
native.long_control_state = candidate.long_control_state = LongCtrlState.stopping
|
||||
detector, frame = held_light()
|
||||
for i in range(45):
|
||||
stop = i >= 22
|
||||
target = .1 if i < 20 else .35
|
||||
current = replace(frame, now_mono_s=100. + i * .05, model_should_stop=stop,
|
||||
stationary_launch_clear=i >= 20 and not stop)
|
||||
detector._commit(current, 80. if i >= 20 else None, False if i >= 20 else None, False, .05)
|
||||
native_stop = stop or i < 20
|
||||
candidate_stop = native_stop or detector.standstill_committed
|
||||
for _ in range(5):
|
||||
baseline = native.update(True, car, target, native_stop, (-3.5, 2.))
|
||||
actual = candidate.update(True, car, target, candidate_stop, (-3.5, 2.))
|
||||
assert actual == pytest.approx(baseline)
|
||||
if stop:
|
||||
assert actual <= 0.
|
||||
|
||||
|
||||
def test_released_light_honors_a_renewed_stop_without_new_geometry():
|
||||
detector, frame = held_light()
|
||||
detector._commit(frame, 80., False, False, .05)
|
||||
assert detector.released_standstill_light and not detector.committed
|
||||
renewed = replace(frame, now_mono_s=100.1, model_should_stop=True)
|
||||
detector._commit(renewed, None, None, False, .05)
|
||||
assert detector.committed and detector.standstill_committed
|
||||
|
||||
|
||||
def test_unknown_source_retains_only_the_prior_light_episode():
|
||||
detector, frame = held_light()
|
||||
detector._commit(frame, 80., False, False, .05)
|
||||
detector.invalidate()
|
||||
assert detector.released_standstill_light and not detector.committed
|
||||
detector._commit(replace(frame, now_mono_s=100.1, model_should_stop=True), None, None, False, .05)
|
||||
assert detector.committed
|
||||
|
||||
|
||||
@pytest.mark.parametrize('change', [{'standstill': False}, {'pedal_override': True}])
|
||||
def test_motion_or_driver_override_ends_the_released_light_episode(change):
|
||||
detector, frame = held_light()
|
||||
detector._commit(frame, 80., False, False, .05)
|
||||
detector._commit(replace(frame, now_mono_s=100.1, **change), None, None, False, .05)
|
||||
assert not detector.released_standstill_light
|
||||
|
||||
|
||||
def test_stop_bit_alone_cannot_acquire_a_new_light():
|
||||
detector, frame = held_light()
|
||||
detector.reset()
|
||||
detector._commit(replace(frame, model_should_stop=True), None, None, False, .05)
|
||||
assert not detector.committed
|
||||
@@ -29,8 +29,9 @@ class TestCloudConsumers(unittest.TestCase):
|
||||
provider.mark_recording(self.konik,'konik')
|
||||
|
||||
def test_actual_uploader_and_athena_listing_keep_legacy_comma_out(self):
|
||||
with patch.object(uploader, 'Api', return_value=SimpleNamespace()):
|
||||
with patch.object(uploader, 'Api', return_value=SimpleNamespace()), patch.object(uploader.os, 'nice') as nice:
|
||||
instance = uploader.Uploader('0'*16, str(self.root))
|
||||
nice.assert_called_once_with(10)
|
||||
with patch.object(uploader,'getxattr',return_value=None):
|
||||
files = list(instance.list_upload_files(False))
|
||||
self.assertTrue(files)
|
||||
|
||||
@@ -35,7 +35,13 @@ class TestCurvePlanner(unittest.TestCase):
|
||||
before = message_bytes(envelopes)
|
||||
slc = CruiseCeiling(slc_speed, ACTIVE) if slc_speed is not None else None
|
||||
current.update(sm, cruise_ceiling=slc, curve_ceiling=CurveCeiling(curve_speed, stamp))
|
||||
expected.update(sm, cruise_ceiling=CruiseCeiling(min(curve_speed, slc_speed or 100), ACTIVE))
|
||||
if selected:
|
||||
reference, _ = messages()
|
||||
reference['carControl'].longActive = True
|
||||
reference['carState'].vCruise = curve_speed * 3.6
|
||||
expected.update(Inputs(reference, stamp))
|
||||
else:
|
||||
expected.update(sm, cruise_ceiling=slc)
|
||||
self.assertEqual(message_bytes(envelopes), before)
|
||||
self.assertEqual(snapshot(current), snapshot(expected))
|
||||
self.assertEqual(current.last_curve_ceiling_status, 'selected' if selected else 'not_binding')
|
||||
|
||||
@@ -113,6 +113,7 @@ SEQUENCE = (
|
||||
|
||||
|
||||
class TestIoniq6ControllerReplay(unittest.TestCase):
|
||||
@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)
|
||||
def test_frozen_stateful_controller_trace(self):
|
||||
self.assertEqual(_GOLDEN["sourceCommit"], "678af783")
|
||||
@@ -128,6 +129,7 @@ class TestIoniq6ControllerReplay(unittest.TestCase):
|
||||
_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_STANDARD_HIGHWAY_FRICTION_THRESHOLD_INCREASE", 0.0, create=True)
|
||||
@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):
|
||||
self.assertEqual(_EXTENDED["sourceCommit"], "678af783")
|
||||
@@ -149,6 +151,7 @@ class TestIoniq6ControllerReplay(unittest.TestCase):
|
||||
_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_STANDARD_HIGHWAY_FRICTION_THRESHOLD_INCREASE", 0.0, create=True)
|
||||
@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):
|
||||
self.assertEqual(_LIVE["sourceControllerSha256"], _GOLDEN["controllerSha256"])
|
||||
@@ -169,6 +172,7 @@ class TestIoniq6ControllerReplay(unittest.TestCase):
|
||||
_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_STANDARD_HIGHWAY_FRICTION_THRESHOLD_INCREASE", 0.0, create=True)
|
||||
@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):
|
||||
for firmware, fw in (("2023", False), ("2025", True)):
|
||||
|
||||
@@ -39,7 +39,8 @@ from openpilot.starpilot.ui.sentry_owner import RESET as SENTRY_RESET, SentryOwn
|
||||
from openpilot.starpilot.ui.vasm_owner import ANNOTATION as VASM_ANNOTATION, RESET as VASM_RESET, VASMOwner, validated_annotation
|
||||
|
||||
|
||||
PAGES = frozenset(("hub", "localization", "starport_options", "driving_options", "resets", "vehicle", "slc", "lane", "lane_change", "profiles", "personalities",
|
||||
PAGES = frozenset(("hub", "developer", "localization", "starport_options", "driving_options", "resets", "vehicle",
|
||||
"slc", "lane", "lane_change", "profiles", "personalities",
|
||||
"traffic", "aggressive", "standard", "relaxed",
|
||||
"curve", "torque", "torque/developer", "tuning", "torque/bluepilot", "aol", "wheel", "appearance", "display",
|
||||
"data", "power", "sounds", "pip", "sentry", "vasm",
|
||||
@@ -650,6 +651,8 @@ class SettingsGateway:
|
||||
return self._localization_owner(ctx).snapshot()
|
||||
if page in ("starport_options", "driving_options", "resets"):
|
||||
return self._device_settings_owner(ctx).snapshot(page)
|
||||
if page == "developer":
|
||||
return self._appearance_owner(ctx).developer_snapshot()
|
||||
if page == "appearance":
|
||||
return self._appearance_owner(ctx).snapshot(Profile.COMPACT, include_large=True)
|
||||
if page == "sounds":
|
||||
@@ -680,6 +683,7 @@ class SettingsGateway:
|
||||
state = replace(state, title="Data & Connections")
|
||||
if page == "hub":
|
||||
state = replace(state, rows=state.rows + (
|
||||
FeatureRow("", "Developer", "Advanced display calibration", page="developer", available=True),
|
||||
FeatureRow("", "Longitudinal options", "Vision-only cruise control and Enhanced Stops", page="driving_options", available=True),
|
||||
))
|
||||
if page in ("torque", "torque/developer"):
|
||||
@@ -883,7 +887,7 @@ class SettingsGateway:
|
||||
raise SettingsChanged("Default or saved settings changed")
|
||||
if intent.page == "pip":
|
||||
return self._pip_owner(ctx, live=True, session_valid=session_valid).apply(intent.request)
|
||||
if intent.page == "appearance":
|
||||
if intent.page in ("appearance", "developer"):
|
||||
return self._appearance_owner(ctx, live=True, session_valid=session_valid).apply(intent.request)
|
||||
if intent.page == "sounds":
|
||||
return self._sounds_owner(ctx, live=True, session_valid=session_valid).apply(intent.request)
|
||||
|
||||
@@ -98,7 +98,7 @@ class DeviceSettingsTest(unittest.TestCase):
|
||||
self.assertEqual([row.key for row in owner.snapshot("resets").rows], [DRIVER_MONITORING_RESET, CALIBRATION_RESET])
|
||||
service.call.assert_not_called()
|
||||
self.assertEqual(owner.snapshot("starport_options").rows, ())
|
||||
self.assertNotIn("developer", PAGES)
|
||||
self.assertIn("developer", PAGES)
|
||||
|
||||
def test_always_hold_default_registry_exact_save_and_parked_authority(self):
|
||||
from openpilot.common.params import Params, ParamKeyType
|
||||
|
||||
@@ -266,7 +266,8 @@ async function layout(label) {
|
||||
}
|
||||
async function show(selector) { await execute('document.querySelector(arguments[0]).scrollIntoView({block:"center",behavior:"instant"})', selector) }
|
||||
async function capture(name) {
|
||||
const base64 = await command(`/session/${session}/screenshot`, {}, 'GET')
|
||||
const { data: base64 } = await command(`/session/${session}/goog/cdp/execute`, { cmd: 'Page.captureScreenshot',
|
||||
params: { format: 'png', captureBeyondViewport: false, optimizeForSpeed: true } })
|
||||
screenshots.push({ name, png_base64: base64 })
|
||||
}
|
||||
let failure = null
|
||||
@@ -699,6 +700,7 @@ try {
|
||||
console.log(`Real Chromium FLM UI: ${checks.length} responsive/theme/state checks, 5 findings/7 destinations, parked save/reset, driving lockout, errors and retained evidence passed`)
|
||||
} catch (error) {
|
||||
failure = error.stack
|
||||
console.error(failure)
|
||||
if (session) { try { await capture('failure') } catch {} }
|
||||
throw error
|
||||
} finally {
|
||||
@@ -729,5 +731,5 @@ try {
|
||||
result.flmUxBrowser.cleanup = { driver_exit_code: driver.exitCode, driver_signal: driver.signalCode, driver_reaped: !running(driver), server_closed: !server.listening }
|
||||
await writeFile(output, JSON.stringify(result))
|
||||
console.log('FLM browser cleanup:', JSON.stringify(result.flmUxBrowser.cleanup))
|
||||
await rm(profile, { recursive: true, force: true })
|
||||
await rm(profile, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 })
|
||||
}
|
||||
|
||||
@@ -1314,3 +1314,13 @@ console.log("Ford rear fog: make visibility, saved placement and strict metadata
|
||||
sample.document.version = 16
|
||||
assert.equal(validDocument(sample.document, sample.metadata), false)
|
||||
}
|
||||
|
||||
const speedAdjustment = snapshot()
|
||||
speedAdjustment.document.speedDisplayOffset = -1.7
|
||||
assert.ok(validDocument(speedAdjustment.document, speedAdjustment.metadata))
|
||||
assert.equal(layoutDocument({ ...speedAdjustment.document, display: {} }).speedDisplayOffset, -1.7)
|
||||
for (const invalidOffset of [true, null, "1", NaN, Infinity, -5.1, 5.1]) {
|
||||
const document = { ...speedAdjustment.document, speedDisplayOffset: invalidOffset }
|
||||
assert.equal(validDocument(document, speedAdjustment.metadata), false)
|
||||
}
|
||||
assert.ok(SETTINGS_SECTIONS.find(section => section.id === "developer").pages.includes("developer"))
|
||||
|
||||
@@ -420,11 +420,12 @@ assert.equal(htmlStates.at(-1).error, "Galaxy could not load settings. Refresh t
|
||||
htmlFeed.stop()
|
||||
|
||||
const sections = (await import('../web/js/settings.js')).SETTINGS_SECTIONS
|
||||
assert(!sections.some(section => section.id === 'developer'))
|
||||
assert.equal(sections.at(-1).id, 'device')
|
||||
assert.equal(sections.at(-1).label, 'Device & System')
|
||||
assert.equal(sections.at(-1).id, 'developer')
|
||||
assert.deepEqual(sections.at(-1).pages, ['developer'])
|
||||
assert.equal(sections.at(-2).id, 'device')
|
||||
assert.equal(sections.at(-2).label, 'Device & System')
|
||||
assert(!sections.some(section => section.id === 'localization'))
|
||||
assert(sections.at(-1).pages.includes('localization'))
|
||||
assert(sections.find(section => section.id === 'device').pages.includes('localization'))
|
||||
assert(sections.find(section => section.id === 'device').pages.includes('starport_options'))
|
||||
assert(sections.find(section => section.id === 'longitudinal').pages.includes('driving_options'))
|
||||
assert.match(SettingsPage.template, /state.data\?\.page === 'data'/)
|
||||
@@ -477,7 +478,7 @@ assert.equal(brakeRows[0].row.label, "Disengage AOL on Brake")
|
||||
assert.equal(requests.length, 0)
|
||||
feed.scheduleParkedRefresh()
|
||||
assert.equal(timers.size, 0)
|
||||
const device = SETTINGS_SECTIONS.at(-1)
|
||||
const device = SETTINGS_SECTIONS.find(section => section.id === "device")
|
||||
const rows = SettingsPage.computed.visibleRows.call({initialPage:'hub', activeSection:device, state:{query:'', data:{page:'hub',rows:[]}}})
|
||||
assert.deepEqual(rows.map(({row})=>row.page), ['power','data','starport_options','browser_preferences','localization'])
|
||||
feed.stop()
|
||||
|
||||
@@ -262,7 +262,7 @@ class SettingsGatewayTest(unittest.TestCase):
|
||||
self.assertEqual(next(page for page in lateral["pages"] if page["id"] == "aol")["title"], self.page("aol")["title"])
|
||||
self.assertEqual([row["page"] for row in hub["rows"]],
|
||||
["aol", "lane_change", "lane", "torque", "torque/developer", "curve", "slc", "profiles", "conditional", "wheel",
|
||||
"vehicle", "personalities", "driving_options"])
|
||||
"vehicle", "personalities", "developer", "driving_options"])
|
||||
self.assertEqual([row["page"] for row in self.page("personalities")["rows"]],
|
||||
["aggressive", "standard", "relaxed", "traffic"])
|
||||
for page in ("slc", "lane", "lane_change", "profiles", "conditional", "conditional/cem",
|
||||
|
||||
@@ -0,0 +1,134 @@
|
||||
import copy
|
||||
from dataclasses import replace
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
from typing import cast
|
||||
from unittest.mock import Mock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
from openpilot.common.params import Params
|
||||
from openpilot.starpilot.galaxy.settings import AuthorityContext, ContextSource, SettingsChanged, SettingsGateway
|
||||
from openpilot.starpilot.ui.appearance_owner import AppearanceOwner
|
||||
from openpilot.starpilot.ui.feature_settings_state import FeatureSettingsRequest
|
||||
from openpilot.starpilot.ui.onroad_customization import PARAM_KEY, decode_document, default_document, validate_document
|
||||
from openpilot.starpilot.ui.onroad_large_widgets import CurrentSpeedHud
|
||||
from openpilot.starpilot.ui.onroad_state import OnroadState, SpeedLimitObservation
|
||||
from openpilot.starpilot.ui.raylib import rl
|
||||
from openpilot.starpilot.ui.shell import ShellMode
|
||||
from openpilot.starpilot.ui.tests.test_runtime_snapshot import NOW, RuntimeSnapshotAdapter, ui_fake
|
||||
|
||||
|
||||
def test_real_gateway_global_slider_saves_restores_and_keeps_layout(tmp_path):
|
||||
params = Params(str(tmp_path))
|
||||
document = default_document()
|
||||
document['layouts']['large']['steering_wheel']['enabled'] = False
|
||||
params.put(PARAM_KEY, document, block=True)
|
||||
context = SimpleNamespace(sample=lambda: AuthorityContext(True, None, None))
|
||||
gateway = SettingsGateway(params, cast(ContextSource, context))
|
||||
page = gateway.page('developer', 'session', b'generation')
|
||||
row = page['rows'][0]
|
||||
assert row['label'] == 'Speed display adjustment' and row['value'] == '0'
|
||||
assert row['available'] and row['minimum'] == -5 and row['maximum'] == 5 and row['step'] == .1
|
||||
intent = gateway.preview(page['view'], 0, 0, 'session', b'generation', value='-1.7')['intent']
|
||||
assert gateway.confirm(intent, 'session', b'generation')
|
||||
assert AppearanceOwner(Params(str(tmp_path)), lambda: True).developer_snapshot().rows[0].value == '-1.7'
|
||||
saved = decode_document(Path(params.get_param_path(PARAM_KEY)).read_bytes())
|
||||
assert saved.pop('speedDisplayOffset') == -1.7 and saved == document
|
||||
|
||||
|
||||
def test_default_and_expired_or_stale_intent(tmp_path):
|
||||
params = Params(str(tmp_path))
|
||||
owner = AppearanceOwner(params, lambda: True)
|
||||
assert owner.developer_snapshot().rows[0].value == '0' and params.get(PARAM_KEY) is None
|
||||
row = owner.developer_snapshot().rows[0]
|
||||
assert owner.apply(FeatureSettingsRequest(row.key, row.source, '2.0'))
|
||||
first = Path(params.get_param_path(PARAM_KEY)).read_bytes()
|
||||
assert not owner.apply(FeatureSettingsRequest(row.key, row.source, '-1.7'))
|
||||
assert not AppearanceOwner(params, lambda: False).apply(FeatureSettingsRequest(row.key, first, '0'))
|
||||
assert Path(params.get_param_path(PARAM_KEY)).read_bytes() == first
|
||||
assert owner.apply(FeatureSettingsRequest(row.key, first, '0'))
|
||||
assert params.get(PARAM_KEY) == default_document()
|
||||
|
||||
|
||||
@pytest.mark.parametrize('bad', ['nan', 'inf', '-inf', '5.1', '-5.1', 'invalid', True, None])
|
||||
def test_invalid_adjustment_never_writes(tmp_path, bad):
|
||||
params = Params(str(tmp_path))
|
||||
assert not AppearanceOwner(params, lambda: True).apply(FeatureSettingsRequest('SpeedDisplayOffset', None, bad))
|
||||
assert params.get(PARAM_KEY) is None
|
||||
|
||||
|
||||
@pytest.mark.parametrize('bad', [True, '1', None, float('nan'), float('inf'), -5.1, 5.1])
|
||||
def test_document_rejects_invalid_adjustment(bad):
|
||||
document = default_document()
|
||||
document['speedDisplayOffset'] = bad
|
||||
with pytest.raises(ValueError, match='speed display adjustment'):
|
||||
validate_document(document)
|
||||
|
||||
|
||||
def test_malformed_saved_layout_is_not_overwritten(tmp_path):
|
||||
params = Params(str(tmp_path))
|
||||
path = Path(params.get_param_path(PARAM_KEY))
|
||||
path.write_bytes(b'{broken')
|
||||
owner = AppearanceOwner(params, lambda: True)
|
||||
assert not owner.developer_snapshot().rows[0].available
|
||||
assert not owner.apply(FeatureSettingsRequest('SpeedDisplayOffset', b'{broken', '1'))
|
||||
assert path.read_bytes() == b'{broken'
|
||||
|
||||
|
||||
@pytest.mark.parametrize('metric,speed,adjustment,expected', [(True, 118 / 3.6, -1.7, '116'),
|
||||
(False, 118 / 3.6, -1.7, '72'),
|
||||
(True, 100 / 3.6, 5., '105'),
|
||||
(False, 60 / 2.2369362921, 5., '63'),
|
||||
(True, 0., -5., '0')])
|
||||
def test_actual_speed_label_only_changes_display(metric, speed, adjustment, expected):
|
||||
state = OnroadState(False, True, speed, 120., SpeedLimitObservation(), metric=metric,
|
||||
speed_display_offset_percent=adjustment)
|
||||
before = copy.deepcopy(state)
|
||||
fonts = Mock()
|
||||
fonts.vertical_ink.return_value = (0, 100)
|
||||
with patch('openpilot.starpilot.ui.onroad_large_widgets._center') as draw:
|
||||
CurrentSpeedHud(fonts).render(rl.Rectangle(0, 0, 1860, 1080), state)
|
||||
assert draw.call_args_list[0].args[1] == expected
|
||||
assert state == before and state.speed_mps == speed and state.cruise_kph == 120.
|
||||
assert replace(state, speed_display_offset_percent=0.).display_speed_mps == speed
|
||||
|
||||
|
||||
def test_real_snapshot_keeps_raw_speed_and_cruise_and_projection_replace(tmp_path):
|
||||
params = Params(str(tmp_path))
|
||||
document = default_document()
|
||||
document['speedDisplayOffset'] = -1.7
|
||||
ui = ui_fake()
|
||||
ui.params = params
|
||||
ui.sm['carState'].vEgoCluster = 118 / 3.6
|
||||
baseline = RuntimeSnapshotAdapter(ui).build(ShellMode.ONROAD, now_ns=NOW).onroad
|
||||
params.put(PARAM_KEY, document, block=True)
|
||||
adapter = RuntimeSnapshotAdapter(ui)
|
||||
state = adapter.build(ShellMode.ONROAD, now_ns=NOW).onroad
|
||||
assert state.speed_mps == ui.sm['carState'].vEgoCluster
|
||||
assert state.display_speed_mps == pytest.approx(118 / 3.6 * .983)
|
||||
assert state.cruise_kph == baseline.cruise_kph
|
||||
assert ui.sm['carState'].vCruiseCluster == 80.
|
||||
projection = replace(state, customization=default_document())
|
||||
assert projection.display_speed_mps == state.display_speed_mps
|
||||
assert params.get(PARAM_KEY) == document
|
||||
|
||||
|
||||
@pytest.mark.parametrize('condition', ['expired', 'changed-layout'])
|
||||
def test_gateway_refuses_expired_session_or_concurrent_layout_edit(tmp_path, condition):
|
||||
params = Params(str(tmp_path))
|
||||
context = SimpleNamespace(sample=lambda: AuthorityContext(True, None, None))
|
||||
gateway = SettingsGateway(params, cast(ContextSource, context))
|
||||
page = gateway.page('developer', 'session', b'generation')
|
||||
intent = gateway.preview(page['view'], 0, 0, 'session', b'generation', value='-1.7')['intent']
|
||||
if condition == 'changed-layout':
|
||||
document = default_document()
|
||||
document['clock24Hour'] = True
|
||||
params.put(PARAM_KEY, document, block=True)
|
||||
before = params.get(PARAM_KEY)
|
||||
if condition == 'expired':
|
||||
with pytest.raises(SettingsChanged):
|
||||
gateway.confirm(intent, 'session', b'generation', session_valid=lambda: False)
|
||||
else:
|
||||
assert not gateway.confirm(intent, 'session', b'generation')
|
||||
assert params.get(PARAM_KEY) == before
|
||||
@@ -148,13 +148,14 @@ export const PROJECTION_DISPLAY_SWITCHES = ["blindSpotBorder", "signalBorder", "
|
||||
export function validDocument(document, metadata) {
|
||||
if (!object(document)) return false
|
||||
const profiles = metadata?.projection === true ? ["large"] : PROFILES
|
||||
if (!keysEqual(document, ["version", "palette", "layouts", "widgetColors", "roadColors", ...(Object.hasOwn(document, "widgetOrder") ? ["widgetOrder"] : []), ...(Object.hasOwn(document, "speedSources") ? ["speedSources"] : []), ...(Object.hasOwn(document, "speedSourcesCard") ? ["speedSourcesCard"] : []), ...(Object.hasOwn(document, "speedAlign") ? ["speedAlign"] : []), ...(Object.hasOwn(document, "clock24Hour") ? ["clock24Hour"] : []), ...(metadata?.projection !== true && Object.hasOwn(document, "reduceMotion") ? ["reduceMotion"] : []), ...(Object.hasOwn(document, "showMaxSpeed") ? ["showMaxSpeed"] : []), ...(metadata?.projection !== true && Object.hasOwn(document, "display") ? ["display"] : []), ...(metadata?.projection === true && Object.hasOwn(document, "largeUiGammaTrial") ? ["largeUiGammaTrial"] : []), ...(metadata?.projection === true ? PROJECTION_DISPLAY_SWITCHES.filter(key => Object.hasOwn(document, key)) : []), ...(metadata?.projection === true && Object.hasOwn(document, "leadInfo") ? ["leadInfo"] : [])]) || (metadata?.projection === true ? document.version !== 8 : ![11, 12, 13, 14, 15].includes(document.version)) ||
|
||||
if (!keysEqual(document, ["version", "palette", "layouts", "widgetColors", "roadColors", ...(Object.hasOwn(document, "widgetOrder") ? ["widgetOrder"] : []), ...(Object.hasOwn(document, "speedSources") ? ["speedSources"] : []), ...(Object.hasOwn(document, "speedSourcesCard") ? ["speedSourcesCard"] : []), ...(Object.hasOwn(document, "speedAlign") ? ["speedAlign"] : []), ...(Object.hasOwn(document, "clock24Hour") ? ["clock24Hour"] : []), ...(metadata?.projection !== true && Object.hasOwn(document, "reduceMotion") ? ["reduceMotion"] : []), ...(Object.hasOwn(document, "showMaxSpeed") ? ["showMaxSpeed"] : []), ...(metadata?.projection !== true && Object.hasOwn(document, "speedDisplayOffset") ? ["speedDisplayOffset"] : []), ...(metadata?.projection !== true && Object.hasOwn(document, "display") ? ["display"] : []), ...(metadata?.projection === true && Object.hasOwn(document, "largeUiGammaTrial") ? ["largeUiGammaTrial"] : []), ...(metadata?.projection === true ? PROJECTION_DISPLAY_SWITCHES.filter(key => Object.hasOwn(document, key)) : []), ...(metadata?.projection === true && Object.hasOwn(document, "leadInfo") ? ["leadInfo"] : [])]) || (metadata?.projection === true ? document.version !== 8 : ![11, 12, 13, 14, 15].includes(document.version)) ||
|
||||
(Object.hasOwn(document, "speedSources") && typeof document.speedSources !== "boolean") ||
|
||||
(Object.hasOwn(document, "speedSourcesCard") && typeof document.speedSourcesCard !== "boolean") ||
|
||||
(Object.hasOwn(document, "speedAlign") && !SPEED_ALIGNMENTS.includes(document.speedAlign)) ||
|
||||
(Object.hasOwn(document, "clock24Hour") && typeof document.clock24Hour !== "boolean") ||
|
||||
(Object.hasOwn(document, "reduceMotion") && typeof document.reduceMotion !== "boolean") ||
|
||||
(Object.hasOwn(document, "showMaxSpeed") && typeof document.showMaxSpeed !== "boolean") ||
|
||||
(Object.hasOwn(document, "speedDisplayOffset") && (!Number.isFinite(document.speedDisplayOffset) || document.speedDisplayOffset < -5 || document.speedDisplayOffset > 5)) ||
|
||||
(Object.hasOwn(document, "display") && (!object(document.display) || !Object.values(document.display).every((value) => typeof value === "string"))) ||
|
||||
(Object.hasOwn(document, "largeUiGammaTrial") && typeof document.largeUiGammaTrial !== "boolean") ||
|
||||
PROJECTION_DISPLAY_SWITCHES.some(key => Object.hasOwn(document, key) && typeof document[key] !== "boolean") ||
|
||||
|
||||
@@ -30,6 +30,7 @@ export const SETTINGS_SECTIONS = Object.freeze([
|
||||
{ id: "sounds", label: "Sounds & Alerts", icon: "bi-volume-up", pages: ["sounds"] },
|
||||
{ id: "vehicle", label: "Vehicle", icon: "bi-car-front", pages: ["vehicle"] },
|
||||
{ id: "device", label: "Device & System", icon: "bi-hdd", pages: ["power", "data", "starport_options", "browser_preferences", "localization"] },
|
||||
{ id: "developer", label: "Developer", icon: "bi-code-slash", pages: ["developer"] },
|
||||
])
|
||||
|
||||
// Crop numeric rows and the inline editor row are controlled from the dedicated
|
||||
|
||||
@@ -31,6 +31,7 @@ from openpilot.starpilot.lateral.torque_shaping import (
|
||||
HKG_CANFD_BASE_FRICTION_THRESHOLD = 0.39
|
||||
IONIQ_6_2025_HIGHWAY_FRICTION_THRESHOLD_INCREASE = 0.50
|
||||
IONIQ_6_STANDARD_FRICTION_THRESHOLD_INCREASE = 0.65
|
||||
IONIQ_6_STANDARD_HIGHWAY_FRICTION_THRESHOLD_INCREASE = 0.15
|
||||
|
||||
IONIQ_6_CARS = (CAR.HYUNDAI_IONIQ_6,)
|
||||
|
||||
@@ -883,6 +884,7 @@ class Ioniq6TorquePolicy:
|
||||
friction_threshold = self.surface_math.friction_threshold(self.surface, CS.vEgo, setpoint, desired_lateral_jerk) / max(center_taper, 1e-3)
|
||||
if not self.is_2025 and not CS.steeringPressed and not self.prev_steering_pressed:
|
||||
friction_threshold *= 1.0 + IONIQ_6_STANDARD_FRICTION_THRESHOLD_INCREASE * float(np.interp(CS.vEgo, [3.0, 12.0], [0.0, 1.0]))
|
||||
friction_threshold *= 1.0 + IONIQ_6_STANDARD_HIGHWAY_FRICTION_THRESHOLD_INCREASE * float(np.interp(CS.vEgo, [20.0, 27.0], [0.0, 1.0]))
|
||||
if self.surface is None and not self.is_2025 and not CS.steeringPressed and not self.prev_steering_pressed:
|
||||
friction_threshold += get_ioniq_6_2023_center_friction_increment(
|
||||
CS.vEgo, setpoint, measurement, desired_lateral_jerk, future_desired_lateral_accel) / max(center_taper, 1e-3)
|
||||
|
||||
@@ -325,3 +325,63 @@ class Ioniq6StandardFrictionTests(Ioniq6HighwayFrictionTests):
|
||||
with mock.patch.object(tune, 'IONIQ_6_STANDARD_FRICTION_THRESHOLD_INCREASE', .50):
|
||||
previous = self.trace(**kwargs)[1]
|
||||
self.assertEqual(actual[100:], previous[100:])
|
||||
|
||||
|
||||
class Ioniq6StandardHighwayFrictionTests(Ioniq6HighwayFrictionTests):
|
||||
def controller(self, *, firmware_2025=False, long=False):
|
||||
return super().controller(firmware_2025=firmware_2025, long=long)
|
||||
|
||||
def trace(self, *, speed=32.0, firmware_2025=False, long=False, tuning=True, pressed=False, center=None):
|
||||
if center is None:
|
||||
_, vm = self.controller(firmware_2025=firmware_2025, long=long)
|
||||
center = math.degrees(vm.get_steer_from_curvature(-.001, speed, 0.0))
|
||||
with mock.patch.object(tune, 'IONIQ_6_STANDARD_HIGHWAY_FRICTION_THRESHOLD_INCREASE', .15 if tuning else 0.0, create=True):
|
||||
return super().trace(speed=speed, firmware_2025=firmware_2025, long=long, pressed=pressed, center=center)
|
||||
|
||||
def test_low_speed_and_older_firmware_are_unchanged(self):
|
||||
for kwargs in ({'speed': 20.0}, {'speed': 10.0}, {'speed': 3.0}, {'firmware_2025': True}):
|
||||
with self.subTest(**kwargs):
|
||||
self.assertEqual(self.trace(**kwargs)[1], self.trace(tuning=False, **kwargs)[1])
|
||||
|
||||
def test_constant_turn_strength_live_parameters_and_limits_are_preserved(self):
|
||||
results = []
|
||||
for tuning in (False, True):
|
||||
controller, vm = self.controller()
|
||||
controller.update_torque_parameters(3.2, .01, .08)
|
||||
self.assertAlmostEqual(controller.torque_params.latAccelFactor, 3.2 * 1.22, places=6)
|
||||
self.assertAlmostEqual(controller.torque_params.friction, .08, places=6)
|
||||
self.assertEqual(controller.pid.pos_limit, controller.lateral_accel_from_torque(1.0, controller.torque_params))
|
||||
cs = structs.CarState.new_message(vEgo=32.0, steeringAngleDeg=-3.0,
|
||||
gearShifter=structs.CarState.GearShifter.drive)
|
||||
curve = -vm.calc_curvature(math.radians(cs.steeringAngleDeg), cs.vEgo, 0.0)
|
||||
with mock.patch.object(tune, 'IONIQ_6_STANDARD_HIGHWAY_FRICTION_THRESHOLD_INCREASE', .15 if tuning else 0.0, create=True):
|
||||
for index in range(400):
|
||||
output, _, _ = controller.update(index != 0, cs, vm, SimpleNamespace(angleOffsetDeg=0.0, roll=0.0),
|
||||
True, curve, False, .322)
|
||||
results.append(output)
|
||||
self.assertAlmostEqual(*results, places=12)
|
||||
|
||||
def test_highway_blend_reaches_actual_friction_without_changing_pid_or_requests(self):
|
||||
for speed, ratio in ((20.0, 1.0), (23.5, 1.075), (27.0, 1.15), (32.0, 1.15)):
|
||||
with self.subTest(speed=speed):
|
||||
with mock.patch.object(latcontrol_torque, 'get_friction', wraps=get_friction) as actual:
|
||||
_, rows = self.trace(speed=speed)
|
||||
threshold = actual.call_args.args[2]
|
||||
with mock.patch.object(latcontrol_torque, 'get_friction', wraps=get_friction) as baseline:
|
||||
_, original = self.trace(speed=speed, tuning=False)
|
||||
old_threshold = baseline.call_args.args[2]
|
||||
self.assertAlmostEqual(threshold / old_threshold, ratio, places=12)
|
||||
for row, old in zip(rows, original, strict=True):
|
||||
self.assertEqual(row[2:], old[2:])
|
||||
|
||||
def test_first_frame_after_driver_release_keeps_previous_response(self):
|
||||
results = []
|
||||
for tuning in (False, True):
|
||||
controller, vm = self.controller()
|
||||
policy = selected_policy(controller)
|
||||
policy.prev_steering_pressed = True
|
||||
cs = structs.CarState.new_message(vEgo=32.0, steeringAngleDeg=-3.0)
|
||||
with mock.patch.object(tune, 'IONIQ_6_STANDARD_HIGHWAY_FRICTION_THRESHOLD_INCREASE', .15 if tuning else 0.0, create=True):
|
||||
results.append(controller.update(True, cs, vm, SimpleNamespace(angleOffsetDeg=0.0, roll=0.0),
|
||||
False, .001, False, .322)[0])
|
||||
self.assertEqual(*results)
|
||||
|
||||
@@ -31,8 +31,11 @@ The planner records the decision in `last_cruise_ceiling_status`; it does not
|
||||
publish that diagnostic or alter the longitudinal plan schema.
|
||||
|
||||
This optional input changes only the cruise candidate before the planner's
|
||||
existing jerk limiting. SLC uses the ordinary cruise braking response and selected
|
||||
profile for its capped target; a cap does not strengthen a softer cruise profile. Lead-relevance checks still prevent cruise comfort
|
||||
existing jerk limiting. SLC uses the selected profile for its capped target; a cap does
|
||||
not strengthen a softer cruise profile. While the SLC cap is the final cruise target and no
|
||||
braking-relevant lead is present, an overshoot is corrected over `CRUISE_ACCEL_RESPONSE_TIME`
|
||||
and braking builds at 0.15 m/s³ until -0.3 m/s², so friction brakes engage gently; braking
|
||||
already requested elsewhere keeps the normal jerk. Lead-relevance checks still prevent cruise comfort
|
||||
tuning from weakening braking for a close, slow or braking lead; malformed lead
|
||||
evidence also vetoes that tuning. The native MPC, lead, e2e, stop and acceleration
|
||||
arbitration remain in place. An inactive planner may still compute a nonzero
|
||||
@@ -80,7 +83,7 @@ acceleration/braking limits. It cannot widen the native car acceleration range.
|
||||
Valid saved curves above native acceleration bounds are intersected with those
|
||||
bounds without dropping their other tuning or rewriting the saved document.
|
||||
Lead, e2e and cruise candidates still arbitrate normally. A lower explicit
|
||||
cruise or curve ceiling retains at least native cruise braking even when a saved profile asks
|
||||
cruise or curve ceiling retains at least the native cruise braking floor even when a saved profile asks
|
||||
for a softer approach; stronger configured braking may still apply.
|
||||
`forceDecel` keeps the native cruise braking response. Stock ACC and lateral-only control receive
|
||||
no profile effect. The acados model and cereal schemas are unchanged.
|
||||
|
||||
@@ -208,37 +208,39 @@ class CemGreenCallerTests(unittest.TestCase):
|
||||
|
||||
def test_red_hold_and_clear_release_reach_actual_planner_publication(self):
|
||||
self.prime()
|
||||
for tick in range(18):
|
||||
_, result, held, plan = self.cycle(stopped=True, position=CLEAR_64_X, velocity=CLEAR_64_V, should_stop=False)
|
||||
if tick < 10:
|
||||
self.assertTrue(result.experimental and held and plan.shouldStop)
|
||||
elif tick >= 12:
|
||||
self.assertFalse(result.experimental or held or plan.shouldStop)
|
||||
_, result, held, plan = self.cycle(stopped=True, position=CLEAR_64_X, velocity=CLEAR_64_V, should_stop=False)
|
||||
self.assertFalse(held or plan.shouldStop)
|
||||
self.assertFalse(self.owner.mode.projector.stop_detector.committed)
|
||||
self.assertFalse(held or result.experimental or plan.shouldStop)
|
||||
self.assertGreater(plan.aTarget, 0.)
|
||||
|
||||
def test_missing_source_and_transient_clear_cannot_release_stop(self):
|
||||
self.prime()
|
||||
for _ in range(6):
|
||||
self.cycle(stopped=True, position=CLEAR_64_X, velocity=CLEAR_64_V, should_stop=False)
|
||||
self.cycle(stopped=True, position=CLEAR_64_X, velocity=CLEAR_64_V, should_stop=False, unavailable='modelV2')
|
||||
for _ in range(6):
|
||||
for _ in range(17):
|
||||
_, result, held, plan = self.cycle(stopped=True, position=CLEAR_64_X, velocity=CLEAR_64_V, should_stop=False)
|
||||
self.assertTrue(result.experimental and held and plan.shouldStop)
|
||||
self.cycle(stopped=True, position=RED_97_X, velocity=RED_97_V)
|
||||
self.assertTrue(self.owner.mode.projector.stop_detector.standstill_committed)
|
||||
self.assertFalse(result.experimental or held or plan.shouldStop)
|
||||
|
||||
def test_alive_transport_gap_and_repeated_model_restart_clear_dwell(self):
|
||||
def test_missing_source_cannot_prove_light_clearance(self):
|
||||
self.prime()
|
||||
self.cycle(stopped=True, position=CLEAR_64_X, velocity=CLEAR_64_V, should_stop=False, unavailable='modelV2')
|
||||
self.assertTrue(self.owner.mode.projector.stop_detector.committed)
|
||||
released = False
|
||||
for _ in range(2):
|
||||
_, _, held, plan = self.cycle(stopped=True, position=CLEAR_64_X, velocity=CLEAR_64_V, should_stop=False)
|
||||
released |= not held
|
||||
self.assertTrue(released)
|
||||
self.cycle(stopped=True, position=RED_97_X, velocity=RED_97_V)
|
||||
self.assertTrue(self.planner.output_should_stop)
|
||||
|
||||
def test_alive_transport_gap_and_repeated_model_cannot_prove_clearance(self):
|
||||
for changes in ({'stale': 'radarState'}, {'repeat_model': True}):
|
||||
for _ in range(6):
|
||||
self.cycle(stopped=True, position=CLEAR_64_X, velocity=CLEAR_64_V, should_stop=False)
|
||||
self.owner.mode.projector.stop_detector.reset()
|
||||
self.prime()
|
||||
self.cycle(stopped=True, position=CLEAR_64_X, velocity=CLEAR_64_V, should_stop=False, **changes)
|
||||
for _ in range(6):
|
||||
_, result, held, plan = self.cycle(stopped=True, position=CLEAR_64_X, velocity=CLEAR_64_V, should_stop=False)
|
||||
self.assertTrue(result.experimental and held and plan.shouldStop)
|
||||
self.assertTrue(self.owner.mode.projector.stop_detector.committed)
|
||||
released = False
|
||||
for _ in range(2):
|
||||
_, _, held, _ = self.cycle(stopped=True, position=CLEAR_64_X, velocity=CLEAR_64_V, should_stop=False)
|
||||
released |= not held
|
||||
self.assertTrue(released)
|
||||
self.cycle(stopped=True, position=RED_97_X, velocity=RED_97_V)
|
||||
self.assertTrue(self.planner.output_should_stop)
|
||||
|
||||
def test_should_stop_veto_and_short_geometry_cannot_be_false_clear(self):
|
||||
self.prime()
|
||||
|
||||
@@ -54,7 +54,7 @@ class GlobalBrakingTests(unittest.TestCase):
|
||||
ordinary.mpc.params[:, [0, 1, 4, 5]].tolist())
|
||||
|
||||
def test_ceiling_hazards_and_category_override(self):
|
||||
ceiling = CruiseCeiling(19.0, ACTIVE)
|
||||
ceiling = CruiseCeiling(18.0, ACTIVE) # 2 m/s over: the halved SLC correction (-1.0) still reaches the eco floor (-0.6)
|
||||
eco, cruise = self.run_planner('eco', ceiling=ceiling)
|
||||
self.assertEqual(cruise['base_brake_floor'], -0.6)
|
||||
self.assertAlmostEqual(eco.a_cruise, -0.6)
|
||||
|
||||
@@ -650,7 +650,7 @@ class ProfileRuntimeTests(unittest.TestCase):
|
||||
strong = LongitudinalPlanner(self.cp, init_v=V_EGO)
|
||||
soft_tuning = ProfileTuning('standard', 1.45, 1, 1, 1, 1, 1, None, 0.75)
|
||||
strong_tuning = ProfileTuning('standard', 1.45, 1, 1, 1, 1, 1, None, 1.8)
|
||||
for _ in range(40):
|
||||
for _ in range(60): # 3 s: SLC braking takes 2 s to ease in to -0.3, then reaches each profile floor
|
||||
sm, _ = messages()
|
||||
sm['carControl'].longActive = True
|
||||
baseline.update(sm, cruise_ceiling=ceiling)
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
"""SLC overshoot braking eases in without weakening lead, model or acceleration responses."""
|
||||
from unittest.mock import patch
|
||||
|
||||
import pytest
|
||||
|
||||
from opendbc.car.honda.interface import CarInterface
|
||||
from opendbc.car.honda.values import CAR
|
||||
from openpilot.selfdrive.controls.lib import longitudinal_planner as planner_module
|
||||
from openpilot.selfdrive.controls.lib.longitudinal_planner import (A_CRUISE_MIN, SLC_BRAKE_ONSET_ACCEL, SLC_BRAKE_ONSET_JERK,
|
||||
LongitudinalPlanner, get_cruise_accel)
|
||||
from openpilot.starpilot.curve_speed.tests.test_planner import Inputs
|
||||
from openpilot.starpilot.longitudinal.cruise_ceiling import CruiseCeiling, CurveCeiling
|
||||
from openpilot.starpilot.longitudinal.tests.test_cruise_ceiling import ACTIVE, V_EGO, messages
|
||||
from openpilot.starpilot.longitudinal.tests.test_cruise_taps import camry
|
||||
|
||||
DT = .05
|
||||
CAP = CruiseCeiling(60. / 3.6, ACTIVE) # below the fixture's 100 km/h SET, with the car 3.3 m/s over it
|
||||
|
||||
|
||||
def test_overshoot_braking_eases_in_then_uses_normal_jerk():
|
||||
cp, accel, trace = camry(), 1.2, []
|
||||
for _ in range(100):
|
||||
previous, accel = accel, get_cruise_accel(False, 10., 12., accel, 0., cp, DT, 0., True, ease_slc_braking=True)
|
||||
trace.append((previous, previous - accel))
|
||||
normal = get_cruise_accel(False, 10., 12., 1.2, 0., cp, DT, 0., True)
|
||||
assert trace[0][1] == pytest.approx(1.2 - normal) # lifting off the throttle is not slowed
|
||||
onset = [step for previous, step in trace if SLC_BRAKE_ONSET_ACCEL < previous <= 0.]
|
||||
assert max(onset) <= SLC_BRAKE_ONSET_JERK * DT + 1e-9
|
||||
assert len(onset) * DT >= abs(SLC_BRAKE_ONSET_ACCEL) / SLC_BRAKE_ONSET_JERK - DT # about 2 s to reach -0.3
|
||||
assert accel == pytest.approx(A_CRUISE_MIN)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('error', (-.2, -.4))
|
||||
def test_overshoot_correction_is_halved(error):
|
||||
assert get_cruise_accel(False, 28. + error, 28., error / 2, 0., camry(), DT, 0., True,
|
||||
ease_slc_braking=True) == pytest.approx(error / 2)
|
||||
|
||||
|
||||
def test_braking_requested_elsewhere_keeps_normal_jerk():
|
||||
args = (False, 20., 25., 0., 0., camry(), DT, 0., True)
|
||||
assert get_cruise_accel(*args, ease_slc_braking=True) == pytest.approx(-SLC_BRAKE_ONSET_JERK * DT)
|
||||
assert get_cruise_accel(*args, a_target_prev=-1., ease_slc_braking=True) == get_cruise_accel(*args, a_target_prev=-1.)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('faster', (False, True))
|
||||
def test_acceleration_is_unchanged(faster):
|
||||
args = (False, 28.4, 28., .1, 0., camry(), DT, 0., True)
|
||||
assert get_cruise_accel(*args, faster_takeoffs=faster, ease_slc_braking=True) == get_cruise_accel(*args, faster_takeoffs=faster)
|
||||
|
||||
|
||||
def planner_easing(*, ceiling=CAP, lead=False, e2e=False):
|
||||
planner = LongitudinalPlanner(CarInterface.get_non_essential_params(CAR.HONDA_CIVIC), init_v=V_EGO)
|
||||
real, seen = planner_module.get_cruise_accel, []
|
||||
|
||||
def observe(*args, **options):
|
||||
seen.append(options['ease_slc_braking'])
|
||||
return real(*args, **options)
|
||||
|
||||
with patch.object(planner_module, 'get_cruise_accel', side_effect=observe):
|
||||
for _ in range(3):
|
||||
planner.update(messages(lead=lead, e2e=e2e)[0], cruise_ceiling=ceiling)
|
||||
return seen, planner
|
||||
|
||||
|
||||
@pytest.mark.parametrize('ceiling,lead,eased', ((CAP, False, True), (CAP, True, False), (None, False, False),
|
||||
(CruiseCeiling(40., ACTIVE), False, False)))
|
||||
def test_planner_eases_only_toward_an_applied_slc_cap_without_a_braking_lead(ceiling, lead, eased):
|
||||
assert planner_easing(ceiling=ceiling, lead=lead)[0] == [eased] * 3
|
||||
|
||||
|
||||
def test_model_braking_still_wins_while_slc_braking_is_eased():
|
||||
seen, planner = planner_easing(e2e=True)
|
||||
assert seen == [True] * 3
|
||||
assert planner.output_a_target < planner.a_cruise
|
||||
|
||||
|
||||
@pytest.mark.parametrize('ceiling', (None, CAP))
|
||||
def test_lower_curve_keeps_normal_braking_with_or_without_slc(ceiling):
|
||||
planner = LongitudinalPlanner(CarInterface.get_non_essential_params(CAR.HONDA_CIVIC), init_v=V_EGO)
|
||||
real, seen = planner_module.get_cruise_accel, []
|
||||
|
||||
def observe(*args, **options):
|
||||
seen.append(options['ease_slc_braking'])
|
||||
return real(*args, **options)
|
||||
|
||||
with patch.object(planner_module, 'get_cruise_accel', side_effect=observe):
|
||||
for frame in range(3):
|
||||
stamp = (frame + 1) * 50_000_000
|
||||
fields, _ = messages()
|
||||
fields['carControl'].longActive = True
|
||||
planner.update(Inputs(fields, stamp), cruise_ceiling=ceiling, curve_ceiling=CurveCeiling(15., stamp))
|
||||
assert seen == [False] * 3
|
||||
assert planner.a_cruise < planner_easing()[1].a_cruise
|
||||
@@ -76,7 +76,8 @@ class TrafficAccelerationPlannerTests(unittest.TestCase):
|
||||
sm['carState'].vCruise = 15.0 * 3.6
|
||||
baseline.update(sm, profile_tuning=target, traffic_mode=True)
|
||||
self.assertEqual(traffic.mpc.solution_status, 0)
|
||||
self.assertLessEqual(traffic.a_cruise, baseline.a_cruise + 1e-8)
|
||||
if force: # cap inactive, so cruise matches SET exactly; an applied cap eases its braking in
|
||||
self.assertLessEqual(traffic.a_cruise, baseline.a_cruise + 1e-8)
|
||||
self.assertEqual(traffic.last_cruise_ceiling_status, 'force_decel' if force else 'applied')
|
||||
self.assertIsNotNone(traffic.last_profile)
|
||||
self.assertAlmostEqual(traffic.last_profile.cruise_brake_magnitude, 0.35)
|
||||
|
||||
@@ -6,7 +6,8 @@ physical-speed coordinates once. Accepting a limit never rewrites SET. Native PC
|
||||
cruise owns its setpoint; non-PCM software cruise and the dedicated Subaru software
|
||||
cruise mode retain their existing owners. Automatic SLC requires system longitudinal
|
||||
control. Lead, curve, stop and actuator safety constraints retain their existing owners.
|
||||
SLC works with either the StarPilot or upstream longitudinal planner.
|
||||
SLC works with either the StarPilot or upstream longitudinal planner. The StarPilot planner
|
||||
eases braking after an overshoot past the cap; the upstream planner keeps its native response.
|
||||
|
||||
## New limits and adoption
|
||||
|
||||
|
||||
@@ -77,7 +77,7 @@ def test_actual_native_planner_responds_before_the_dashboard_updates(drive):
|
||||
current.update(fixture.sm, cruise_ceiling=result.ceiling)
|
||||
legacy.update(fixture.sm, cruise_ceiling=old.ceiling)
|
||||
assert current.mpc.solution_status == legacy.mpc.solution_status == 0
|
||||
assert current.output_a_target < -.01
|
||||
assert current.output_a_target < -1e-3 # braking has begun; eased SLC braking starts small
|
||||
assert abs(legacy.output_a_target) < 1e-5
|
||||
np.testing.assert_array_equal(current.mpc.params, legacy.mpc.params)
|
||||
np.testing.assert_array_equal(current.mpc.x_sol, legacy.mpc.x_sol)
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
from collections.abc import Callable
|
||||
from dataclasses import replace
|
||||
import json
|
||||
import math
|
||||
|
||||
from openpilot.starpilot.saved_document import commit_exact
|
||||
from openpilot.starpilot.saved_source import read_saved
|
||||
@@ -104,7 +105,39 @@ class AppearanceOwner:
|
||||
subtitle="Display preferences; border highlights apply to C4 only.",
|
||||
rows=tuple(rows), parked=parked)
|
||||
|
||||
def developer_snapshot(self) -> FeatureSettingsState:
|
||||
raw, document = self._motion_source()
|
||||
valid = document is not None
|
||||
value = f"{document.get('speedDisplayOffset', 0):g}" if document is not None else "Unavailable"
|
||||
row = FeatureRow("SpeedDisplayOffset", "Speed display adjustment", value, source=raw,
|
||||
step=0.1, minimum=-5., maximum=5., unit="%", default_value="0",
|
||||
available=self.parked() and valid,
|
||||
reason=("0% leaves the display unchanged. Lower if the comma reads too high; raise if it reads too low. " +
|
||||
"Only changes displayed vehicle speed, not cruise speed or vehicle control.") if valid else
|
||||
"Repair the saved driving-screen layout first.")
|
||||
return FeatureSettingsState("developer", "Developer", "Advanced display calibration for every vehicle.",
|
||||
(row,), self.parked())
|
||||
|
||||
def apply(self, request: FeatureSettingsRequest) -> bool:
|
||||
if request.key == "SpeedDisplayOffset":
|
||||
raw, document = self._motion_source()
|
||||
if document is None or request.expected != raw or type(request.value) is not str:
|
||||
return False
|
||||
try:
|
||||
value = float(request.value)
|
||||
except ValueError:
|
||||
return False
|
||||
if not math.isfinite(value) or not -5 <= value <= 5:
|
||||
return False
|
||||
value = round(value, 1)
|
||||
if value:
|
||||
document['speedDisplayOffset'] = value
|
||||
else:
|
||||
document.pop('speedDisplayOffset', None)
|
||||
result = commit_exact(self.params, key=PARAM_KEY, max_bytes=MAX_BYTES,
|
||||
raw=json.dumps(document, separators=(',', ':')).encode(), expected=raw,
|
||||
authorized=self.parked, temp_prefix='.appearance-')
|
||||
return result.committed and result.verified
|
||||
if request.key in ('TurnByTurn:large', 'TurnByTurn:compact'):
|
||||
raw, document = self._motion_source()
|
||||
if document is None or request.expected != raw or request.value not in ('Off', 'On'):
|
||||
|
||||
@@ -528,6 +528,11 @@ def validate_document(value):
|
||||
fields.add('showMaxSpeed')
|
||||
if type(value['showMaxSpeed']) is not bool:
|
||||
raise ValueError('Invalid MAX speed preference')
|
||||
if 'speedDisplayOffset' in value:
|
||||
fields.add('speedDisplayOffset')
|
||||
adjustment = value['speedDisplayOffset']
|
||||
if type(adjustment) not in (int, float) or not math.isfinite(adjustment) or not -5 <= adjustment <= 5:
|
||||
raise ValueError('Invalid speed display adjustment')
|
||||
if set(value) != fields:
|
||||
raise ValueError("Invalid customization fields")
|
||||
palette, layouts = value["palette"], value["layouts"]
|
||||
@@ -734,6 +739,8 @@ def validate_document(value):
|
||||
result['clock24Hour'] = value['clock24Hour']
|
||||
if 'showMaxSpeed' in value:
|
||||
result['showMaxSpeed'] = value['showMaxSpeed']
|
||||
if 'speedDisplayOffset' in value:
|
||||
result['speedDisplayOffset'] = value['speedDisplayOffset']
|
||||
if value['version'] < 10:
|
||||
migrate_large_sign_layout(result['layouts']['large'], PROFILES['large']['bounds'], extra_height=sources_extent(result))
|
||||
if value['version'] < 8:
|
||||
|
||||
@@ -98,9 +98,10 @@ class CurrentSpeedHud:
|
||||
self.fonts = fonts
|
||||
|
||||
def render(self, content: rl.Rectangle, state: OnroadState) -> None:
|
||||
if state.speed_mps is None:
|
||||
speed_mps = state.display_speed_mps
|
||||
if speed_mps is None:
|
||||
return
|
||||
speed = str(round(state.speed_mps * (3.6 if state.metric else 2.2369362921)))
|
||||
speed = str(round(speed_mps * (3.6 if state.metric else 2.2369362921)))
|
||||
dx, dy = offset(state.customization, "large", "current_speed")
|
||||
rect = rl.Rectangle(content.x + 610 + dx, content.y + dy, 580, 300)
|
||||
number_top, _ = self.fonts.vertical_ink(speed, FontRole.SPEED, 176)
|
||||
|
||||
@@ -246,8 +246,16 @@ class OnroadState:
|
||||
ford_rear_fog_on: bool = False
|
||||
ford_rear_fog_source_ns: int = 0
|
||||
slc_offset_schedule: OffsetSchedule | None = None
|
||||
speed_display_offset_percent: float = 0.0
|
||||
|
||||
@property
|
||||
def display_speed_mps(self) -> float | None:
|
||||
return None if self.speed_mps is None else self.speed_mps * (1 + self.speed_display_offset_percent / 100)
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
if (type(self.speed_display_offset_percent) not in (int, float) or
|
||||
not math.isfinite(self.speed_display_offset_percent) or not -5 <= self.speed_display_offset_percent <= 5):
|
||||
raise ValueError("Invalid speed display adjustment")
|
||||
if self.speed_mps is not None and (not math.isfinite(self.speed_mps) or self.speed_mps < 0):
|
||||
raise ValueError("Speed must be finite and nonnegative")
|
||||
if self.cruise_kph is not None and (not math.isfinite(self.cruise_kph) or self.cruise_kph < 0):
|
||||
|
||||
@@ -729,6 +729,7 @@ class RuntimeSnapshotAdapter:
|
||||
onroad = OnroadState(weather_location=weather_location, developer_metrics=developer_metrics, stop_sign_observed_ns=stop_observed_ns,
|
||||
engaged=display_lat_active or display_long_active or longitudinal_overridden, camera_available=started,
|
||||
speed_mps=raw_speed, cruise_kph=cruise, speed_limit=observation,
|
||||
speed_display_offset_percent=self._customization_value.get("speedDisplayOffset", 0.),
|
||||
appearance=self._appearance_value, customization=self._customization_value,
|
||||
alert=alert, metric=bool(ui.is_metric), slc_offset_schedule=self._slc_offset_schedule,
|
||||
experimental_available=bool(ui.has_longitudinal_control),
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
"""Saved screen gestures for a detected Tesla Vehicle CAN connection."""
|
||||
"""Saved cooperative steering selection for modern Tesla vehicles."""
|
||||
from openpilot.starpilot.saved_document import commit_exact
|
||||
from openpilot.starpilot.saved_source import read_saved
|
||||
from openpilot.starpilot.ui.feature_settings_state import FeatureRow
|
||||
@@ -6,7 +6,7 @@ from openpilot.starpilot.ui.feature_settings_state import FeatureRow
|
||||
|
||||
KEYS = frozenset(('TeslaCoopSteering',))
|
||||
ROWS = (('TeslaCoopSteering', 'Tesla Co-op Steering',
|
||||
'Model 3 only. Light steering input adjusts the assisted steering angle within its limits. Applies after the next startup.'),)
|
||||
'Model 3 and Model Y. Light steering input adjusts the assisted steering angle within its limits. Applies after the next startup.'),)
|
||||
|
||||
|
||||
class TeslaCoopFeature:
|
||||
|
||||
+1
-1
@@ -1 +1 @@
|
||||
{"protected_inventory_sha256": "6548e067cdc2b559eef4a1eca1cc9e3c9fd05a378b133fb3d16b6a2fbde4bbae", "schema_version": 1}
|
||||
{"protected_inventory_sha256": "5804469748ae5eec238bfa10f9d75742ad822161fd5be0605f7a349df06f6522", "schema_version": 1}
|
||||
|
||||
@@ -280,6 +280,9 @@ RELEASE_TARGETS = (
|
||||
"openpilot/starpilot/car/subaru/tests/test_stock_aol_callers.py::test_actual_stopped_feedback_gap_retains_only_armed_intent",
|
||||
"openpilot/starpilot/car/subaru/tests/test_stock_aol_callers.py::test_actual_stopped_source_gap_retains_intent_without_renewing_output",
|
||||
"openpilot/starpilot/car/subaru/tests/test_stock_aol_callers.py::test_actual_paused_subaru_restriction_keeps_armed_intent",
|
||||
"openpilot/starpilot/car/subaru/tests/test_stock_aol_callers.py::test_actual_subaru_eps_clear_during_blinker_pause_keeps_armed_intent",
|
||||
"openpilot/starpilot/car/subaru/tests/test_stock_aol_callers.py::test_actual_subaru_family_eps_recovery_join",
|
||||
"openpilot/starpilot/car/subaru/tests/test_stock_aol_callers.py::test_actual_subaru_paused_restriction_event_join",
|
||||
"openpilot/starpilot/car/subaru/tests/test_stock_aol_callers.py::test_actual_repeat_main_with_brake_and_signal_pause",
|
||||
"openpilot/starpilot/aol/tests/test_subaru_temporary_eps.py",
|
||||
"openpilot/starpilot/car/subaru/tests/test_paused_intent.py",
|
||||
|
||||
Reference in New Issue
Block a user