diff --git a/.github/workflows/docs.yaml b/.github/workflows/docs.yaml index 2a5aac38eb..e5075f530c 100644 --- a/.github/workflows/docs.yaml +++ b/.github/workflows/docs.yaml @@ -11,6 +11,7 @@ on: - testing - dev pull_request: + types: [opened, synchronize, reopened, edited] workflow_dispatch: workflow_call: inputs: diff --git a/.github/workflows/flm-offroad.yaml b/.github/workflows/flm-offroad.yaml index 87c6ed223c..55374156ea 100644 --- a/.github/workflows/flm-offroad.yaml +++ b/.github/workflows/flm-offroad.yaml @@ -24,6 +24,9 @@ on: - '.github/workflows/flm-offroad.yaml' - 'pyproject.toml' - 'uv.lock' + pull_request: + branches: [stable] + types: [opened, synchronize, reopened, edited] workflow_dispatch: inputs: source_sha: diff --git a/.github/workflows/galaxy-phone-bridge.yaml b/.github/workflows/galaxy-phone-bridge.yaml index cfbbcaa4d8..134811a74c 100644 --- a/.github/workflows/galaxy-phone-bridge.yaml +++ b/.github/workflows/galaxy-phone-bridge.yaml @@ -7,10 +7,12 @@ on: - 'openpilot/starpilot/galaxy_bluetooth/**' - '.github/workflows/galaxy-phone-bridge.yaml' pull_request: + branches-ignore: [stable] paths: - 'openpilot/starpilot/galaxy_bluetooth/**' - '.github/workflows/galaxy-phone-bridge.yaml' workflow_dispatch: + workflow_call: permissions: contents: read diff --git a/.github/workflows/safety.yaml b/.github/workflows/safety.yaml index f6988c1222..3c6a87d555 100644 --- a/.github/workflows/safety.yaml +++ b/.github/workflows/safety.yaml @@ -4,6 +4,7 @@ on: push: branches: [master, Domathon, Dom, StarPilot, stable, testing, dev] pull_request: + types: [opened, synchronize, reopened, edited] workflow_dispatch: permissions: diff --git a/.github/workflows/tests.yaml b/.github/workflows/tests.yaml index 9529871b79..20d4563e4c 100644 --- a/.github/workflows/tests.yaml +++ b/.github/workflows/tests.yaml @@ -11,6 +11,7 @@ on: - testing - dev pull_request: + types: [opened, synchronize, reopened, edited] workflow_dispatch: workflow_call: inputs: @@ -31,6 +32,12 @@ env: PYTHONPATH: ${{ github.workspace }} jobs: + stable_pr_phone_bridge: + if: github.event_name == 'pull_request' && github.base_ref == 'stable' + permissions: + contents: read + uses: ./.github/workflows/galaxy-phone-bridge.yaml + source_integrity: name: source integrity runs-on: ubuntu-24.04 diff --git a/launch_env.sh b/launch_env.sh index 9b9378161e..fc8fbe622c 100755 --- a/launch_env.sh +++ b/launch_env.sh @@ -26,7 +26,7 @@ fi export QCOM_PRIORITY=12 if [ -z "$AGNOS_VERSION" ]; then - export AGNOS_VERSION="20.5.3" + export AGNOS_VERSION="20.5.5" fi # Legacy stagers defer flashing; agnos_init still requires AGNOS_VERSION before manager startup. diff --git a/opendbc_repo/opendbc/car/car_helpers.py b/opendbc_repo/opendbc/car/car_helpers.py index d89cd0d031..3975f202d4 100644 --- a/opendbc_repo/opendbc/car/car_helpers.py +++ b/opendbc_repo/opendbc/car/car_helpers.py @@ -15,7 +15,8 @@ from opendbc.car.ford.discovery import (normal_bus0_selection as ford_normal_bus normal_bus0_queries as ford_normal_bus0_queries, normal_bus_query_brand) from opendbc.car.volvo.discovery import normal_bus_topology as volvo_normal_bus_topology, v60_bus_topology as volvo_v60_bus_topology from opendbc.car.hyundai.discovery import normal_bus_topology -from opendbc.car.honda.discovery import normal_bus_topology as honda_normal_bus_topology +from opendbc.car.honda.discovery import nidec_bus0_topology, normal_bus_topology as honda_normal_bus_topology +from opendbc.car.honda.values import CAR as HONDA, HondaFlags from opendbc.car.chrysler.discovery import normal_bus_topology as chrysler_normal_bus_topology from opendbc.car.tesla.discovery import normal_bus0_topology as tesla_normal_bus0_topology from opendbc.car.values import BRANDS @@ -150,6 +151,7 @@ def fingerprint(can_recv: CanRecvCallable, can_send: CanSendCallable, set_obd_mu volvo_v60 = volvo_v60_bus_topology(fp) return volvo_normal_bus_topology(fp) or volvo_v60 + full_scan = False if known_gm_bus0: # An explicit registered GM selection already identifies the query family. # Current GM requests use normal bus 0. Keep live VIN/FW collection and @@ -189,19 +191,30 @@ def fingerprint(can_recv: CanRecvCallable, can_send: CanSendCallable, set_obd_mu volvo_probe=volvo_probe, tesla_probe=tesla_normal_bus0_topology if _tesla_fw_uses_normal_bus0() else None) or ('honda' if honda_normal_bus_topology(normal_bus_packets) else None) or + ('honda_nidec' if nidec_bus0_topology(normal_bus_packets) else None) or ('chrysler' if chrysler_normal_bus_topology(normal_bus_packets) else None)) is not None: set_obd_multiplexing(False) warmup_remaining = 0.1 - (time.monotonic() - start_time) if warmup_remaining > 0: time.sleep(warmup_remaining) - vin_buses = (0,) if normal_brand in ('ford', 'gm', 'volvo', 'tesla', 'chrysler') else (0, 1) + vin_buses = (0,) if normal_brand in ('ford', 'gm', 'volvo', 'tesla', 'chrysler', 'honda_nidec') else (0, 1) vin_rx_addr, vin_rx_bus, vin = get_vin(can_recv, can_send, vin_buses) - # Polestar is identified by live CAN alone; the V60 by its engine FW, which answers on bus 0 - car_fw = [] if normal_brand == 'volvo' and not volvo_v60 else get_fw_versions(can_recv, can_send, set_obd_multiplexing, - query_brand=normal_brand, normal_bus_only=True) + if normal_brand == 'honda_nidec': + car_fw = get_fw_versions(can_recv, can_send, set_obd_multiplexing, query_brand='honda', query_bus=0) + exact, matches = match_fw_to_car(car_fw, vin) + full_scan = not (exact and len(matches) == 1 and any( + candidate in HONDA and HONDA(candidate).config.flags & HondaFlags.NIDEC for candidate in matches)) + elif normal_brand == 'volvo' and not volvo_v60: + # Polestar is identified by live CAN alone; the V60 by its engine FW, which answers on bus 0 + car_fw = [] + else: + car_fw = get_fw_versions(can_recv, can_send, set_obd_multiplexing, + query_brand=normal_brand, normal_bus_only=True) ecu_rx_addrs = {(fw.responseAddress, fw.subAddress or None, fw.bus) for fw in car_fw if fw.responseAddress > 0} else: + full_scan = True + if full_scan: # enable OBD multiplexing for VIN query # NOTE: this takes ~0.1s and is relied on to allow sendcan subscriber to connect in time set_obd_multiplexing(True) diff --git a/opendbc_repo/opendbc/car/fw_versions.py b/opendbc_repo/opendbc/car/fw_versions.py index 8e0456a821..3a42a846b2 100644 --- a/opendbc_repo/opendbc/car/fw_versions.py +++ b/opendbc_repo/opendbc/car/fw_versions.py @@ -275,7 +275,7 @@ def get_fw_versions_ordered(can_recv: CanRecvCallable, can_send: CanSendCallable def get_fw_versions(can_recv: CanRecvCallable, can_send: CanSendCallable, set_obd_multiplexing: ObdCallback, query_brand: str | None = None, extra: OfflineFwVersions | None = None, timeout: float = 0.1, progress: bool = False, - *, normal_bus_only: bool = False) -> list[CarParams.CarFw]: + *, normal_bus_only: bool = False, query_bus: int | None = None) -> list[CarParams.CarFw]: versions = VERSIONS.copy() if query_brand is not None: @@ -309,6 +309,7 @@ def get_fw_versions(can_recv: CanRecvCallable, can_send: CanSendCallable, set_ob # Get versions and build capnp list to put into CarParams car_fw = [] requests = [(brand, config, r) for brand, config, r in REQUESTS if is_brand(brand, query_brand) and + (query_bus is None or r.bus == query_bus) and not (normal_bus_only and r.bus % 4 == 1 and r.obd_multiplexing)] for addr_group in tqdm(addrs, disable=not progress): # split by subaddr, if any for addr_chunk in chunks(addr_group): diff --git a/opendbc_repo/opendbc/car/honda/discovery.py b/opendbc_repo/opendbc/car/honda/discovery.py index a5b797cebd..fb767d610a 100644 --- a/opendbc_repo/opendbc/car/honda/discovery.py +++ b/opendbc_repo/opendbc/car/honda/discovery.py @@ -7,14 +7,26 @@ NORMAL_BUS_LAYOUT = {(1, 0x158): 8, (1, 0x17C): 8, (1, 0x18F): 7, (1, 0x296): 4, (2, 0xE4): 5, (2, 0x400): 4} -def normal_bus_topology(packets): +# Nidec uses two SCM layouts and two EPS status lengths on normal bus 0. +NIDEC_BUS0_COMMON = {(0, 0x158): 8, (0, 0x17C): 8} +NIDEC_BUS0_LAYOUTS = ( + *({**NIDEC_BUS0_COMMON, (0, 0x18F): eps_length, (0, 0x1A6): 8, (0, 0x156): 6} for eps_length in (6, 7)), + {**NIDEC_BUS0_COMMON, (0, 0x18F): 7, (0, 0x296): 4, (0, 0x326): 8}, +) + + +def normal_bus_topology(packets, *, layout=NORMAL_BUS_LAYOUT): observed = set() for packet in packets: for frame in packet: key = (frame.src, frame.address) - if key in NORMAL_BUS_LAYOUT: - if (len(frame.dat) != NORMAL_BUS_LAYOUT[key] or + if key in layout: + if (len(frame.dat) != layout[key] or honda_checksum(frame.address, None, frame.dat) != frame.dat[-1] & 0xF): return False observed.add(key) - return observed == NORMAL_BUS_LAYOUT.keys() + return observed == layout.keys() + + +def nidec_bus0_topology(packets): + return any(normal_bus_topology(packets, layout=layout) for layout in NIDEC_BUS0_LAYOUTS) diff --git a/opendbc_repo/opendbc/car/hyundai/discovery.py b/opendbc_repo/opendbc/car/hyundai/discovery.py index 753d23fc48..27db038bd5 100644 --- a/opendbc_repo/opendbc/car/hyundai/discovery.py +++ b/opendbc_repo/opendbc/car/hyundai/discovery.py @@ -22,6 +22,11 @@ HDA2_NORMAL_BUS_LAYOUT = {(2, 0x50): 16, (2, 0x2A4): 24, (1, 0x35): 32, (1, 0xEA (1, 0xA0): 24, (1, 0x1A0): 32, (1, 0x1CF): 8, (1, 0x130): 16} +MIXED_CAN_NORMAL_BUS_LAYOUT = {(2, 0x50): 16, (2, 0x2A4): 24, (0, 0x251): 16, + (1, 0x251): 8, (1, 0x386): 8, (1, 0x394): 8, + (1, 0x4F1): 4, (1, 0x420): 8, (1, 0x421): 8} + + QUIET_CAMERA_NORMAL_BUS_LAYOUT = {(0, 0xEA): 24, (0, 0xA0): 24, (0, 0x1A0): 32, (0, 0x60): 32, (0, 0x35): 32, (0, 0x1CF): 8, (0, 0x130): 16, **{(1, address): 32 for address in range(0x210, 0x220)}} @@ -59,8 +64,9 @@ def normal_bus_topology(can_recv, *, clock=time.monotonic): hda2_invalid = False hda1_observed = {} hda1_invalid = False - variants_observed = [{} for _ in CANFD_VARIANT_LAYOUTS] - variants_invalid = [False for _ in CANFD_VARIANT_LAYOUTS] + alternate_layouts = (*CANFD_VARIANT_LAYOUTS, MIXED_CAN_NORMAL_BUS_LAYOUT) + variants_observed = [{} for _ in alternate_layouts] + variants_invalid = [False for _ in alternate_layouts] for _ in range(24): if clock() >= deadline: break @@ -76,7 +82,7 @@ def normal_bus_topology(can_recv, *, clock=time.monotonic): return False original_invalid = True received[key] = length - for index, layout in enumerate(CANFD_VARIANT_LAYOUTS): + for index, layout in enumerate(alternate_layouts): if key in layout: if len(frame.dat) != layout[key]: variants_invalid[index] = True @@ -98,6 +104,6 @@ def normal_bus_topology(can_recv, *, clock=time.monotonic): not hda1_invalid and hda1_observed == HDA1_NORMAL_BUS_LAYOUT)): return True if any(not invalid and received == layout and (not original_invalid or (2, 0x50) in layout) - for layout, received, invalid in zip(CANFD_VARIANT_LAYOUTS, variants_observed, variants_invalid, strict=True)): + for layout, received, invalid in zip(alternate_layouts, variants_observed, variants_invalid, strict=True)): return True return False diff --git a/opendbc_repo/opendbc/car/hyundai/tests/test_mixed_can_normal_discovery.py b/opendbc_repo/opendbc/car/hyundai/tests/test_mixed_can_normal_discovery.py new file mode 100644 index 0000000000..8cae72e3c4 --- /dev/null +++ b/opendbc_repo/opendbc/car/hyundai/tests/test_mixed_can_normal_discovery.py @@ -0,0 +1,52 @@ +from unittest.mock import patch + +import pytest + +from opendbc.car.can_definitions import CanData +from opendbc.car.car_helpers import fingerprint +from opendbc.car.hyundai.discovery import normal_bus_topology +from opendbc.car.vin import VIN_UNKNOWN + + +def mixed_can_frames(): + return [CanData(addr, bytes(length), bus) for bus, addr, length in ( + (0, 0x251, 16), (2, 0x50, 16), (2, 0x2A4, 24), + (1, 0x251, 8), (1, 0x386, 8), (1, 0x394, 8), (1, 0x4F1, 4), (1, 0x420, 8), (1, 0x421, 8), + )] + + +@pytest.mark.parametrize('index', range(9)) +@pytest.mark.parametrize('defect', ['missing', 'length', 'bus', 'echo', 'contradiction']) +def test_mixed_can_probe_requires_consistent_physical_sources(index, defect): + frames = mixed_can_frames() + original = frames.pop(index) + if defect in ('length', 'contradiction'): + frames.append(CanData(original.address, original.dat[:-1], original.src)) + if defect == 'contradiction': + frames.append(original) + elif defect in ('bus', 'echo'): + frames.append(CanData(original.address, original.dat, original.src + (128 if defect == 'echo' else 1))) + assert not normal_bus_topology(lambda **kwargs: [frames]) + + +def test_mixed_can_probe_spans_can_reads(): + frames = iter([frame] for frame in mixed_can_frames()) + assert normal_bus_topology(lambda **kwargs: [next(frames, [])], clock=lambda: 0.) + + +def test_mixed_can_fingerprint_keeps_fresh_queries_on_normal_wiring(): + switches = [] + with patch('opendbc.car.car_helpers.get_vin', return_value=(-1, -1, VIN_UNKNOWN)) as vin, \ + patch('opendbc.car.car_helpers.get_fw_versions', return_value=[]) as query, \ + patch('opendbc.car.car_helpers.get_present_ecus', return_value=set()) as present, \ + patch('opendbc.car.car_helpers.get_fw_versions_ordered', return_value=[]) as generic, \ + patch('opendbc.car.car_helpers.can_fingerprint', return_value=(None, {})): + result = fingerprint(lambda **kwargs: [mixed_can_frames()], lambda packets: None, switches.append, None) + assert result[0] is None + assert switches and not any(switches) + vin.assert_called_once() + assert vin.call_args.args[2] == (0, 1) + query.assert_called_once() + assert query.call_args.kwargs == {'query_brand': 'hyundai', 'normal_bus_only': True} + present.assert_not_called() + generic.assert_not_called() diff --git a/opendbc_repo/opendbc/car/mazda/interface.py b/opendbc_repo/opendbc/car/mazda/interface.py index 259e3e7af4..7f279c3b01 100755 --- a/opendbc_repo/opendbc/car/mazda/interface.py +++ b/opendbc_repo/opendbc/car/mazda/interface.py @@ -18,7 +18,7 @@ class CarInterface(CarInterfaceBase): ret.radarUnavailable = True ret.deprecated.enableBsm = True - ret.dashcamOnly = candidate not in (CAR.MAZDA_CX5_2022, CAR.MAZDA_CX9_2021) + ret.dashcamOnly = candidate not in (CAR.MAZDA_CX5, CAR.MAZDA_CX5_2022, CAR.MAZDA_CX9_2021) ret.steerActuatorDelay = 0.1 ret.steerLimitTimer = 0.8 diff --git a/opendbc_repo/opendbc/car/mazda/stock_aol.py b/opendbc_repo/opendbc/car/mazda/stock_aol.py index 5932b2fc11..fa6088322c 100644 --- a/opendbc_repo/opendbc/car/mazda/stock_aol.py +++ b/opendbc_repo/opendbc/car/mazda/stock_aol.py @@ -1,7 +1,7 @@ from opendbc.car import structs from opendbc.car.mazda.values import CAR, MazdaFlags -CARS = frozenset((CAR.MAZDA_CX5_2022, CAR.MAZDA_CX9_2021)) +CARS = frozenset((CAR.MAZDA_CX5, CAR.MAZDA_CX5_2022, CAR.MAZDA_CX9_2021)) def qualified(cp, *, marked_only=False): diff --git a/opendbc_repo/opendbc/car/mazda/tests/test_dashboard_stop_sign.py b/opendbc_repo/opendbc/car/mazda/tests/test_dashboard_stop_sign.py index f417a70a4e..81cd65aa9e 100644 --- a/opendbc_repo/opendbc/car/mazda/tests/test_dashboard_stop_sign.py +++ b/opendbc_repo/opendbc/car/mazda/tests/test_dashboard_stop_sign.py @@ -8,7 +8,7 @@ from opendbc.car.mazda.values import CAR, DBC from opendbc.car.mazda.tests.test_stock_startup import complete_frames, exercise_startup from openpilot.starpilot.car.mazda import dashboard -SUPPORTED = (CAR.MAZDA_CX5_2022, CAR.MAZDA_CX9_2021) +SUPPORTED = (CAR.MAZDA_CX5, CAR.MAZDA_CX5_2022, CAR.MAZDA_CX9_2021) @pytest.mark.parametrize('identity', list(CAR)) diff --git a/opendbc_repo/opendbc/car/mazda/tests/test_native_engagement_callers.py b/opendbc_repo/opendbc/car/mazda/tests/test_native_engagement_callers.py index 1d71ec4419..20f9db687a 100644 --- a/opendbc_repo/opendbc/car/mazda/tests/test_native_engagement_callers.py +++ b/opendbc_repo/opendbc/car/mazda/tests/test_native_engagement_callers.py @@ -14,17 +14,17 @@ from opendbc.car.mazda.values import CAR, DBC from opendbc.car.mazda.tests.test_stock_startup import complete_frames, exercise_startup -@pytest.mark.parametrize('identity', (CAR.MAZDA_CX5_2022, CAR.MAZDA_CX9_2021)) +@pytest.mark.parametrize('identity', (CAR.MAZDA_CX5, CAR.MAZDA_CX5_2022, CAR.MAZDA_CX9_2021)) def test_ordinary_engagement_brake_actual_family_callers(identity, monkeypatch): _exercise_actual_family_callers(identity, monkeypatch) -@pytest.mark.parametrize('identity', (CAR.MAZDA_CX5_2022, CAR.MAZDA_CX9_2021)) +@pytest.mark.parametrize('identity', (CAR.MAZDA_CX5, CAR.MAZDA_CX5_2022, CAR.MAZDA_CX9_2021)) def test_unassigned_cancel_retains_lateral_main_off_revokes_actual_callers(identity, monkeypatch): _exercise_actual_family_callers(identity, monkeypatch, scenario='cancel', cancel_action=0) -@pytest.mark.parametrize('identity', (CAR.MAZDA_CX5_2022, CAR.MAZDA_CX9_2021)) +@pytest.mark.parametrize('identity', (CAR.MAZDA_CX5, CAR.MAZDA_CX5_2022, CAR.MAZDA_CX9_2021)) def test_longitudinal_cancel_assignment_keeps_lateral_actual_callers(identity, monkeypatch): _exercise_actual_family_callers(identity, monkeypatch, scenario='long_cancel', cancel_action=4) @@ -59,29 +59,29 @@ extern "C" bool mazda_test_armed(const unsigned char *data, size_t size, uint64_ yield armed -@pytest.mark.parametrize('identity', (CAR.MAZDA_CX5_2022, CAR.MAZDA_CX9_2021)) +@pytest.mark.parametrize('identity', (CAR.MAZDA_CX5, CAR.MAZDA_CX5_2022, CAR.MAZDA_CX9_2021)) def test_reverse_return_retains_lateral_actual_callers(identity, monkeypatch, armed_intent_decoder): _exercise_actual_family_callers(identity, monkeypatch, scenario='reverse', armed_intent=armed_intent_decoder) -@pytest.mark.parametrize('identity', (CAR.MAZDA_CX5_2022, CAR.MAZDA_CX9_2021)) +@pytest.mark.parametrize('identity', (CAR.MAZDA_CX5, CAR.MAZDA_CX5_2022, CAR.MAZDA_CX9_2021)) def test_standstill_return_retains_lateral_actual_callers(identity, monkeypatch, armed_intent_decoder): _exercise_actual_family_callers(identity, monkeypatch, scenario='standstill', armed_intent=armed_intent_decoder) -@pytest.mark.parametrize('identity', (CAR.MAZDA_CX5_2022, CAR.MAZDA_CX9_2021)) +@pytest.mark.parametrize('identity', (CAR.MAZDA_CX5, CAR.MAZDA_CX5_2022, CAR.MAZDA_CX9_2021)) def test_permanent_fault_while_stopped_disarms_actual_callers(identity, monkeypatch, armed_intent_decoder): _exercise_actual_family_callers(identity, monkeypatch, scenario='stop_fault', armed_intent=armed_intent_decoder) -@pytest.mark.parametrize('identity', (CAR.MAZDA_CX5_2022, CAR.MAZDA_CX9_2021)) +@pytest.mark.parametrize('identity', (CAR.MAZDA_CX5, CAR.MAZDA_CX5_2022, CAR.MAZDA_CX9_2021)) @pytest.mark.parametrize('cancel_action', (3, 9)) def test_mapped_cancel_pause_and_toggle_actual_callers(identity, cancel_action, monkeypatch, armed_intent_decoder): _exercise_actual_family_callers(identity, monkeypatch, scenario='mapped_cancel', cancel_action=cancel_action, armed_intent=armed_intent_decoder) -@pytest.mark.parametrize('identity', (CAR.MAZDA_CX5_2022, CAR.MAZDA_CX9_2021)) +@pytest.mark.parametrize('identity', (CAR.MAZDA_CX5, CAR.MAZDA_CX5_2022, CAR.MAZDA_CX9_2021)) @pytest.mark.parametrize('lateral_only', (False, True)) def test_eps_recovery_actual_callers(identity, lateral_only, monkeypatch, armed_intent_decoder): _exercise_actual_family_callers(identity, monkeypatch, scenario='temporary', lateral_only=lateral_only, @@ -489,23 +489,23 @@ def _exercise_actual_family_callers(identity, monkeypatch, *, scenario='brake', mapping=(0, 0) if scenario in ('startup', 'startup_stopped') else (9, 9)) -@pytest.mark.parametrize('identity', (CAR.MAZDA_CX5_2022, CAR.MAZDA_CX9_2021)) +@pytest.mark.parametrize('identity', (CAR.MAZDA_CX5, CAR.MAZDA_CX5_2022, CAR.MAZDA_CX9_2021)) def test_main_already_on_startup_actual_callers(identity, monkeypatch, armed_intent_decoder): _exercise_actual_family_callers(identity, monkeypatch, scenario='startup', cancel_action=9, armed_intent=armed_intent_decoder) -@pytest.mark.parametrize('identity', (CAR.MAZDA_CX5_2022, CAR.MAZDA_CX9_2021)) +@pytest.mark.parametrize('identity', (CAR.MAZDA_CX5, CAR.MAZDA_CX5_2022, CAR.MAZDA_CX9_2021)) def test_main_on_startup_respects_button_managed_aol(identity, monkeypatch, armed_intent_decoder): _exercise_actual_family_callers(identity, monkeypatch, scenario='startup_managed', armed_intent=armed_intent_decoder) -@pytest.mark.parametrize('identity', (CAR.MAZDA_CX5_2022, CAR.MAZDA_CX9_2021)) +@pytest.mark.parametrize('identity', (CAR.MAZDA_CX5, CAR.MAZDA_CX5_2022, CAR.MAZDA_CX9_2021)) def test_main_on_startup_stopped_then_drive_actual_callers(identity, monkeypatch, armed_intent_decoder): _exercise_actual_family_callers(identity, monkeypatch, scenario='startup_stopped', cancel_action=9, armed_intent=armed_intent_decoder) -@pytest.mark.parametrize('identity', (CAR.MAZDA_CX5_2022, CAR.MAZDA_CX9_2021)) +@pytest.mark.parametrize('identity', (CAR.MAZDA_CX5, CAR.MAZDA_CX5_2022, CAR.MAZDA_CX9_2021)) def test_main_on_startup_disabled_aol_actual_card_controls_native(identity, monkeypatch): from openpilot.cereal import messaging from openpilot.selfdrive.car import card as card_module @@ -566,19 +566,19 @@ def test_main_on_startup_disabled_aol_actual_card_controls_native(identity, monk exercise_startup(identity, False, False, False, monkeypatch, probe=probe) -@pytest.mark.parametrize('identity', (CAR.MAZDA_CX5_2022, CAR.MAZDA_CX9_2021)) +@pytest.mark.parametrize('identity', (CAR.MAZDA_CX5, CAR.MAZDA_CX5_2022, CAR.MAZDA_CX9_2021)) @pytest.mark.parametrize('warning', ('calibrationInvalid', 'lowMemory', 'processNotRunning', 'radarTempUnavailable')) def test_ordinary_warning_retains_intent_actual_callers(identity, warning, monkeypatch, armed_intent_decoder): _exercise_actual_family_callers(identity, monkeypatch, scenario='warning', warning=warning, armed_intent=armed_intent_decoder) -@pytest.mark.parametrize('identity', (CAR.MAZDA_CX5_2022, CAR.MAZDA_CX9_2021)) +@pytest.mark.parametrize('identity', (CAR.MAZDA_CX5, CAR.MAZDA_CX5_2022, CAR.MAZDA_CX9_2021)) @pytest.mark.parametrize('scenario', ('mapped_cancel', 'temporary')) def test_unbelted_lateral_pause_recovery_actual_callers(identity, scenario, monkeypatch, armed_intent_decoder): _exercise_actual_family_callers(identity, monkeypatch, scenario=scenario, cancel_action=3, armed_intent=armed_intent_decoder, unbelted=True) -@pytest.mark.parametrize('identity', (CAR.MAZDA_CX5_2022, CAR.MAZDA_CX9_2021)) +@pytest.mark.parametrize('identity', (CAR.MAZDA_CX5, CAR.MAZDA_CX5_2022, CAR.MAZDA_CX9_2021)) @pytest.mark.parametrize('warning', ('calibrationInvalid', 'lowMemory', 'processNotRunning', 'radarTempUnavailable')) def test_active_ordinary_warning_retains_intent_actual_callers(identity, warning, monkeypatch, armed_intent_decoder): _exercise_actual_family_callers(identity, monkeypatch, scenario='warning_active', warning=warning, armed_intent=armed_intent_decoder) diff --git a/opendbc_repo/opendbc/car/mazda/tests/test_stock_cancel_events.py b/opendbc_repo/opendbc/car/mazda/tests/test_stock_cancel_events.py index e9faaa2c43..b6fb2b1efd 100644 --- a/opendbc_repo/opendbc/car/mazda/tests/test_stock_cancel_events.py +++ b/opendbc_repo/opendbc/car/mazda/tests/test_stock_cancel_events.py @@ -8,7 +8,7 @@ from opendbc.car.mazda.values import CAR class TestStockCancelEvents(unittest.TestCase): def test_actual_parser_cancel_is_scoped_to_marked_profile(self): - for identity in (CAR.MAZDA_CX5_2022, CAR.MAZDA_CX9_2021): + for identity in (CAR.MAZDA_CX5, CAR.MAZDA_CX5_2022, CAR.MAZDA_CX9_2021): for experience in (0, 32): with self.subTest(identity=identity, experience=experience): cp = CarInterface.get_params(identity, gen_empty_fingerprint(), [], False, False, False) diff --git a/opendbc_repo/opendbc/car/mazda/tests/test_stock_startup.py b/opendbc_repo/opendbc/car/mazda/tests/test_stock_startup.py index a68b2d9ce5..5f9681a755 100644 --- a/opendbc_repo/opendbc/car/mazda/tests/test_stock_startup.py +++ b/opendbc_repo/opendbc/car/mazda/tests/test_stock_startup.py @@ -9,7 +9,7 @@ from opendbc.car.mazda.interface import CarInterface from opendbc.car.mazda.values import CAR, DBC -CARS = (CAR.MAZDA_CX5_2022, CAR.MAZDA_CX9_2021) +CARS = (CAR.MAZDA_CX5, CAR.MAZDA_CX5_2022, CAR.MAZDA_CX9_2021) def exercise_startup(identity, alpha, release, aol, monkeypatch, mapping=(0, 0), probe=None, cancel_action=3): @@ -143,7 +143,7 @@ def test_saved_button_mappings_reach_actual_card_owner(identity, mapping, monkey exercise_startup(identity, False, False, True, monkeypatch, mapping=mapping) -@pytest.mark.parametrize("identity", (CAR.MAZDA_CX5, CAR.MAZDA_CX9, CAR.MAZDA_3, CAR.MAZDA_6)) +@pytest.mark.parametrize("identity", (CAR.MAZDA_CX9, CAR.MAZDA_3, CAR.MAZDA_6)) def test_unchanged_dashcam_configuration_denies_independent_owner(identity): from opendbc.car.mazda.stock_aol import qualified from openpilot.starpilot.car.mazda.aol import policy_for diff --git a/opendbc_repo/opendbc/car/subaru/avh.py b/opendbc_repo/opendbc/car/subaru/avh.py index f102d2ea7c..9e897b761a 100644 --- a/opendbc_repo/opendbc/car/subaru/avh.py +++ b/opendbc_repo/opendbc/car/subaru/avh.py @@ -10,7 +10,7 @@ def checksum(address, data): def avh_request(template, step): - if len(template) != 8 or checksum(AVH_REQUEST, template) != template[0] or template[2] & 3 or step not in (1, 2): + if len(template) != 8 or checksum(AVH_REQUEST, template) != template[0] or template[2] & 3 or step not in (1, 2, 3, 4): raise ValueError("Invalid AVH template or counter step") data = bytearray(template) data[1] = (data[1] & 0xF0) | ((data[1] + step) & 0xF) @@ -27,6 +27,8 @@ class AvhStartup: self.last_time = None self.stable_since = None self.frames = {} + self.avh_req_gap = None + self.avh_req_same_payload = False self.done = False self.followup = None @@ -85,6 +87,9 @@ class AvhStartup: # checks their full counter stream; require consecutive head-unit frames here. sequential = bool(previous and (address not in (AVH_REQUEST, AVH_STATUS) or (data[1] & 15) == ((previous[1][1] + 1) & 15))) + if address == AVH_REQUEST and previous is not None and timestamp > previous[0]: + self.avh_req_gap = timestamp - previous[0] + self.avh_req_same_payload = data[2:] == previous[1][2:] self.frames[address] = (timestamp, data, sequential) fresh = all(a in self.frames and self.frames[a][2] and @@ -104,20 +109,25 @@ class AvhStartup: if self.stable_since is None: self.stable_since = now if self.followup is not None: - sent, timestamp, template = self.followup + sent, timestamp, template, step = self.followup if now - sent > 0.075 or self.frames[AVH_REQUEST][0] != timestamp: self.done = True elif now - sent >= 0.05: - self.done = True - return [avh_request(template, 2)] + next_step = step + 1 + if next_step == 4: + self.done = True + self.followup = None + else: + self.followup = (now, timestamp, template, next_step) + return [avh_request(template, next_step)] return [] if (now - self.started < 10 or now - self.stable_since < 3 or (self.configured_since is not None and now - self.configured_since < 10)): return [] timestamp, template, _ = self.frames[AVH_REQUEST] - if now - timestamp > 0.010: + if now - timestamp > 0.010 or self.avh_req_gap is None or self.avh_req_gap < 0.80 or not self.avh_req_same_payload: return [] - self.followup = (now, timestamp, template) + self.followup = (now, timestamp, template, 1) return [avh_request(template, 1)] @@ -143,6 +153,7 @@ class AvhSources: def __init__(self): self.frames = {} self.sequential = {} + self.source_ns = {} self.blocked = False def observe(self, packets, *, boot_ns, mono_ns): @@ -163,10 +174,12 @@ class AvhSources: if data != previous[1]: self.blocked = True continue - if source <= previous[0] * 1e9: + prev_ns = self.source_ns[address] + if source < prev_ns or (source == prev_ns and counter != ((previous[1][1] + 1) & 15)): self.blocked = True continue self.sequential[address] = previous is not None and counter == ((previous[1][1] + 1) & 15) + self.source_ns[address] = source self.frames[address] = source / 1e9, data def fresh(self, now): diff --git a/opendbc_repo/opendbc/car/subaru/carcontroller.py b/opendbc_repo/opendbc/car/subaru/carcontroller.py index 1a203bf5df..b19206af38 100644 --- a/opendbc_repo/opendbc/car/subaru/carcontroller.py +++ b/opendbc_repo/opendbc/car/subaru/carcontroller.py @@ -27,13 +27,18 @@ class CarController(CarControllerBase): from opendbc.car.subaru.avh import selected as avh_selected, AvhStartup self.avh_startup = AvhStartup() if avh_selected(CP) else None self.apply_torque_last = 0 - self.angle_filter = FirstOrderFilter(0.0, 0.3, DT_CTRL) if CP.carFingerprint in (CAR.SUBARU_CROSSTREK_2025, CAR.SUBARU_IMPREZA_2025) else None + self.angle_filter = (FirstOrderFilter(0.0, 0.3, DT_CTRL) + if CP.carFingerprint in (CAR.SUBARU_CROSSTREK_2025, CAR.SUBARU_IMPREZA_2025, CAR.SUBARU_LEGACY_2025) + else None) self.apply_angle_last = 0. self.angle_was_active = False self.angle_override_frames = 0 + self.eps_stall_count = 0 self.ascent_angle_initialized = False self.ascent_es_distance_counter_last = None self.ascent_lkas_alert_counter_last = None + self.aol_non_drive_ticks = 0 + self.aol_dash_green_last = False self.angle_driver_override = False self.angle_handoff_active = False self.VM = VehicleModel(CP) if CP.carFingerprint in GEN2_ANGLE_PORTS else None @@ -62,7 +67,7 @@ class CarController(CarControllerBase): self.angle_handoff_active = False return False high, low = (150, 100) if self.CP.carFingerprint in (CAR.SUBARU_CROSSTREK_2025, CAR.SUBARU_IMPREZA_2025) else (200, 150) - torque = abs(CS.out.steeringTorque) + torque = abs(float(CS.out.steeringTorque)) if self.angle_driver_override: if torque < low: self.angle_driver_override = False @@ -85,12 +90,72 @@ class CarController(CarControllerBase): return False return True + @staticmethod + def _legacy_2025_effective_lateral_off(CS, CC) -> bool: + if bool(getattr(CS, "aol_enabled", True)): + return bool(getattr(CS, "lateral_off", False)) + return not bool(CC.enabled) + + def _legacy_2025_aol_dash_green(self, hud_control, CS, cruise_available: bool, lateral_off: bool) -> bool: + if ( + lateral_off or not cruise_available or + CS.out.steerFaultTemporary or CS.out.steerFaultPermanent + ): + self.aol_non_drive_ticks = 0 + self.aol_dash_green_last = False + return False + Gear = structs.CarState.GearShifter + if CS.out.gearShifter == Gear.park: + self.aol_non_drive_ticks = 0 + green = bool(hud_control.lanesVisible) + self.aol_dash_green_last = green + return green + if CS.out.gearShifter in (Gear.drive, Gear.manumatic): + self.aol_non_drive_ticks = 0 + stationary_aol_green = bool( + hud_control.lanesVisible and + (CS.out.standstill or CS.out.vEgoRaw <= 0.44704) and + not CS.out.steeringPressed and + not self.angle_driver_override and not self.angle_handoff_active + ) + green = bool(self.angle_was_active or stationary_aol_green) + self.aol_dash_green_last = green + return green + self.aol_non_drive_ticks += 1 + if self.aol_non_drive_ticks >= 80: + self.aol_dash_green_last = False + return False + return self.aol_dash_green_last + def _ascent_lkas_alert(self, CC, CS): - if self.CP.carFingerprint != CAR.SUBARU_ASCENT_2023 or not self.CP.flags & SubaruFlags.ASCENT_LKAS_ALERT: + if self.CP.carFingerprint not in (CAR.SUBARU_ASCENT_2023, CAR.SUBARU_LEGACY_2025) or not self.CP.flags & SubaruFlags.ASCENT_LKAS_ALERT: return None dat = CS.es_lkas_alert_dat - lateral_active = self.angle_was_active and CC.latActive and (CC.enabled or subaru_aol_qualified(self.CP, marked_only=True)) - msg = subarucan.create_ascent_lkas_alert(dat, lateral_active, CC.hudControl.visualAlert) + is_legacy_2025 = self.CP.carFingerprint == CAR.SUBARU_LEGACY_2025 + lateral_active = self.angle_was_active and CC.latActive and ( + CC.enabled or subaru_aol_qualified(self.CP, marked_only=True) + ) + if is_legacy_2025: + armed = CS.out.cruiseState.available + if self.CP.openpilotLongitudinalControl: + acc_lead_visible = bool(CC.longActive and not CS.out.gasPressed and CC.hudControl.leadVisible) + else: + dashstatus_msg = getattr(CS, "es_dashstatus_msg", None) + if dashstatus_msg and ("Cruise_Activated_Dash" in dashstatus_msg or "Cruise_State" in dashstatus_msg): + cruise_active = bool( + dashstatus_msg.get("Cruise_Activated_Dash", 0) and + dashstatus_msg.get("Cruise_State", 1) != 2 and + not CS.out.gasPressed + ) + else: + cruise_active = bool(CS.out.cruiseState.enabled and not CS.out.gasPressed) + acc_lead_visible = bool(cruise_active and dashstatus_msg and dashstatus_msg.get("Car_Follow", 0)) + msg = subarucan.create_ascent_lkas_alert( + dat, lateral_active, CC.hudControl.visualAlert, + armed=armed, acc_lead_visible=acc_lead_visible, legacy_2025=True, + ) + else: + msg = subarucan.create_ascent_lkas_alert(dat, lateral_active, CC.hudControl.visualAlert) if msg is None or (dat[1] & 0xf) == self.ascent_lkas_alert_counter_last: return None self.ascent_lkas_alert_counter_last = dat[1] & 0xf @@ -127,21 +192,48 @@ class CarController(CarControllerBase): if (self.frame % self.p.STEER_STEP) == 0: if self.CP.carFingerprint in GEN2_ANGLE_PORTS: independent_lateral = subaru_aol_qualified(self.CP, marked_only=True) - # Preserve large-turn admission; active Jacobw ports retain their native angle envelope. - angle_continuation = (self.angle_was_active and self.angle_filter is not None and - abs(CS.out.steeringAngleDeg) < JACOBW_MAX_ANGLE) - aol_motion_ok = CC.enabled or (CS.out.vEgoRaw > 0.44704 and - (abs(CS.out.steeringAngleDeg) < 120. or angle_continuation)) + if self.CP.carFingerprint == CAR.SUBARU_LEGACY_2025: + if CC.latActive and not CC.enabled: + # Hold max AOL angle cleanly inside the 210 deg cutout ceiling instead of steering out of bounds. + angle_target = float(np.clip(angle_target, -200., 200.)) + max_mads_angle = 210. if self.angle_was_active else 200. + aol_motion_ok = CC.enabled or (CS.out.vEgoRaw > 0.44704 and abs(CS.out.steeringAngleDeg) <= max_mads_angle) + gear_ok = CS.out.gearShifter in (structs.CarState.GearShifter.drive, structs.CarState.GearShifter.manumatic) + else: + # Preserve large-turn admission; active Jacobw ports retain their native angle envelope. + angle_continuation = (self.angle_was_active and self.angle_filter is not None and + abs(CS.out.steeringAngleDeg) < JACOBW_MAX_ANGLE) + aol_motion_ok = CC.enabled or (CS.out.vEgoRaw > 0.44704 and + (abs(CS.out.steeringAngleDeg) < 120. or angle_continuation)) + gear_ok = CS.out.gearShifter == structs.CarState.GearShifter.drive + legacy_lateral_off = self._legacy_2025_effective_lateral_off(CS, CC) if self.CP.carFingerprint == CAR.SUBARU_LEGACY_2025 else False angle_available = (CC.latActive and aol_motion_ok and CS.out.cruiseState.available and - (independent_lateral or CC.enabled and CS.out.cruiseState.enabled and not CS.out.brakePressed) and - CS.out.gearShifter == structs.CarState.GearShifter.drive and + (independent_lateral or (CC.enabled and CS.out.cruiseState.enabled and not CS.out.brakePressed)) and + gear_ok and + not legacy_lateral_off and not CS.out.standstill and not CS.out.steerFaultTemporary and not CS.out.steerFaultPermanent) angle_active = self.angle_active(CS, angle_available) + if self.CP.carFingerprint == CAR.SUBARU_LEGACY_2025: + if angle_active and self.angle_was_active and abs(self.apply_angle_last - CS.out.steeringAngleDeg) > 5.0: + self.eps_stall_count += 1 + if self.eps_stall_count >= 8: + # Yield via handoff before EPS rack latches Steer_Error_1, then re-sync next step. + self.angle_handoff_active = True + angle_active = False + self.eps_stall_count = 0 + else: + self.eps_stall_count = 0 + if not angle_active and self.angle_filter is not None: + self.angle_filter.x = CS.out.steeringAngleDeg if self.CP.carFingerprint == CAR.SUBARU_ASCENT_2023 and not self.ascent_angle_initialized: self.apply_angle_last = CS.out.steeringAngleDeg self.ascent_angle_initialized = True angle_active = False - if self.CP.carFingerprint in (CAR.SUBARU_LEGACY_2025, CAR.SUBARU_ASCENT_2023, CAR.SUBARU_OUTBACK_2023): + if self.CP.carFingerprint == CAR.SUBARU_LEGACY_2025: + apply_angle = apply_std_steer_angle_limits(angle_target, self.apply_angle_last, + CS.out.vEgoRaw, CS.out.steeringAngleDeg, angle_active, + self.p.LEGACY_2025_ANGLE_LIMITS) + elif self.CP.carFingerprint in (CAR.SUBARU_ASCENT_2023, CAR.SUBARU_OUTBACK_2023): apply_angle = apply_std_steer_angle_limits(actuators.steeringAngleDeg, self.apply_angle_last, CS.out.vEgoRaw, CS.out.steeringAngleDeg, angle_active, self.p.FIXED_ANGLE_LIMITS) @@ -214,11 +306,19 @@ class CarController(CarControllerBase): can_sends.extend(send_sng(self, CC, CS, now_nanos)) # *** alerts and pcm cancel *** + enabled_for_dash_2025 = False + if self.CP.carFingerprint == CAR.SUBARU_LEGACY_2025: + enabled_for_dash_2025 = self._legacy_2025_aol_dash_green( + hud_control, + CS, + bool(CS.out.cruiseState.available), + self._legacy_2025_effective_lateral_off(CS, CC), + ) lkas_alert_msg = self._ascent_lkas_alert(CC, CS) if lkas_alert_msg is not None: can_sends.append(lkas_alert_msg) if self.CP.flags & SubaruFlags.PREGLOBAL: - if self.frame % 5 == 0: + if self.CP.carFingerprint != CAR.SUBARU_OUTBACK_PREGLOBAL and self.frame % 5 == 0: # 1 = main, 2 = set shallow, 3 = set deep, 4 = resume shallow, 5 = resume deep # disengage ACC when OP is disengaged if pcm_cancel_cmd: @@ -241,18 +341,50 @@ class CarController(CarControllerBase): can_sends.append(subarucan.create_es_dashstatus(self.packer, self.frame // 10, CS.es_dashstatus_msg, CC.enabled, self.CP.openpilotLongitudinalControl, CC.longActive, hud_control.leadVisible)) - lkas_active = self.angle_was_active if self.CP.carFingerprint in GEN2_ANGLE_PORTS else CC.enabled - lkas_state_msg = CS.es_lkas_state_msg - if self.CP.carFingerprint in GEN2_ANGLE_PORTS or subaru_aol_qualified(self.CP, marked_only=True): - if self.CP.carFingerprint not in GEN2_ANGLE_PORTS: - lkas_active = CC.latActive - lkas_state_msg = dict(lkas_state_msg, LKAS_ACTIVE=int(lkas_active)) - can_sends.append(subarucan.create_es_lkas_state(self.packer, self.frame // 10, lkas_state_msg, lkas_active, hud_control.visualAlert, - hud_control.leftLaneVisible, hud_control.rightLaneVisible, - hud_control.leftLaneDepart, hud_control.rightLaneDepart)) + if self.CP.carFingerprint == CAR.SUBARU_LEGACY_2025: + in_drive = CS.out.gearShifter in (structs.CarState.GearShifter.drive, structs.CarState.GearShifter.manumatic) + cruise_available = CS.out.cruiseState.available + lateral_off = self._legacy_2025_effective_lateral_off(CS, CC) + aol_enabled = bool(getattr(CS, "aol_enabled", True)) + wheel_ready = bool(cruise_available and aol_enabled) + if not (in_drive and cruise_available) or lateral_off or not hud_control.lanesVisible: + left_line = 0 + right_line = 0 + left_depart = False + right_depart = False + else: + left_line = 1 if hud_control.leftLaneVisible else 0 + right_line = 1 if hud_control.rightLaneVisible else 0 + left_depart = bool(hud_control.leftLaneDepart) + right_depart = bool(hud_control.rightLaneDepart) + + can_sends.append(subarucan.create_es_lkas_state( + self.packer, self.frame // 10, CS.es_lkas_state_msg, enabled_for_dash_2025, hud_control.visualAlert, + left_line, right_line, left_depart, right_depart, + ready=wheel_ready, lkas_active=True, in_drive=in_drive, + steering_active=self.angle_was_active and CC.latActive, + )) + else: + lkas_active = self.angle_was_active if self.CP.carFingerprint in GEN2_ANGLE_PORTS else CC.enabled + lkas_state_msg = CS.es_lkas_state_msg + if self.CP.carFingerprint in GEN2_ANGLE_PORTS or subaru_aol_qualified(self.CP, marked_only=True): + if self.CP.carFingerprint not in GEN2_ANGLE_PORTS: + lkas_active = CC.latActive + lkas_state_msg = dict(lkas_state_msg, LKAS_ACTIVE=int(lkas_active)) + can_sends.append(subarucan.create_es_lkas_state(self.packer, self.frame // 10, lkas_state_msg, lkas_active, hud_control.visualAlert, + hud_control.leftLaneVisible, hud_control.rightLaneVisible, + hud_control.leftLaneDepart, hud_control.rightLaneDepart)) if self.CP.flags & SubaruFlags.SEND_INFOTAINMENT: - can_sends.append(subarucan.create_es_infotainment(self.packer, self.frame // 10, CS.es_infotainment_msg, hud_control.visualAlert)) + if self.CP.carFingerprint == CAR.SUBARU_LEGACY_2025: + can_sends.append(subarucan.create_es_infotainment( + self.packer, self.frame // 10, CS.es_infotainment_msg, hud_control.visualAlert, + audible_alert=hud_control.audibleAlert, legacy_2025=True, + )) + else: + can_sends.append(subarucan.create_es_infotainment( + self.packer, self.frame // 10, CS.es_infotainment_msg, hud_control.visualAlert, + )) if self.CP.openpilotLongitudinalControl: if self.frame % 5 == 0: @@ -266,7 +398,7 @@ class CarController(CarControllerBase): self.CP.openpilotLongitudinalControl, cruise_brake > 0, cruise_throttle)) else: cancel_frame_ready = True - if self.CP.carFingerprint == CAR.SUBARU_ASCENT_2023: + if self.CP.carFingerprint in (CAR.SUBARU_ASCENT_2023, CAR.SUBARU_LEGACY_2025): stock_counter = CS.es_distance_msg["COUNTER"] cancel_frame_ready = stock_counter != self.ascent_es_distance_counter_last self.ascent_es_distance_counter_last = stock_counter diff --git a/opendbc_repo/opendbc/car/subaru/carstate.py b/opendbc_repo/opendbc/car/subaru/carstate.py index 1fd4b37e01..1cb51c6160 100644 --- a/opendbc_repo/opendbc/car/subaru/carstate.py +++ b/opendbc_repo/opendbc/car/subaru/carstate.py @@ -6,6 +6,10 @@ from opendbc.car.interfaces import CarStateBase from opendbc.car.subaru.values import CAR, DBC, CanBus, SubaruFlags from opendbc.car import CanSignalRateCalculator +# 8-speed Lineartronic CVT simulated paddle-shift ratios 1..8 on 0x48 Transmission.Gear +# (bits 0..2 = 0b001 Drive range, bits 3..6 = simulated gear 1..8 or 0 in shift transition, bit 7 = manual mode) +SUBARU_CVT_MANUAL_GEARS = frozenset({129, 137, 145, 153, 161, 169, 177, 185, 193}) + class CarState(CarStateBase): def __init__(self, CP): @@ -33,6 +37,32 @@ class CarState(CarStateBase): from opendbc.car.subaru.high_angle_guard import HighAngleGuard, selected self.high_angle_guard = HighAngleGuard() if selected(CP) else None self.high_angle_cut = False + self.prev_cam_lkas_toggle: bool | None = None + self.prev_cruise_available: bool | None = None + self.aol_enabled = True + self.lateral_off = False + self._prev_aol_enabled: bool | None = None + self._lkas_event_hold_frames = 0 + self._lkas_mode_settle_frames = 0 + + def _sync_legacy_2025_lateral_mode(self, cruise_available: bool, lkas_pressed: bool) -> None: + aol = bool(getattr(self, "aol_enabled", True)) + if not cruise_available: + self.lateral_off = not aol + self._lkas_mode_settle_frames = 0 + self._prev_aol_enabled = aol + return + + entered_mode = (not bool(self.prev_cruise_available)) or (aol != self._prev_aol_enabled) + if entered_mode: + self._lkas_mode_settle_frames = 15 + self.lateral_off = not aol + elif lkas_pressed: + self._lkas_mode_settle_frames = 15 + self.lateral_off = (not self.lateral_off) if aol else True + else: + self._lkas_mode_settle_frames = max(0, self._lkas_mode_settle_frames - 1) + self._prev_aol_enabled = aol def update(self, can_parsers) -> structs.CarState: cp = can_parsers[Bus.pt] @@ -78,7 +108,12 @@ class CarState(CarStateBase): cp_transmission = cp_alt if self.CP.flags & SubaruFlags.HYBRID else cp can_gear = int(cp_transmission.vl["Transmission"]["Gear"]) - ret.gearShifter = self.parse_gear_shifter(self.shifter_values.get(can_gear, None)) + if self.CP.carFingerprint == CAR.SUBARU_LEGACY_2025 and can_gear in SUBARU_CVT_MANUAL_GEARS: + ret.gearShifter = structs.CarState.GearShifter.manumatic + elif self.CP.carFingerprint == CAR.SUBARU_LEGACY_2025 and can_gear == 0: + ret.gearShifter = structs.CarState.GearShifter.neutral + else: + ret.gearShifter = self.parse_gear_shifter(self.shifter_values.get(can_gear, None)) if not (self.CP.flags & SubaruFlags.LKAS_ANGLE): ret.steeringAngleDeg = cp_angle.vl["Steering_Torque"]["Steering_Angle"] @@ -102,11 +137,14 @@ class CarState(CarStateBase): cp_cruise = cp_alt if self.CP.flags & SubaruFlags.GLOBAL_GEN2 else cp cp_es_brake = cp_alt if self.CP.flags & SubaruFlags.GLOBAL_GEN2 else cp_cam + soft_disable = False + if self.CP.carFingerprint == CAR.SUBARU_LEGACY_2025: + soft_disable = cp_cam.vl["ES_DashStatus"].get("Cruise_Soft_Disable", 0) != 0 if self.CP.carFingerprint in (CAR.SUBARU_CROSSTREK_2025, CAR.SUBARU_IMPREZA_2025, CAR.SUBARU_LEGACY_2025, CAR.SUBARU_ASCENT_2023, CAR.SUBARU_FORESTER_2022, CAR.SUBARU_OUTBACK_2023): ret.cruiseState.enabled = cp_es_brake.vl["ES_Status"]["Cruise_Activated"] != 0 - ret.cruiseState.available = cp_cam.vl["ES_DashStatus"]["Cruise_On"] != 0 + ret.cruiseState.available = (cp_cam.vl["ES_DashStatus"]["Cruise_On"] != 0) and not soft_disable elif self.CP.flags & (SubaruFlags.HYBRID | SubaruFlags.LKAS_ANGLE): # ES_DashStatus->Cruise_Activated_Dash is likely intended for the dash display only, as it falls # during user gas override and at standstill. ES_Status is missing on hybrid, so we use ES_Brake instead @@ -115,10 +153,10 @@ class CarState(CarStateBase): # brake while engaged at a stop. ES_Status and ES_DashStatus->Signal7 correctly fell, but is either missing or # always zero on hybrids. Probably need to split angle & hybrid. 0x27 and 0x225 on hybrids may work for them. ret.cruiseState.enabled = cp_es_brake.vl["ES_Brake"]['Cruise_Activated'] != 0 - ret.cruiseState.available = cp_cam.vl["ES_DashStatus"]['Cruise_On'] != 0 + ret.cruiseState.available = (cp_cam.vl["ES_DashStatus"]['Cruise_On'] != 0) and not soft_disable else: ret.cruiseState.enabled = cp_cruise.vl["CruiseControl"]["Cruise_Activated"] != 0 - ret.cruiseState.available = cp_cruise.vl["CruiseControl"]["Cruise_On"] != 0 + ret.cruiseState.available = (cp_cruise.vl["CruiseControl"]["Cruise_On"] != 0) and not soft_disable ret.cruiseState.speed = cp_cam.vl["ES_DashStatus"]["Cruise_Set_Speed"] * CV.KPH_TO_MS if (self.CP.flags & SubaruFlags.PREGLOBAL and cp.vl["Dash_State2"]["UNITS"] == 1) or \ @@ -148,6 +186,34 @@ class CarState(CarStateBase): self.es_lkas_state_msg = copy.copy(cp_cam.vl["ES_LKAS_State"]) self.es_brake_msg = copy.copy(cp_es_brake.vl["ES_Brake"]) + if self.CP.carFingerprint == CAR.SUBARU_LEGACY_2025: + cam_lkas_toggle = int(self.es_lkas_state_msg.get("LKAS_Dash_State", 0)) > 0 + steer_fault = bool(ret.steerFaultTemporary or ret.steerFaultPermanent) + lkas_pressed = False + if steer_fault or not ret.cruiseState.available: + self.prev_cam_lkas_toggle = None + self._lkas_event_hold_frames = 0 + else: + if ( + self.prev_cam_lkas_toggle is not None + and self.prev_cruise_available + and cam_lkas_toggle != self.prev_cam_lkas_toggle + ): + lkas_pressed = True + self._lkas_event_hold_frames = 5 + self.prev_cam_lkas_toggle = cam_lkas_toggle + if self._lkas_event_hold_frames > 0: + button_events = list(ret.buttonEvents) if ret.buttonEvents else [] + ButtonType = structs.CarState.ButtonEvent.Type + button_events.extend([ + structs.CarState.ButtonEvent(pressed=True, type=ButtonType.lkas), + structs.CarState.ButtonEvent(pressed=False, type=ButtonType.lkas), + ]) + ret.buttonEvents = button_events + self._lkas_event_hold_frames -= 1 + self._sync_legacy_2025_lateral_mode(bool(ret.cruiseState.available), lkas_pressed) + self.prev_cruise_available = bool(ret.cruiseState.available) + # TODO: Hybrid cars don't have ES_Distance, need a replacement if not (self.CP.flags & SubaruFlags.HYBRID): # 8 is known AEB, there are a few other values related to AEB we ignore @@ -190,8 +256,17 @@ class CarState(CarStateBase): self.es_dashstatus_msg = copy.copy(cp_cam.vl["ES_DashStatus"]) if self.CP.flags & SubaruFlags.ASCENT_LKAS_ALERT: alert = cp_cam.vl["ES_LKAS_Alert"] - self.es_lkas_alert_dat = (bytes((int(alert["CHECKSUM"]), int(alert["COUNTER"]) | (int(alert["Signal1"]) << 4))) + - int(alert["Payload"]).to_bytes(6, "little")) + self.es_lkas_alert_dat = ( + bytes(( + int(alert["CHECKSUM"]), + int(alert["COUNTER"]) | (int(alert["Signal1"]) << 4), + int(alert["LKAS_Alert"]), + int(alert["LKAS_Alert_Msg"]), + int(alert["LKAS_HUD_Lights"]), + int(alert["ACC_Lead_LED"]), + )) + + int(alert["Signal2"]).to_bytes(2, "little") + ) if self.CP.flags & SubaruFlags.SEND_INFOTAINMENT: self.es_infotainment_msg = copy.copy(cp_cam.vl["ES_Infotainment"]) diff --git a/opendbc_repo/opendbc/car/subaru/interface.py b/opendbc_repo/opendbc/car/subaru/interface.py index 0d5570ccd9..1cc0705762 100644 --- a/opendbc_repo/opendbc/car/subaru/interface.py +++ b/opendbc_repo/opendbc/car/subaru/interface.py @@ -14,6 +14,7 @@ GEN2_ANGLE_PORTS = frozenset((CAR.SUBARU_CROSSTREK_2025, CAR.SUBARU_IMPREZA_2025 class CarInterface(CarInterfaceBase): CarState = CarState CarController = CarController + DRIVABLE_GEARS = (structs.CarState.GearShifter.manumatic,) def update(self, can_packets): source = self.CS.startup_sources @@ -58,7 +59,7 @@ class CarInterface(CarInterfaceBase): if not (ret.flags & SubaruFlags.PREGLOBAL) and 0x323 in fingerprint[2]: ret.flags |= SubaruFlags.SEND_INFOTAINMENT.value - if candidate == CAR.SUBARU_ASCENT_2023 and fingerprint[CanBus.camera].get(0x3C4) == 8: + if candidate in (CAR.SUBARU_ASCENT_2023, CAR.SUBARU_LEGACY_2025) and fingerprint[CanBus.camera].get(0x3C4) == 8: ret.flags |= SubaruFlags.ASCENT_LKAS_ALERT.value if ret.flags & SubaruFlags.PREGLOBAL: @@ -131,7 +132,8 @@ class CarInterface(CarInterfaceBase): ret.steerActuatorDelay = 0.15 elif candidate == CAR.SUBARU_OUTBACK_PREGLOBAL: - pass + ret.dashcamOnly = False + ret.safetyConfigs[0].safetyParam = SubaruSafetyFlags.PREGLOBAL_OUTBACK_STOCK_ACC.value else: raise ValueError(f"unknown car: {candidate}") diff --git a/opendbc_repo/opendbc/car/subaru/stock_aol.py b/opendbc_repo/opendbc/car/subaru/stock_aol.py index 18ae912d7e..3f37c68ab0 100644 --- a/opendbc_repo/opendbc/car/subaru/stock_aol.py +++ b/opendbc_repo/opendbc/car/subaru/stock_aol.py @@ -30,7 +30,7 @@ def qualified(cp, *, marked_only=False): if cp.flags & SubaruFlags.STOP_START_OFF: expected |= int(SubaruSafetyFlags.STOP_START_BUTTON) if cp.carFingerprint == CAR.SUBARU_LEGACY_2025: - allowed |= int(SubaruFlags.STOP_START_OFF | SubaruFlags.AVH_STARTUP) + allowed |= int(SubaruFlags.STOP_START_OFF | SubaruFlags.AVH_STARTUP | SubaruFlags.ASCENT_LKAS_ALERT) if cp.flags & SubaruFlags.AVH_STARTUP: expected |= int(SubaruSafetyFlags.AVH_STARTUP) if cp.flags & SubaruFlags.STOP_START_OFF: @@ -59,6 +59,11 @@ def qualified(cp, *, marked_only=False): def temporary_restriction(cp, state): + allowed_gears = ( + (structs.CarState.GearShifter.drive, structs.CarState.GearShifter.manumatic) + if cp is not None and cp.carFingerprint == CAR.SUBARU_LEGACY_2025 else + (structs.CarState.GearShifter.drive,) + ) return bool(state is not None and qualified(cp, marked_only=True) and state.canValid and not state.canTimeout and not state.steerFaultPermanent and not state.accFaulted and state.cruiseState.available and - (state.gearShifter != structs.CarState.GearShifter.drive or state.steerFaultTemporary or state.standstill)) + (state.gearShifter not in allowed_gears or state.steerFaultTemporary or state.standstill)) diff --git a/opendbc_repo/opendbc/car/subaru/subarucan.py b/opendbc_repo/opendbc/car/subaru/subarucan.py index 6c31a9b8a6..4150c28290 100644 --- a/opendbc_repo/opendbc/car/subaru/subarucan.py +++ b/opendbc_repo/opendbc/car/subaru/subarucan.py @@ -2,6 +2,7 @@ from opendbc.car import structs from opendbc.car.subaru.values import CanBus VisualAlert = structs.CarControl.HUDControl.VisualAlert +AudibleAlert = structs.CarControl.HUDControl.AudibleAlert def create_steering_control(packer, apply_torque, steer_req): @@ -67,7 +68,8 @@ def create_es_distance(packer, frame, es_distance_msg, bus, pcm_cancel_cmd, long return packer.make_can_msg("ES_Distance", bus, values) -def create_es_lkas_state(packer, frame, es_lkas_state_msg, enabled, visual_alert, left_line, right_line, left_lane_depart, right_lane_depart): +def create_es_lkas_state(packer, frame, es_lkas_state_msg, enabled, visual_alert, left_line, right_line, left_lane_depart, right_lane_depart, + ready=None, lkas_active=None, in_drive=False, steering_active=False): values = {s: es_lkas_state_msg[s] for s in [ "CHECKSUM", "LKAS_Alert_Msg", @@ -88,29 +90,43 @@ def create_es_lkas_state(packer, frame, es_lkas_state_msg, enabled, visual_alert values["COUNTER"] = frame % 0x10 - # Filter the stock LKAS "Keep hands on wheel" alert - if values["LKAS_Alert_Msg"] == 1: - values["LKAS_Alert_Msg"] = 0 + legacy_2025_hud = (ready is not None) or (lkas_active is not None) + if legacy_2025_hud: + # Filter stock EyeSight centering engage/cancel and "Keep hands on wheel" alerts + # (25: centering engage beep, 27: centering off beep, 28: hands-on warning beep, 30: hands-on OFF cancel beep) + if steering_active and values["LKAS_Alert"] in (25, 27, 28, 30) and values["LKAS_Alert_Msg"] in (0, 1, 7): + values["LKAS_Alert"] = 0 + if steering_active and values["LKAS_Alert_Msg"] in (1, 7) and values["LKAS_Alert"] == 0: + values["LKAS_Alert_Msg"] = 0 + else: + # Filter the stock LKAS "Keep hands on wheel" alert + if values["LKAS_Alert_Msg"] == 1: + values["LKAS_Alert_Msg"] = 0 - # Filter the stock LKAS sending an audible alert when it turns off LKAS - if values["LKAS_Alert"] == 27: - values["LKAS_Alert"] = 0 + # Filter the stock LKAS sending an audible alert when it turns off LKAS + if values["LKAS_Alert"] == 27: + values["LKAS_Alert"] = 0 - # Filter the stock LKAS sending an audible alert when "Keep hands on wheel" alert is active (2020+ models) - if values["LKAS_Alert"] == 28 and values["LKAS_Alert_Msg"] == 7: - values["LKAS_Alert"] = 0 + # Filter the stock LKAS sending an audible alert when "Keep hands on wheel" alert is active (2020+ models) + if values["LKAS_Alert"] == 28 and values["LKAS_Alert_Msg"] == 7: + values["LKAS_Alert"] = 0 - # Filter the stock LKAS sending an audible alert when "Keep hands on wheel OFF" alert is active (2020+ models) - if values["LKAS_Alert"] == 30: - values["LKAS_Alert"] = 0 + # Filter the stock LKAS sending an audible alert when "Keep hands on wheel OFF" alert is active (2020+ models) + if values["LKAS_Alert"] == 30: + values["LKAS_Alert"] = 0 - # Filter the stock LKAS sending "Keep hands on wheel OFF" alert (2020+ models) - if values["LKAS_Alert_Msg"] == 7: - values["LKAS_Alert_Msg"] = 0 + # Filter the stock LKAS sending "Keep hands on wheel OFF" alert (2020+ models) + if values["LKAS_Alert_Msg"] == 7: + values["LKAS_Alert_Msg"] = 0 + # Preserve stock EyeSight Lane Departure Warnings (11, 12) at all times. # Show Keep hands on wheel alert for openpilot steerRequired alert if visual_alert == VisualAlert.steerRequired: - values["LKAS_Alert_Msg"] = 1 + if legacy_2025_hud: + if values["LKAS_Alert"] == 0 and values["LKAS_Alert_Msg"] == 0: + values["LKAS_Alert_Msg"] = 1 + else: + values["LKAS_Alert_Msg"] = 1 # Ensure we don't overwrite potentially more important alerts from stock (e.g. FCW) if visual_alert == VisualAlert.ldw and values["LKAS_Alert"] == 0: @@ -119,14 +135,37 @@ def create_es_lkas_state(packer, frame, es_lkas_state_msg, enabled, visual_alert elif right_lane_depart: values["LKAS_Alert"] = 11 # Right lane departure dash alert - if enabled: - values["LKAS_ACTIVE"] = 1 # Show LKAS lane lines - values["LKAS_Dash_State"] = 2 # Green enabled indicator - else: - values["LKAS_Dash_State"] = 0 # LKAS Not enabled + if legacy_2025_hud: + screen_active = True if lkas_active is None else bool(lkas_active) + if screen_active: + values["LKAS_ACTIVE"] = 1 # Show LKAS lane lines / keep screen active + values["LKAS_Left_Line_Enable"] = 1 + values["LKAS_Right_Line_Enable"] = 1 + if enabled: + values["LKAS_Dash_State"] = 2 # 2: Green enabled / active steering + elif ready: + values["LKAS_Dash_State"] = 1 # 1: White ready / override + else: + values["LKAS_Dash_State"] = 0 # 0: Inactive / no steering wheel icon + line_visible = 1 if in_drive else 0 + else: + values["LKAS_ACTIVE"] = 0 + values["LKAS_Dash_State"] = 0 + values["LKAS_Left_Line_Enable"] = 0 + values["LKAS_Right_Line_Enable"] = 0 + line_visible = 0 - values["LKAS_Left_Line_Visible"] = int(left_line) - values["LKAS_Right_Line_Visible"] = int(right_line) + values["LKAS_Left_Line_Visible"] = line_visible if left_line else 0 + values["LKAS_Right_Line_Visible"] = line_visible if right_line else 0 + else: + if enabled: + values["LKAS_ACTIVE"] = 1 # Show LKAS lane lines + values["LKAS_Dash_State"] = 2 # Green enabled indicator + else: + values["LKAS_Dash_State"] = 0 # LKAS Not enabled + + values["LKAS_Left_Line_Visible"] = int(left_line) + values["LKAS_Right_Line_Visible"] = int(right_line) return packer.make_can_msg("ES_LKAS_State", CanBus.main, values) @@ -231,7 +270,7 @@ def create_es_status(packer, frame, es_status_msg, long_enabled, long_active, cr return packer.make_can_msg("ES_Status", CanBus.main, values) -def create_es_infotainment(packer, frame, es_infotainment_msg, visual_alert): +def create_es_infotainment(packer, frame, es_infotainment_msg, visual_alert, audible_alert=AudibleAlert.none, legacy_2025=False): # Filter stock LKAS disabled and Keep hands on steering wheel OFF alerts values = {s: es_infotainment_msg[s] for s in [ "CHECKSUM", @@ -248,7 +287,12 @@ def create_es_infotainment(packer, frame, es_infotainment_msg, visual_alert): # Show Keep hands on wheel alert for openpilot steerRequired alert if visual_alert == VisualAlert.steerRequired: - values["LKAS_State_Infotainment"] = 3 + if legacy_2025: + # 4 adds wheel OFF icon on lockout without clobbering existing warnings + if values["LKAS_State_Infotainment"] == 0: + values["LKAS_State_Infotainment"] = 4 if audible_alert == AudibleAlert.warningImmediate else 3 + else: + values["LKAS_State_Infotainment"] = 3 # Show Obstacle Detected for fcw if visual_alert == VisualAlert.fcw: @@ -257,14 +301,54 @@ def create_es_infotainment(packer, frame, es_infotainment_msg, visual_alert): return packer.make_can_msg("ES_Infotainment", CanBus.main, values) -def create_ascent_lkas_alert(raw_dat: bytes, lateral_active: bool, visual_alert): +def create_ascent_lkas_alert( + raw_dat: bytes, + lateral_active: bool, + visual_alert, + armed: bool = False, + acc_lead_visible: bool = False, + legacy_2025: bool = False, +): address = 0x3C4 if len(raw_dat) != 8 or raw_dat[0] != (((address & 0xff) + (address >> 8) + sum(raw_dat[1:])) & 0xff): return None dat = bytearray(raw_dat) - if lateral_active and visual_alert != VisualAlert.steerRequired and dat[2:] == b"\x00\x01\x04\x00\x00\x00": - dat[3:5] = b"\x00\x00" + changed = False + + if legacy_2025 and armed: + # 0x3C4 on Legacy 2025: dat[2]=chime (0x18 chirp, 0x1a/0x1b single, 0x1c 2x bouncy, 0x1e 4x strong), + # dat[3]=small-screen popup (0x01 hands-on, 0x07 flashing), dat[4]=HUD LEDs (0x01/0x02/0x04 yellow, 0x10/0x20/0x40 red). + target_alert = b"\x00\x01\x04" if visual_alert == VisualAlert.steerRequired else None + + # Only deduplicate EyeSight prompts while we are requesting steering. + duplicate = dat[2:5] in ( + b"\x00\x01\x04", b"\x00\x07\x04", b"\x00\x07\x30", + b"\x00\x00\x02", b"\x00\x00\x30", b"\x1b\x00\x00", b"\x19\x00\x00", + b"\x1c\x07\x04", b"\x1e\x00\x30", b"\x19\x01\x04", + ) + if lateral_active and duplicate and dat[2:5] != target_alert: + dat[2:5] = b"\x00\x00\x00" + changed = True + if target_alert is not None: + if dat[2:5] == b"\x00\x00\x00": + dat[2:5] = target_alert + changed = True + if dat[2:5] == target_alert and dat[5] == 0x01: + dat[5] = 0x00 + changed = True + + if not legacy_2025 and lateral_active and visual_alert != VisualAlert.steerRequired: + if dat[2:] == b"\x00\x01\x04\x00\x00\x00": + dat[3:5] = b"\x00\x00" + changed = True + + # Restore dat[5] = 0x01 when ACC is tracking a lead and background LKAS warning cleared dat[5]. + if legacy_2025 and acc_lead_visible and dat[2:5] == b"\x00\x00\x00" and dat[5] == 0x00: + dat[5] = 0x01 + changed = True + + if changed: dat[0] = ((address & 0xff) + (address >> 8) + sum(dat[1:])) & 0xff return address, bytes(dat), CanBus.main diff --git a/opendbc_repo/opendbc/car/subaru/tests/test_angle_handoff.py b/opendbc_repo/opendbc/car/subaru/tests/test_angle_handoff.py index 603a61c71d..1132e288f1 100644 --- a/opendbc_repo/opendbc/car/subaru/tests/test_angle_handoff.py +++ b/opendbc_repo/opendbc/car/subaru/tests/test_angle_handoff.py @@ -59,10 +59,12 @@ class TestIndependentAngleEnvelope(unittest.TestCase): cars = (CAR.SUBARU_CROSSTREK_2025, CAR.SUBARU_IMPREZA_2025, CAR.SUBARU_LEGACY_2025, CAR.SUBARU_ASCENT_2023, CAR.SUBARU_FORESTER_2022, CAR.SUBARU_OUTBACK_2023) for car in cars: - for speed, angle, expected in ((5., 119.5, True), (5., -119.5, True), - (5., 120., False), (5., -120., False), - (5., 200., False), (5., -200., False), - (.4, 10., False), (.5, 10., True)): + cases = ((5., 199.5, True), (5., -199.5, True), (5., 200., True), (5., -200., True), + (5., 201., False), (5., -201., False), (.4, 10., False), (.5, 10., True)) \ + if car == CAR.SUBARU_LEGACY_2025 else \ + ((5., 119.5, True), (5., -119.5, True), (5., 120., False), (5., -120., False), + (5., 200., False), (5., -200., False), (.4, 10., False), (.5, 10., True)) + for speed, angle, expected in cases: with self.subTest(car=car, speed=speed, angle=angle): cp, controller, command, state = setup_controller(car) cp.alternativeExperience = 32 @@ -80,6 +82,88 @@ class TestIndependentAngleEnvelope(unittest.TestCase): expected_angle = max(-190., min(190., angle)) if car in (CAR.SUBARU_CROSSTREK_2025, CAR.SUBARU_IMPREZA_2025) else angle self.assertAlmostEqual(decoded['LKAS_Output'], expected_angle, places=2) + def test_legacy_2025_mads_hysteresis_and_eps_stall_guard(self): + cp, controller, command, state = setup_controller(CAR.SUBARU_LEGACY_2025) + cp.alternativeExperience = 32 + command.enabled = False + state.out.cruiseState.enabled = False + state.out.vEgoRaw = state.out.vEgo = 5. + state.out.standstill = False + state.out.steeringTorque = state.out.steeringRateDeg = 0 + state.out.steeringAngleDeg = 199. + command.actuators.steeringAngleDeg = 199. + _, decoded = step(controller, command, state) + self.assertEqual(decoded['LKAS_Request'], 1) + state.out.steeringAngleDeg = 205. + command.actuators.steeringAngleDeg = 205. + _, decoded = step(controller, command, state) + self.assertEqual(decoded['LKAS_Request'], 1) + state.out.steeringAngleDeg = 211. + _, decoded = step(controller, command, state) + self.assertEqual(decoded['LKAS_Request'], 0) + + # 8-frame EPS stall guard releases for 1 frame when wheel angle stops tracking target. + _, controller, command, state = setup_controller(CAR.SUBARU_LEGACY_2025) + state.out.vEgoRaw = state.out.vEgo = 5. + state.out.standstill = False + state.out.steeringAngleDeg = 0. + command.actuators.steeringAngleDeg = 0. + _, decoded = step(controller, command, state) + self.assertEqual(decoded['LKAS_Request'], 1) + command.actuators.steeringAngleDeg = 40. + stalled = 0 + for _ in range(20): + prev_output = decoded['LKAS_Output'] + _, decoded = step(controller, command, state) + if abs(prev_output - state.out.steeringAngleDeg) > 5.0: + stalled += 1 + if stalled == 8: + self.assertEqual(decoded['LKAS_Request'], 0) + self.assertEqual(decoded['LKAS_Output'], 0.) + break + self.assertEqual(decoded['LKAS_Request'], 1) + else: + self.fail("EPS stall guard did not trigger after 8 stalled frames") + + def test_legacy_2025_aol_clamps_target_to_hold_max_turn(self): + for sign in (-1, 1): + with self.subTest(sign=sign): + cp, controller, command, state = setup_controller(CAR.SUBARU_LEGACY_2025) + cp.alternativeExperience = 32 + command.enabled = False + state.out.cruiseState.enabled = False + state.out.vEgoRaw = state.out.vEgo = 25. + state.out.standstill = False + state.out.steeringTorque = state.out.steeringRateDeg = 0 + state.out.steeringAngleDeg = 199. * sign + command.latActive = False + step(controller, command, state) + command.latActive = True + command.actuators.steeringAngleDeg = 240. * sign + for _ in range(10): + _, decoded = step(controller, command, state) + state.out.steeringAngleDeg = decoded['LKAS_Output'] + self.assertEqual(decoded['LKAS_Request'], 1) + self.assertAlmostEqual(decoded['LKAS_Output'], 200. * sign, places=2) + + # Active cruise (ACC engaged) is not capped to the AOL 200 deg ceiling. + _, controller, command, state = setup_controller(CAR.SUBARU_LEGACY_2025) + command.enabled = True + state.out.cruiseState.enabled = True + state.out.vEgoRaw = state.out.vEgo = 25. + state.out.standstill = False + state.out.steeringTorque = state.out.steeringRateDeg = 0 + state.out.steeringAngleDeg = 199. + command.latActive = False + step(controller, command, state) + command.latActive = True + command.actuators.steeringAngleDeg = 220. + for _ in range(10): + _, decoded = step(controller, command, state) + state.out.steeringAngleDeg = decoded['LKAS_Output'] + self.assertEqual(decoded['LKAS_Request'], 1) + self.assertGreater(decoded['LKAS_Output'], 200.) + def test_ordinary_engagement_preserves_transmitted_history_and_other_profiles(self): for car in (CAR.SUBARU_CROSSTREK_2025, CAR.SUBARU_IMPREZA_2025, CAR.SUBARU_LEGACY_2025, CAR.SUBARU_ASCENT_2023, CAR.SUBARU_FORESTER_2022, CAR.SUBARU_OUTBACK_2023): @@ -94,7 +178,7 @@ class TestIndependentAngleEnvelope(unittest.TestCase): for _ in range(3): _, decoded = step(controller, command, state) self.assertTrue(decoded['LKAS_Request']) - if car in (CAR.SUBARU_CROSSTREK_2025, CAR.SUBARU_IMPREZA_2025): + if car in (CAR.SUBARU_CROSSTREK_2025, CAR.SUBARU_IMPREZA_2025, CAR.SUBARU_LEGACY_2025): # The EPS bound applies to transmitted commands, not measured-angle admission. # Follow the small target without jumping to the measured angle. expected = -1.45 * (1. - (30. / 31.) ** 5) diff --git a/opendbc_repo/opendbc/car/subaru/tests/test_ascent_angle.py b/opendbc_repo/opendbc/car/subaru/tests/test_ascent_angle.py index 68f2f6bfa6..920d2d7049 100644 --- a/opendbc_repo/opendbc/car/subaru/tests/test_ascent_angle.py +++ b/opendbc_repo/opendbc/car/subaru/tests/test_ascent_angle.py @@ -196,7 +196,7 @@ class TestSubaruAscentController(unittest.TestCase): self.assertEqual(values['Close_Distance'], state.es_distance_msg['Close_Distance']) self.assertEqual(observed, [0, 1, 3]) - def test_repeated_stock_cancel_gate_is_ascent_2023_only(self): + def test_repeated_stock_cancel_gate_cars(self): for car in (CAR.SUBARU_ASCENT_2023, CAR.SUBARU_CROSSTREK_2025, CAR.SUBARU_IMPREZA_2025, CAR.SUBARU_LEGACY_2025, CAR.SUBARU_OUTBACK_2023, CAR.SUBARU_ASCENT): with self.subTest(car=car): @@ -211,7 +211,7 @@ class TestSubaruAscentController(unittest.TestCase): for tick in range(5): _, sends = controller.update(command.as_reader(), state, 1_000_000_000 + tick * 10_000_000) distance.extend(frame for frame in sends if frame[0] == 0x221) - self.assertEqual(len(distance), 1 if car == CAR.SUBARU_ASCENT_2023 else 5) + self.assertEqual(len(distance), 1 if car in (CAR.SUBARU_ASCENT_2023, CAR.SUBARU_LEGACY_2025) else 5) self.assertEqual(len(set(distance)), 1) self.assertEqual(distance[0][2], 1 if cp.flags & SubaruFlags.GLOBAL_GEN2 else 0) diff --git a/opendbc_repo/opendbc/car/subaru/tests/test_ascent_lkas_alert.py b/opendbc_repo/opendbc/car/subaru/tests/test_ascent_lkas_alert.py index e86d7065be..a5cb77744c 100644 --- a/opendbc_repo/opendbc/car/subaru/tests/test_ascent_lkas_alert.py +++ b/opendbc_repo/opendbc/car/subaru/tests/test_ascent_lkas_alert.py @@ -18,13 +18,14 @@ class TestAscentLkasAlert(unittest.TestCase): def test_platform_bus_length_gate_preserves_native_identity(self): for car in CAR: cp = self.params(car) - self.assertEqual(bool(cp.flags & SubaruFlags.ASCENT_LKAS_ALERT), car == CAR.SUBARU_ASCENT_2023) + self.assertEqual(bool(cp.flags & SubaruFlags.ASCENT_LKAS_ALERT), car in (CAR.SUBARU_ASCENT_2023, CAR.SUBARU_LEGACY_2025)) self.assertEqual(bool(cp.safetyConfigs[0].safetyParam & SubaruSafetyFlags.ASCENT_LKAS_ALERT), car == CAR.SUBARU_ASCENT_2023) for bus, length in ((0, 8), (1, 8), (2, 4), (2, 16)): cp = self.params(bus=bus, length=length) self.assertFalse(cp.flags & SubaruFlags.ASCENT_LKAS_ALERT) self.assertEqual(cp.safetyConfigs[0].safetyParam, 0xB1) self.assertEqual(self.params().safetyConfigs[0].safetyParam, 0x8B1) + self.assertEqual(self.params(CAR.SUBARU_LEGACY_2025).safetyConfigs[0].safetyParam, 0x91) def test_production_parser_state_controller_and_actual_request(self): cp = self.params() @@ -66,3 +67,29 @@ class TestAscentLkasAlert(unittest.TestCase): self.assertEqual(subarucan.create_ascent_lkas_alert(bytes(dat), True, 0)[1], dat) for dat in (b"", bytes(7), bytes(9), bytes.fromhex("0002000104000000")): self.assertIsNone(subarucan.create_ascent_lkas_alert(dat, True, 0)) + + def test_legacy_2025_alert_suppression_and_lead_restore(self): + def packet(hex_tail: str): + dat = bytearray(bytes.fromhex("0002" + hex_tail)) + dat[0] = (0xC4 + 3 + sum(dat[1:])) & 0xFF + return bytes(dat) + + for payload in ("000104000000", "1c0704000000", "000704000000", "1e0030000000", "1b0000000000", "000002000000"): + raw = packet(payload) + self.assertEqual(subarucan.create_ascent_lkas_alert(raw, False, 0, armed=True, legacy_2025=True)[1], raw) + msg = subarucan.create_ascent_lkas_alert(raw, True, 0, armed=True, acc_lead_visible=False, legacy_2025=True) + self.assertEqual(msg[1][2:5], b"\x00\x00\x00", payload) + self.assertEqual(msg[1][0], (0xC4 + 3 + sum(msg[1][1:])) & 0xFF) + + # Restore green ACC lead-car LED (dat[5] = 0x01) when tracking a lead and background alert cleared it. + msg = subarucan.create_ascent_lkas_alert(packet("000104000000"), True, 0, armed=True, acc_lead_visible=True, legacy_2025=True) + self.assertEqual(msg[1][2:], bytes.fromhex("000000010000")) + + # Native LDW (0x0b, 0x0c) and openpilot steerRequired (000104000000) work cleanly. + ldw = packet("0b0000010000") + self.assertEqual(subarucan.create_ascent_lkas_alert(ldw, True, 0, armed=True, legacy_2025=True)[1], ldw) + hands_on = subarucan.create_ascent_lkas_alert( + packet("000000010000"), False, structs.CarControl.HUDControl.VisualAlert.steerRequired, + armed=True, legacy_2025=True, + ) + self.assertEqual(hands_on[1][2:], bytes.fromhex("000104000000")) diff --git a/opendbc_repo/opendbc/car/subaru/tests/test_avh.py b/opendbc_repo/opendbc/car/subaru/tests/test_avh.py index 5cf75113d1..d348b6c526 100644 --- a/opendbc_repo/opendbc/car/subaru/tests/test_avh.py +++ b/opendbc_repo/opendbc/car/subaru/tests/test_avh.py @@ -34,20 +34,30 @@ def test_captured_legacy_press_bytes(): template = bytes.fromhex('5b0b000100800e00') assert avh_request(template, 1) == (0x6BB, bytes.fromhex('5e0c020100800e00'), 1) assert avh_request(template, 2) == (0x6BB, bytes.fromhex('5f0d020100800e00'), 1) + assert avh_request(template, 3) == (0x6BB, bytes.fromhex('600e020100800e00'), 1) + assert avh_request(template, 4) == (0x6BB, bytes.fromhex('610f020100800e00'), 1) wrap = sample(AVH_REQUEST, 15) assert avh_request(wrap, 1)[1][1] == 0 assert avh_request(wrap, 2)[1][1] == 1 + assert avh_request(wrap, 3)[1][1] == 2 + assert avh_request(wrap, 4)[1][1] == 3 -def test_two_frames_only_and_no_retry(): +def test_four_frames_only_and_no_retry(): policy, frames = prepare() assert policy.update(110.04, frames, True, True, False) == [] assert policy.update(110.06, frames, True, True, False) == [avh_request(frames[AVH_REQUEST][1], 2)] - assert policy.update(110.07, frames, True, True, False) == [] + assert policy.update(110.10, frames, True, True, False) == [] + assert policy.update(110.12, frames, True, True, False) == [avh_request(frames[AVH_REQUEST][1], 3)] + assert policy.update(110.16, frames, True, True, False) == [] + assert policy.update(110.18, frames, True, True, False) == [avh_request(frames[AVH_REQUEST][1], 4)] + assert policy.update(110.20, frames, True, True, False) == [] assert policy.update(111, frames, True, True, False) == [] def test_controller_snapshots_may_skip_fast_can_samples(): policy, frames = prepare(fast_counter_step=2) assert policy.update(110.06, frames, True, True, False) == [avh_request(frames[AVH_REQUEST][1], 2)] + assert policy.update(110.12, frames, True, True, False) == [avh_request(frames[AVH_REQUEST][1], 3)] + assert policy.update(110.18, frames, True, True, False) == [avh_request(frames[AVH_REQUEST][1], 4)] @pytest.mark.parametrize('reason', ['late','new_template','manual','ack','moving','gas','gear','invalid','disabled','engaged','stale']) def test_followup_aborts_permanently(reason): @@ -69,3 +79,53 @@ def test_followup_aborts_permanently(reason): assert policy.update(now, frames, reason != 'disabled', reason != 'invalid', reason == 'engaged') == [] assert policy.done assert policy.update(111, frames, True, True, False) == [] + + +def test_skips_state_change_and_50ms_burst_waits_for_steady_heartbeat(): + policy = AvhStartup() + frames = {} + counter = 0 + fast_counter = 0 + for tick in range(100): + now = 100.0 + tick / 10 + fast_counter = tick + for address in INPUTS: + if address != AVH_REQUEST or tick % 10 == 0: + if address == AVH_REQUEST: + counter += 1 + c = counter if address == AVH_REQUEST else fast_counter + frames[address] = (now, sample(address, c)) + assert policy.update(now, frames, True, True, False) == [] + + # Event transition (byte 6 changes) -> 1st burst frame at 109.95s, then 50ms burst at 110.00, 110.05, 110.10 (10s met mid-burst). + for offset, changed in ((109.95, True), (110.00, False), (110.05, False), (110.10, False)): + counter += 1 + fast_counter += 1 + data = bytearray(sample(AVH_REQUEST, counter)) + data[6] = 0x0F if changed else 0x0E + data[0] = checksum(AVH_REQUEST, data) + frames[AVH_REQUEST] = (offset, bytes(data)) + for address in INPUTS: + if address != AVH_REQUEST: + frames[address] = (offset, sample(address, fast_counter)) + assert policy.update(offset, frames, True, True, False) == [] + assert not policy.done + + # Wait past 1.20s at 100ms ticks so configured/stable continuity stays intact, then send steady heartbeat at 111.30s. + for tick in range(1, 12): + now = 110.10 + tick * 0.10 + fast_counter += 1 + for address in INPUTS: + if address != AVH_REQUEST: + frames[address] = (now, sample(address, fast_counter)) + assert policy.update(now, frames, True, True, False) == [] + + counter += 1 + fast_counter += 1 + for address in INPUTS: + frames[address] = (111.30, sample(address, counter if address == AVH_REQUEST else fast_counter)) + assert policy.update(111.30, frames, True, True, False) == [avh_request(frames[AVH_REQUEST][1], 1)] + assert policy.update(111.36, frames, True, True, False) == [avh_request(frames[AVH_REQUEST][1], 2)] + assert policy.update(111.42, frames, True, True, False) == [avh_request(frames[AVH_REQUEST][1], 3)] + assert policy.update(111.48, frames, True, True, False) == [avh_request(frames[AVH_REQUEST][1], 4)] + assert policy.done diff --git a/opendbc_repo/opendbc/car/subaru/tests/test_legacy_2025_aol.py b/opendbc_repo/opendbc/car/subaru/tests/test_legacy_2025_aol.py new file mode 100644 index 0000000000..597ec5dca4 --- /dev/null +++ b/opendbc_repo/opendbc/car/subaru/tests/test_legacy_2025_aol.py @@ -0,0 +1,540 @@ +import unittest + +from opendbc.can import CANPacker, CANParser +from opendbc.car import Bus, structs +from opendbc.car.subaru import subarucan +from opendbc.car.subaru.carcontroller import CarController +from opendbc.car.subaru.carstate import CarState +from opendbc.car.subaru.interface import CarInterface +from opendbc.car.subaru.tests.test_ascent_angle import setup_controller, step +from opendbc.car.subaru.values import CAR, CanBus, DBC +from opendbc.safety.tests import test_subaru_gen2_angle_pair as pair + + +def _step_to_hud(controller, command, state): + while controller.frame % 10 != 0: + controller.update(command.as_reader(), state, 1_000_000_000 + controller.frame * 10_000_000) + _, sends = controller.update(command.as_reader(), state, 1_000_000_000 + controller.frame * 10_000_000) + hud = next(frame for frame in sends if frame[0] == 0x322) + parser = CANParser(DBC[controller.CP.carFingerprint][Bus.pt], [('ES_LKAS_State', 0)], hud[2]) + parser.update([(1, [hud])]) + return parser.vl['ES_LKAS_State'] + + +class TestLegacy2025Aol(unittest.TestCase): + def test_lkas_dash_state_toggle_emits_button_event_and_toggles_aol(self): + cp = CarInterface.get_params(CAR.SUBARU_LEGACY_2025, {0: {}, 1: {}, 2: {}}, [], False, False, False) + _, frames = pair.TestSubaruGen2AnglePair.sources(CAR.SUBARU_LEGACY_2025) + packer = CANPacker(DBC[CAR.SUBARU_LEGACY_2025][Bus.pt]) + state = CarState(cp) + self.assertTrue(state.aol_enabled) + parsers = state.get_can_parsers(cp) + state.update(parsers) + for parser in parsers.values(): + parser.update([(1_000_000_000, frames)]) + ret = state.update(parsers) + self.assertTrue(ret.cruiseState.available) + self.assertFalse(state.lateral_off) + self.assertEqual(len(ret.buttonEvents), 0) + + # Flip LKAS_Dash_State (0 -> 1) on bus 2: toggles AOL off once and holds Type.lkas press/release for 5 frames. + lkas_on = packer.make_can_msg('ES_LKAS_State', CanBus.camera, {'LKAS_Dash_State': 1}) + parsers[Bus.cam].update([(1_020_000_000, [lkas_on])]) + ret = state.update(parsers) + self.assertTrue(state.lateral_off) + lkas_events = [be for be in ret.buttonEvents if be.type == structs.CarState.ButtonEvent.Type.lkas] + self.assertEqual([be.pressed for be in lkas_events], [True, False]) + for idx in range(4): + ret = state.update(parsers) + self.assertTrue(state.lateral_off) + lkas_events = [be for be in ret.buttonEvents if be.type == structs.CarState.ButtonEvent.Type.lkas] + self.assertEqual([be.pressed for be in lkas_events], [True, False], f"hold frame {idx + 2}") + ret = state.update(parsers) + self.assertTrue(state.lateral_off) + self.assertEqual([be for be in ret.buttonEvents if be.type == structs.CarState.ButtonEvent.Type.lkas], []) + + # Flip LKAS_Dash_State (1 -> 0): restores AOL active cleanly. + lkas_off = packer.make_can_msg('ES_LKAS_State', CanBus.camera, {'LKAS_Dash_State': 0}) + parsers[Bus.cam].update([(1_040_000_000, [lkas_off])]) + ret = state.update(parsers) + self.assertFalse(state.lateral_off) + + # Toggle off, then drop Cruise_On -> lateral_off resets to False when AOL is enabled. + parsers[Bus.cam].update([(1_060_000_000, [lkas_on])]) + state.update(parsers) + self.assertTrue(state.lateral_off) + dash_off = packer.make_can_msg('ES_DashStatus', CanBus.camera, {'Cruise_On': 0}) + parsers[Bus.cam].update([(1_080_000_000, [dash_off])]) + state.update(parsers) + self.assertFalse(state.lateral_off) + + def test_aol_mode_transitions_and_lkas_button_behavior(self): + cp = CarInterface.get_params(CAR.SUBARU_LEGACY_2025, {0: {}, 1: {}, 2: {}}, [], False, False, False) + _, frames = pair.TestSubaruGen2AnglePair.sources(CAR.SUBARU_LEGACY_2025) + packer = CANPacker(DBC[CAR.SUBARU_LEGACY_2025][Bus.pt]) + + def init_state(aol_enabled: bool): + state = CarState(cp) + state.aol_enabled = aol_enabled + parsers = state.get_can_parsers(cp) + state.update(parsers) + for parser in parsers.values(): + parser.update([(1_000_000_000, frames)]) + state.update(parsers) + return state, parsers + + def press_lkas(state, parsers, ts_ns: int, dash_state: int): + msg = packer.make_can_msg('ES_LKAS_State', CanBus.camera, {'LKAS_Dash_State': dash_state}) + parsers[Bus.cam].update([(ts_ns, [msg])]) + return state.update(parsers) + + # 1. AOL ON: AOL Active <-> AOL Off. + state, parsers = init_state(True) + self.assertFalse(state.lateral_off) + press_lkas(state, parsers, 1_020_000_000, 1) + self.assertTrue(state.lateral_off) + press_lkas(state, parsers, 1_040_000_000, 0) + self.assertFalse(state.lateral_off) + + # 2. AOL OFF: forced Off even after LKAS presses. + state, parsers = init_state(False) + self.assertTrue(state.lateral_off) + press_lkas(state, parsers, 1_020_000_000, 1) + self.assertTrue(state.lateral_off) + + # 3. Dynamic transitions across AOL settings changes. + state, parsers = init_state(True) + self.assertFalse(state.lateral_off) + state.aol_enabled = False + state.update(parsers) + self.assertTrue(state.lateral_off) + state.aol_enabled = True + state.update(parsers) + self.assertFalse(state.lateral_off) + + def test_carcontroller_dash_state_and_steering_across_lateral_modes(self): + _, controller, command, state = setup_controller(CAR.SUBARU_LEGACY_2025) + state.out.cruiseState.available = True + state.out.gearShifter = structs.CarState.GearShifter.drive + state.out.vEgo = 20.0 + state.out.standstill = False + + # AOL active -> LKAS_Dash_State == 2, lines visible, and ES_LKAS_ANGLE LKAS_Request == 1. + state.aol_enabled = True + state.lateral_off = False + command.enabled = True + command.latActive = True + command.hudControl.lanesVisible = True + command.hudControl.leftLaneVisible = True + command.hudControl.rightLaneVisible = True + command.actuators.steeringAngleDeg = 10.0 + _, angle = step(controller, command, state) + self.assertEqual(angle['LKAS_Request'], 1) + hud = _step_to_hud(controller, command, state) + self.assertEqual(hud['LKAS_Dash_State'], 2) + self.assertEqual(hud['LKAS_Left_Line_Visible'], 1) + self.assertEqual(hud['LKAS_Right_Line_Visible'], 1) + + # lateral_off with AOL toggle ON -> LKAS_Dash_State == 1 (white ready wheel), NO lines, and LKAS_Request == 0. + state.lateral_off = True + state.aol_enabled = True + command.hudControl.lanesVisible = False + _, angle = step(controller, command, state) + self.assertEqual(angle['LKAS_Request'], 0) + hud = _step_to_hud(controller, command, state) + self.assertEqual(hud['LKAS_Dash_State'], 1) + self.assertEqual(hud['LKAS_Left_Line_Visible'], 0) + self.assertEqual(hud['LKAS_Right_Line_Visible'], 0) + + # AOL toggle OFF while not engaged -> LKAS_Dash_State == 0 (wheel off) and NO lines (even before lateral_off syncs). + state.aol_enabled = False + state.lateral_off = False + command.enabled = False + command.latActive = False + command.hudControl.lanesVisible = False + _, angle = step(controller, command, state) + self.assertEqual(angle['LKAS_Request'], 0) + hud = _step_to_hud(controller, command, state) + self.assertEqual(hud['LKAS_Dash_State'], 0) + self.assertEqual(hud['LKAS_Left_Line_Visible'], 0) + self.assertEqual(hud['LKAS_Right_Line_Visible'], 0) + + # AOL toggle OFF with ACC engaged (even when state.lateral_off is still True) -> steers + green wheel + lines. + state.lateral_off = True + command.enabled = True + command.latActive = True + command.hudControl.lanesVisible = True + _, angle = step(controller, command, state) + self.assertEqual(angle['LKAS_Request'], 1) + hud = _step_to_hud(controller, command, state) + self.assertEqual(hud['LKAS_Dash_State'], 2) + self.assertEqual(hud['LKAS_Left_Line_Visible'], 1) + + # Main cruise OFF -> LKAS_Dash_State == 0 (wheel icon off) even with AOL toggle ON. + state.aol_enabled = True + state.out.cruiseState.available = False + hud = _step_to_hud(controller, command, state) + self.assertEqual(hud['LKAS_Dash_State'], 0) + + def test_lkas_button_hold_survives_conflation_and_keeps_dash_wheel_in_sync(self): + cp, controller, command, state = setup_controller(CAR.SUBARU_LEGACY_2025) + _, frames = pair.TestSubaruGen2AnglePair.sources(CAR.SUBARU_LEGACY_2025) + packer = CANPacker(DBC[CAR.SUBARU_LEGACY_2025][Bus.pt]) + state.aol_enabled = True + parsers = state.get_can_parsers(cp) + state.update(parsers) + for parser in parsers.values(): + parser.update([(1_000_000_000, frames)]) + state.update(parsers) + self.assertFalse(state.lateral_off) + + controlsd_lateral_off = False + prev_lkas_pressed = False + + def step_controlsd_from_ret(car_state): + nonlocal controlsd_lateral_off, prev_lkas_pressed + raw_pressed = any( + be.type == structs.CarState.ButtonEvent.Type.lkas and be.pressed + for be in car_state.buttonEvents + ) + if not car_state.cruiseState.available: + prev_lkas_pressed = False + lkas_pressed = raw_pressed and not prev_lkas_pressed + prev_lkas_pressed = raw_pressed + if lkas_pressed: + controlsd_lateral_off = not controlsd_lateral_off + + # 1. Press LKAS (0 -> 1): simulate SubMaster dropping the first two carState frames. + parsers[Bus.cam].update([(1_020_000_000, [packer.make_can_msg('ES_LKAS_State', CanBus.camera, {'LKAS_Dash_State': 1})])]) + cs_frames = [state.update(parsers) for _ in range(6)] + self.assertEqual([any(be.type == structs.CarState.ButtonEvent.Type.lkas for be in f.buttonEvents) for f in cs_frames], + [True, True, True, True, True, False]) + self.assertTrue(state.lateral_off) + for f in cs_frames[2:]: + step_controlsd_from_ret(f) + self.assertTrue(controlsd_lateral_off) + self.assertEqual(state.lateral_off, controlsd_lateral_off) + + # With AOL toggled off, wheel icon must stay white (1) with no lane lines and no steering request. + state.out.cruiseState.available = True + state.out.gearShifter = structs.CarState.GearShifter.drive + state.out.vEgo = 20.0 + state.out.standstill = False + command.enabled = False + command.latActive = True + command.hudControl.lanesVisible = False + command.hudControl.leftLaneVisible = True + command.actuators.steeringAngleDeg = -8.0 + _, decoded = step(controller, command, state) + self.assertEqual(decoded['LKAS_Request'], 0) + hud = _step_to_hud(controller, command, state) + self.assertEqual(hud['LKAS_Dash_State'], 1) + self.assertEqual(hud['LKAS_Left_Line_Visible'], 0) + + # 2. Press LKAS (1 -> 0) back to AOL: again drop first two carState frames via conflation. + parsers[Bus.cam].update([(1_100_000_000, [packer.make_can_msg('ES_LKAS_State', CanBus.camera, {'LKAS_Dash_State': 0})])]) + cs_frames_2 = [state.update(parsers) for _ in range(6)] + self.assertEqual([any(be.type == structs.CarState.ButtonEvent.Type.lkas for be in f.buttonEvents) for f in cs_frames_2], + [True, True, True, True, True, False]) + self.assertFalse(state.lateral_off) + for f in cs_frames_2[2:]: + step_controlsd_from_ret(f) + self.assertFalse(controlsd_lateral_off) + self.assertEqual(state.lateral_off, controlsd_lateral_off) + + # In AOL mode with active steering, wheel icon turns back to green (2) and lines reappear. + command.enabled = True + command.latActive = True + command.hudControl.lanesVisible = True + command.actuators.steeringAngleDeg = 8.0 + _, decoded = step(controller, command, state) + self.assertEqual(decoded['LKAS_Request'], 1) + hud = _step_to_hud(controller, command, state) + self.assertEqual(hud['LKAS_Dash_State'], 2) + self.assertEqual(hud['LKAS_Left_Line_Visible'], 1) + + def test_carcontroller_aol_green_wheel_park_override_and_alerts(self): + _, controller, command, state = setup_controller(CAR.SUBARU_LEGACY_2025) + state.out.cruiseState.available = True + state.out.gearShifter = structs.CarState.GearShifter.park + state.out.vEgo = 0.0 + state.out.standstill = True + state.aol_enabled = True + + # AOL active in Park / standstill (latActive=False, lanesVisible=True) -> green wheel icon (2). + state.lateral_off = False + command.enabled = False + command.latActive = False + command.hudControl.lanesVisible = True + hud = _step_to_hud(controller, command, state) + self.assertEqual(hud['LKAS_Dash_State'], 2) + + # Toggle LKAS off in Park -> immediately drops to white wheel icon (1). + state.lateral_off = True + command.hudControl.lanesVisible = False + hud = _step_to_hud(controller, command, state) + self.assertEqual(hud['LKAS_Dash_State'], 1) + + # steerRequired visual alert maps to Keep Hands On Wheel message (1) cleanly on 0x322. + command.hudControl.visualAlert = structs.CarControl.HUDControl.VisualAlert.steerRequired + command.hudControl.audibleAlert = structs.CarControl.HUDControl.AudibleAlert.none + hud = _step_to_hud(controller, command, state) + self.assertEqual(hud['LKAS_Alert_Msg'], 1) + self.assertEqual(hud['LKAS_Alert'], 0) + command.hudControl.visualAlert = structs.CarControl.HUDControl.VisualAlert.none + hud = _step_to_hud(controller, command, state) + self.assertEqual(hud['LKAS_Alert_Msg'], 0) + self.assertEqual(hud['LKAS_Alert'], 0) + + # Driving in AOL / full OP: active steering -> green (2), manual override -> white (1), resume -> green (2). + state.lateral_off = False + state.out.gearShifter = structs.CarState.GearShifter.drive + state.out.vEgo = 20.0 + state.out.vEgoRaw = 20.0 + state.out.standstill = False + command.enabled = True + command.latActive = True + command.hudControl.lanesVisible = True + state.out.steeringTorque = 0.0 + state.out.steeringRateDeg = 0.0 + state.out.steeringPressed = False + _, decoded = step(controller, command, state) + self.assertEqual(decoded['LKAS_Request'], 1) + hud = _step_to_hud(controller, command, state) + self.assertEqual(hud['LKAS_Dash_State'], 2) + + # Driver manually overrides steering -> wheel icon turns white (1). + state.out.steeringTorque = 250.0 + state.out.steeringRateDeg = 30.0 + state.out.steeringPressed = True + step(controller, command, state) + _, decoded = step(controller, command, state) + self.assertEqual(decoded['LKAS_Request'], 0) + hud = _step_to_hud(controller, command, state) + self.assertEqual(hud['LKAS_Dash_State'], 1) + + # Driver releases wheel -> openpilot resumes control and wheel icon turns back to green (2). + state.out.steeringTorque = 0.0 + state.out.steeringRateDeg = 0.0 + state.out.steeringPressed = False + step(controller, command, state) + _, decoded = step(controller, command, state) + self.assertEqual(decoded['LKAS_Request'], 1) + hud = _step_to_hud(controller, command, state) + self.assertEqual(hud['LKAS_Dash_State'], 2) + + # Stock EyeSight LDW / allowed alert takes priority over steerRequired alert. + state.es_lkas_state_msg["LKAS_Alert"] = 12 + command.hudControl.visualAlert = structs.CarControl.HUDControl.VisualAlert.steerRequired + hud = _step_to_hud(controller, command, state) + self.assertEqual(hud['LKAS_Alert'], 12) + self.assertEqual(hud['LKAS_Alert_Msg'], 0) + + dbc = DBC[CAR.SUBARU_LEGACY_2025][Bus.pt] + packer = CANPacker(dbc) + info_parser = CANParser(dbc, [('ES_Infotainment', 0)], CanBus.main) + info_msg = subarucan.create_es_infotainment( + packer, 0, {'CHECKSUM': 0, 'LKAS_State_Infotainment': 1, 'LKAS_Blue_Lines': 0, 'Signal1': 0, 'Signal2': 0}, + structs.CarControl.HUDControl.VisualAlert.steerRequired, + legacy_2025=True, + ) + info_parser.update([(1, [info_msg])]) + self.assertEqual(info_parser.vl['ES_Infotainment']['LKAS_State_Infotainment'], 1) + + for audible, expected in ( + (structs.CarControl.HUDControl.AudibleAlert.none, 3), + (structs.CarControl.HUDControl.AudibleAlert.warningSoft, 3), + (structs.CarControl.HUDControl.AudibleAlert.warningImmediate, 4), + ): + info_msg = subarucan.create_es_infotainment( + packer, 1, {'CHECKSUM': 0, 'LKAS_State_Infotainment': 0, 'LKAS_Blue_Lines': 0, 'Signal1': 0, 'Signal2': 0}, + structs.CarControl.HUDControl.VisualAlert.steerRequired, + audible_alert=audible, + legacy_2025=True, + ) + info_parser.update([(2, [info_msg])]) + self.assertEqual(info_parser.vl['ES_Infotainment']['LKAS_State_Infotainment'], expected) + + # Non-Legacy default (legacy_2025=False) preserves exact upstream 0x323 behavior. + for stock_state in (0, 1): + info_msg = subarucan.create_es_infotainment( + packer, 2, {'CHECKSUM': 0, 'LKAS_State_Infotainment': stock_state, 'LKAS_Blue_Lines': 0, 'Signal1': 0, 'Signal2': 0}, + structs.CarControl.HUDControl.VisualAlert.steerRequired, + audible_alert=structs.CarControl.HUDControl.AudibleAlert.warningImmediate, + ) + info_parser.update([(3, [info_msg])]) + self.assertEqual(info_parser.vl['ES_Infotainment']['LKAS_State_Infotainment'], 3) + + def test_carcontroller_aol_manumatic_and_unauthorized_gate(self): + cp, _, command, state = setup_controller(CAR.SUBARU_LEGACY_2025) + cp.alternativeExperience = 32 + controller = CarController(DBC[CAR.SUBARU_LEGACY_2025], cp) + state.out.gearShifter = structs.CarState.GearShifter.manumatic + state.lateral_off = False + state.out.steeringAngleDeg = 0.0 + state.out.steeringRateDeg = 0.0 + state.out.steeringTorque = 0.0 + + # Active AOL in manumatic: angle requested, green wheel icon (2), visible left line (1). + command.enabled = False + command.latActive = True + command.hudControl.lanesVisible = True + command.hudControl.leftLaneVisible = True + command.hudControl.rightLaneVisible = False + command.actuators.steeringAngleDeg = -8.0 + _, decoded = step(controller, command, state) + self.assertEqual(decoded['LKAS_Request'], 1) + self.assertLess(decoded['LKAS_Output'], 0.0) + hud = _step_to_hud(controller, command, state) + self.assertEqual(hud['LKAS_Dash_State'], 2) + self.assertEqual(hud['LKAS_Left_Line_Visible'], 1) + + # Unauthorized gate: when controlsd keeps latActive=False, CarController must never request 0x124 torque/angle. + command.latActive = False + _, decoded = step(controller, command, state) + self.assertEqual(decoded['LKAS_Request'], 0) + _, decoded = step(controller, command, state) + self.assertEqual(decoded['LKAS_Request'], 0) + + def test_legacy_2025_manumatic_transition_and_between_detent_gears(self): + cp = CarInterface.get_params(CAR.SUBARU_LEGACY_2025, {0: {}, 1: {}, 2: {}}, [], False, False, False) + _, frames = pair.TestSubaruGen2AnglePair.sources(CAR.SUBARU_LEGACY_2025) + packer = CANPacker(DBC[CAR.SUBARU_LEGACY_2025][Bus.pt]) + state = CarState(cp) + parsers = state.get_can_parsers(cp) + state.update(parsers) + for parser in parsers.values(): + parser.update([(1_000_000_000, frames)]) + state.update(parsers) + + Gear = structs.CarState.GearShifter + for can_gear, expected_gear in ((121, Gear.drive), (129, Gear.manumatic), (177, Gear.manumatic), (0, Gear.neutral), (4, Gear.park)): + msg = packer.make_can_msg('Transmission', 0, {'Gear': can_gear}) + parsers[Bus.pt].update([(1_020_000_000, [msg])]) + ret = state.update(parsers) + self.assertEqual(ret.gearShifter, expected_gear, f'can_gear={can_gear}') + + def test_legacy_2025_acc_lead_led_preserved_and_aol_line_visibility_passthrough(self): + _, _, command, state = setup_controller(CAR.SUBARU_LEGACY_2025) + cp = CarInterface.get_params(CAR.SUBARU_LEGACY_2025, {0: {}, 1: {}, 2: {0x3C4: 8}}, [], False, False, False) + controller = CarController(DBC[CAR.SUBARU_LEGACY_2025], cp) + state.out.cruiseState.available = True + state.out.gearShifter = structs.CarState.GearShifter.drive + state.out.vEgo = 20.0 + state.out.standstill = False + + controller.angle_was_active = True + command.enabled = command.latActive = True + # Stock ACC active via Cruise_Activated_Dash + Car_Follow (not gasPressed) preserves dat[5]=0x01 when masking 000104000000. + state.out.cruiseState.enabled = True + state.out.gasPressed = False + state.es_dashstatus_msg.update({'Cruise_Activated_Dash': 1, 'Cruise_State': 0, 'Car_Follow': 1}) + raw = bytearray(bytes.fromhex('0002000104000000')) + raw[0] = (0xC4 + 3 + sum(raw[1:])) & 0xFF + state.es_lkas_alert_dat = bytes(raw) + msg = controller._ascent_lkas_alert(command.as_reader(), state) + self.assertIsNotNone(msg) + self.assertEqual(msg[1][2:], bytes.fromhex('000000010000')) + + # Gas pedal override clears green lead LED (dat[5] = 0x00) even when cruiseState.enabled and Car_Follow remain set. + for idx, override_fields in enumerate(( + {'gas': True, 'dash': 1, 'cstate': 0}, + {'gas': False, 'dash': 0, 'cstate': 2}, + )): + state.out.gasPressed = override_fields['gas'] + state.es_dashstatus_msg.update({ + 'Cruise_Activated_Dash': override_fields['dash'], + 'Cruise_State': override_fields['cstate'], + 'Car_Follow': 1, + }) + raw[1] = 0x03 + idx + raw[0] = (0xC4 + 3 + sum(raw[1:])) & 0xFF + state.es_lkas_alert_dat = bytes(raw) + msg = controller._ascent_lkas_alert(command.as_reader(), state) + self.assertIsNotNone(msg) + self.assertEqual(msg[1][2:], bytes.fromhex('000000000000'), override_fields) + state.out.gasPressed = False + state.es_dashstatus_msg.update({'Cruise_Activated_Dash': 1, 'Cruise_State': 0}) + + # Without Car_Follow, dat[5] stays 0x00 when masking the alert. + state.es_dashstatus_msg.update({'Cruise_Activated_Dash': 1, 'Cruise_State': 0, 'Car_Follow': 0}) + raw[1] = 0x05 + raw[0] = (0xC4 + 3 + sum(raw[1:])) & 0xFF + state.es_lkas_alert_dat = bytes(raw) + msg = controller._ascent_lkas_alert(command.as_reader(), state) + self.assertIsNotNone(msg) + self.assertEqual(msg[1][2:], bytes.fromhex('000000000000')) + + # A controller handoff restores the stock red HUD notification. + controller.angle_was_active = False + raw = bytearray(bytes.fromhex('00061e0030000000')) + raw[0] = (0xC4 + 3 + sum(raw[1:])) & 0xFF + state.es_lkas_alert_dat = bytes(raw) + self.assertEqual(controller._ascent_lkas_alert(command.as_reader(), state)[1], raw) + + # AOL mode passes debounced hudControl lane visibility directly through to cluster CAN. + state.lateral_off = False + command.enabled = False + command.latActive = True + command.hudControl.lanesVisible = True + command.hudControl.leftLaneVisible = True + command.hudControl.rightLaneVisible = True + hud = _step_to_hud(controller, command, state) + self.assertEqual(hud['LKAS_Left_Line_Visible'], 1) + self.assertEqual(hud['LKAS_Right_Line_Visible'], 1) + + command.hudControl.leftLaneVisible = False + hud = _step_to_hud(controller, command, state) + self.assertEqual(hud['LKAS_Left_Line_Visible'], 0) + self.assertEqual(hud['LKAS_Right_Line_Visible'], 1) + + command.hudControl.leftLaneVisible = True + hud = _step_to_hud(controller, command, state) + self.assertEqual(hud['LKAS_Left_Line_Visible'], 1) + + def test_aol_wheel_icon_park_reverse_neutral_and_shift_debounce(self): + _, controller, command, state = setup_controller(CAR.SUBARU_LEGACY_2025) + state.out.cruiseState.available = True + state.out.vEgo = 0.0 + state.out.vEgoRaw = 0.0 + state.out.standstill = True + state.aol_enabled = True + state.lateral_off = False + command.enabled = False + command.latActive = False + command.hudControl.lanesVisible = True + + # In Park: stays solid green even if steering wheel is moved slightly. + state.out.gearShifter = structs.CarState.GearShifter.park + state.out.steeringPressed = True + self.assertEqual(_step_to_hud(controller, command, state)['LKAS_Dash_State'], 2) + + # Fast Park -> Reverse -> Neutral -> Drive shift (< 0.8s) holds green without flashing white. + state.out.steeringPressed = False + for gear, steps in ( + (structs.CarState.GearShifter.reverse, 3), + (structs.CarState.GearShifter.neutral, 3), + ): + state.out.gearShifter = gear + for _ in range(steps): + self.assertEqual(_step_to_hud(controller, command, state)['LKAS_Dash_State'], 2) + state.out.gearShifter = structs.CarState.GearShifter.drive + self.assertEqual(_step_to_hud(controller, command, state)['LKAS_Dash_State'], 2) + + # Settling in Reverse (>= 0.8s) switches to solid white regardless of steering input. + state.out.gearShifter = structs.CarState.GearShifter.reverse + for _ in range(9): + hud = _step_to_hud(controller, command, state) + self.assertEqual(hud['LKAS_Dash_State'], 1) + state.out.steeringPressed = True + self.assertEqual(_step_to_hud(controller, command, state)['LKAS_Dash_State'], 1) + state.out.gearShifter = structs.CarState.GearShifter.neutral + self.assertEqual(_step_to_hud(controller, command, state)['LKAS_Dash_State'], 1) + + # Returning to Park restores solid green cleanly. + state.out.gearShifter = structs.CarState.GearShifter.park + self.assertEqual(_step_to_hud(controller, command, state)['LKAS_Dash_State'], 2) + + +if __name__ == '__main__': + unittest.main() diff --git a/opendbc_repo/opendbc/car/subaru/tests/test_output_contract.py b/opendbc_repo/opendbc/car/subaru/tests/test_output_contract.py index 11197a48bd..4271026725 100644 --- a/opendbc_repo/opendbc/car/subaru/tests/test_output_contract.py +++ b/opendbc_repo/opendbc/car/subaru/tests/test_output_contract.py @@ -71,9 +71,13 @@ def test_dash_uses_current_request_without_mutating_physical_template(car, enabl if any(frame[0] == 0x322 for frame in sends): expected = controller.angle_was_active if car in ANGLE_CARS else (lat_active if marked else enabled) dash = decoder.vl['ES_LKAS_State'] - if car in ANGLE_CARS or marked or enabled: - assert bool(dash['LKAS_ACTIVE']) == expected - assert dash['LKAS_Dash_State'] == (2 if expected else 0) + if car == CAR.SUBARU_LEGACY_2025: + assert bool(dash['LKAS_ACTIVE']) + assert dash['LKAS_Dash_State'] == (2 if expected else (1 if state.out.cruiseState.available else 0)) + else: + if car in ANGLE_CARS or marked or enabled: + assert bool(dash['LKAS_ACTIVE']) == expected + assert dash['LKAS_Dash_State'] == (2 if expected else 0) assert state.es_lkas_state_msg == original checked += 1 assert checked == 5 diff --git a/opendbc_repo/opendbc/car/subaru/values.py b/opendbc_repo/opendbc/car/subaru/values.py index 496160b0c0..dc7b2b03c1 100644 --- a/opendbc_repo/opendbc/car/subaru/values.py +++ b/opendbc_repo/opendbc/car/subaru/values.py @@ -71,6 +71,7 @@ class SubaruSafetyFlags(IntFlag): GEN2 = 1 LONG = 2 PREGLOBAL_REVERSED_DRIVER_TORQUE = 4 + PREGLOBAL_OUTBACK_STOCK_ACC = 8 LKAS_ANGLE = 16 D_PLATFORM = 64 FIXED_ANGLE_LIMITS = 128 diff --git a/opendbc_repo/opendbc/car/toyota/interface.py b/opendbc_repo/opendbc/car/toyota/interface.py index 97b2c9a91c..e7b120c6b3 100644 --- a/opendbc_repo/opendbc/car/toyota/interface.py +++ b/opendbc_repo/opendbc/car/toyota/interface.py @@ -242,7 +242,8 @@ class CarInterface(CarInterfaceBase): # min speed to enable ACC. if car can do stop and go, then set enabling speed # to a negative value, so it won't matter. - ret.minEnableSpeed = -1. if stop_and_go else MIN_ACC_SPEED + highlander_sdsu = candidate == CAR.TOYOTA_HIGHLANDER and (rav4h_sdsu or legacy_advert) + ret.minEnableSpeed = -1. if stop_and_go or highlander_sdsu else MIN_ACC_SPEED if ret.flags & ToyotaFlags.TSS2 or ret.flags & ToyotaFlags.LONG_FILTER and not (rav4h_sdsu or eps8_filter or legacy_filter): ret.flags |= ToyotaFlags.RAISED_ACCEL_LIMIT.value diff --git a/opendbc_repo/opendbc/car/toyota/legacy_advert_filter.py b/opendbc_repo/opendbc/car/toyota/legacy_advert_filter.py index c91044cd1c..1123da7980 100644 --- a/opendbc_repo/opendbc/car/toyota/legacy_advert_filter.py +++ b/opendbc_repo/opendbc/car/toyota/legacy_advert_filter.py @@ -3,7 +3,7 @@ from opendbc.can import CANParser from opendbc.car import structs from opendbc.car.toyota import legacy_sdsu, rav4h_filter -from opendbc.car.toyota.values import CAR, ToyotaFlags +from opendbc.car.toyota.values import CAR, MIN_ACC_SPEED, ToyotaFlags from opendbc.car.toyota.toyotacan import toyota_checksum PROFILES = dict.fromkeys(rav4h_filter.EPS5_SDSU_CARS, (0x9449, 0x9649)) @@ -78,6 +78,8 @@ def prepare_stock(cp): if not configured(cp): return False cp.openpilotLongitudinalControl = False + if cp.carFingerprint == CAR.TOYOTA_HIGHLANDER: + cp.minEnableSpeed = MIN_ACC_SPEED cp.safetyConfigs[0].safetyParam = PROFILES[cp.carFingerprint][1] cp.autoResumeSng = False return True diff --git a/opendbc_repo/opendbc/car/toyota/rav4h_filter.py b/opendbc_repo/opendbc/car/toyota/rav4h_filter.py index a751e959f5..e428a3ad4e 100644 --- a/opendbc_repo/opendbc/car/toyota/rav4h_filter.py +++ b/opendbc_repo/opendbc/car/toyota/rav4h_filter.py @@ -2,7 +2,7 @@ from opendbc.can import CANParser from opendbc.car import structs from opendbc.car.config_cache import cached_config -from opendbc.car.toyota.values import CAR, ToyotaFlags +from opendbc.car.toyota.values import CAR, MIN_ACC_SPEED, ToyotaFlags # Bit15 is a distinct exact-profile marker; reserve Dom bit14 for Lexus ALT_CRUISE. EPS5_SDSU_CARS = frozenset(( @@ -76,6 +76,8 @@ def prepare_stock(cp): cp.flags &= ~int(ToyotaFlags.AUTO_BRAKE_HOLD) cp.alternativeExperience &= ~(128 | 256) cp.openpilotLongitudinalControl = False + if cp.carFingerprint == CAR.TOYOTA_HIGHLANDER: + cp.minEnableSpeed = MIN_ACC_SPEED cp.safetyConfigs[0].safetyParam = STOCK_WORD cp.autoResumeSng = False return True diff --git a/opendbc_repo/opendbc/car/toyota/tests/test_rav4h_filter.py b/opendbc_repo/opendbc/car/toyota/tests/test_rav4h_filter.py index f7e2e028c3..efc1225702 100644 --- a/opendbc_repo/opendbc/car/toyota/tests/test_rav4h_filter.py +++ b/opendbc_repo/opendbc/car/toyota/tests/test_rav4h_filter.py @@ -10,15 +10,15 @@ from opendbc.car.toyota.values import CAR, DBC, ToyotaFlags from openpilot.starpilot.car.toyota.aol import qualified -def firmware(): +def firmware(car=CAR.TOYOTA_RAV4H): return [structs.CarParams.CarFw(ecu=ecu, address=address, subAddress=subaddress or 0, fwVersion=versions[0], brand="toyota", bus=0) - for (ecu, address, subaddress), versions in FW_VERSIONS[CAR.TOYOTA_RAV4H].items()] + for (ecu, address, subaddress), versions in FW_VERSIONS[car].items()] def factory(fp=None, fw=None, alpha=False, car=CAR.TOYOTA_RAV4H): return CarInterface.get_params(car, {0: {0x2FF: 8}, 1: {}, 2: {}} if fp is None else fp, - firmware() if fw is None else fw, alpha, False, False) + firmware(car) if fw is None else fw, alpha, False, False) class TestRav4hFilter(unittest.TestCase): @@ -43,6 +43,29 @@ class TestRav4hFilter(unittest.TestCase): self.assertAlmostEqual(LongControl(cp).stopping_decel_rate, .3) self.assertEqual(DBC[cp.carFingerprint][Bus.pt], "toyota_tnga_k_pt_generated") + def test_highlander_sdsu_low_speed_engagement_and_stock_fallback(self): + from opendbc.car.toyota import legacy_advert_filter + from opendbc.car.toyota.values import MIN_ACC_SPEED + + car = CAR.TOYOTA_HIGHLANDER + stock = factory(fp={0: {}, 1: {}, 2: {}}, car=car) + self.assertFalse(stock.openpilotLongitudinalControl) + self.assertAlmostEqual(stock.minEnableSpeed, MIN_ACC_SPEED, places=6) + for size, restore_stock in ((4, legacy_advert_filter.prepare_stock), (8, prepare_stock)): + fp = {0: {0x2FF: size}, 1: {}, 2: {}} + for alpha in (False, True): + with self.subTest(size=size, alpha=alpha): + cp = factory(fp=fp, car=car, alpha=alpha) + self.assertTrue(cp.openpilotLongitudinalControl) + self.assertFalse(cp.alphaLongitudinalAvailable) + self.assertEqual(cp.minEnableSpeed, -1) + self.assertTrue(restore_stock(cp)) + self.assertFalse(cp.openpilotLongitudinalControl) + self.assertEqual(cp.minEnableSpeed, stock.minEnableSpeed) + unknown = factory(fp=fp, car=car, fw=[]) + self.assertFalse(unknown.openpilotLongitudinalControl) + self.assertEqual(unknown.minEnableSpeed, stock.minEnableSpeed) + def test_missing_or_mismatched_hardware_never_grants_long_or_aol(self): fps = ({0: {}, 1: {}, 2: {}}, {0: {0x2FF: 7}, 1: {}, 2: {}}, {0: {}, 1: {0x2FF: 8}, 2: {}}, {0: {0x2FF: 8}, 1: {0x2FF: 8}, 2: {}}, diff --git a/opendbc_repo/opendbc/car/volkswagen/carcontroller.py b/opendbc_repo/opendbc/car/volkswagen/carcontroller.py index 14fd72dd51..bd26666df7 100644 --- a/opendbc_repo/opendbc/car/volkswagen/carcontroller.py +++ b/opendbc_repo/opendbc/car/volkswagen/carcontroller.py @@ -6,6 +6,8 @@ from opendbc.car.lateral import apply_driver_steer_torque_limits from opendbc.car.common.conversions import Conversions as CV from opendbc.car.interfaces import CarControllerBase from opendbc.car.volkswagen import mebcan, mlbcan, mqbcan, pqcan +from opendbc.car.volkswagen.stock_aol import qualified as stock_aol_qualified +from opendbc.car.volkswagen.long_aol import qualified as long_aol_qualified from opendbc.car.volkswagen.values import CanBus, CarControllerParams, VolkswagenFlags VisualAlert = structs.CarControl.HUDControl.VisualAlert @@ -171,11 +173,14 @@ class CarController(CarControllerBase): # **** HUD Controls ***************************************************** # if self.frame % self.CCP.LDW_STEP == 0: - hud_alert = 0 - if hud_control.visualAlert in (VisualAlert.steerRequired, VisualAlert.ldw): - hud_alert = self.CCP.LDW_MESSAGES["laneAssistTakeOver"] - can_sends.append(self.CCS.create_lka_hud_control(self.packer_pt, self.CAN.pt, CS.ldw_stock_values, CC.latActive, - CS.out.steeringPressed, hud_alert, hud_control)) + # Card finalizes the AOL safety configuration after constructing the controller. + mqb_aol_hud = stock_aol_qualified(self.CP, marked_only=True) or long_aol_qualified(self.CP, marked_only=True) + if not mqb_aol_hud or (CC.latActive and self.apply_torque_last != 0): + hud_alert = 0 + if hud_control.visualAlert in (VisualAlert.steerRequired, VisualAlert.ldw): + hud_alert = self.CCP.LDW_MESSAGES["laneAssistTakeOver"] + can_sends.append(self.CCS.create_lka_hud_control(self.packer_pt, self.CAN.pt, CS.ldw_stock_values, CC.latActive, + CS.out.steeringPressed, hud_alert, hud_control)) if hud_control.leadDistanceBars != self.lead_distance_bars_last: self.distance_bar_frame = self.frame diff --git a/opendbc_repo/opendbc/dbc/generator/subaru/_subaru_global.dbc b/opendbc_repo/opendbc/dbc/generator/subaru/_subaru_global.dbc index d7ca0d1b2a..98889d6d19 100644 --- a/opendbc_repo/opendbc/dbc/generator/subaru/_subaru_global.dbc +++ b/opendbc_repo/opendbc/dbc/generator/subaru/_subaru_global.dbc @@ -256,7 +256,11 @@ BO_ 964 ES_LKAS_Alert: 8 XXX SG_ CHECKSUM : 0|8@1+ (1,0) [0|255] "" XXX SG_ COUNTER : 8|4@1+ (1,0) [0|15] "" XXX SG_ Signal1 : 12|4@1+ (1,0) [0|15] "" XXX - SG_ Payload : 16|48@1+ (1,0) [0|281474976710655] "" XXX + SG_ LKAS_Alert : 16|8@1+ (1,0) [0|255] "" XXX + SG_ LKAS_Alert_Msg : 24|8@1+ (1,0) [0|255] "" XXX + SG_ LKAS_HUD_Lights : 32|8@1+ (1,0) [0|255] "" XXX + SG_ ACC_Lead_LED : 40|8@1+ (1,0) [0|255] "" XXX + SG_ Signal2 : 48|16@1+ (1,0) [0|65535] "" XXX BO_ 722 AC_State: 8 XXX SG_ CHECKSUM : 0|8@1+ (1,0) [0|255] "" XXX @@ -300,12 +304,24 @@ CM_ SG_ 801 LKAS_State_Msg "1 = LKAS_Off_Sharp_Curve, 2 = Keep_Hands_On_Steering CM_ SG_ 801 Cruise_State_Msg "1 = Cruise_Off_Steep_Slope, 2 = Cruise_lvl1_eco, 3 = Cruise_lvl2_comfort, 4 = Cruise_off_empty_reason, 5 = Cruise_off, 6 = Cruise_Unable_to_set, 7 = Cruise_Unable_to_set_brakes_applied, 8 = Eyesight_not_ready, 9 = Cruise_lvl3_standard, 10 = Cruise_lvl4_dynamic, 11 = Cruise_Unable_to_set_steep_slope"; CM_ SG_ 801 Cruise_Soft_Disable "Eyesight soft disable (eg direct sunlight)"; CM_ SG_ 801 Cruise_Status_Msg "1 = Disabled_Bad_Visibility, 2 = Disabled_Check_Manual"; +CM_ SG_ 292 SET_3 "2 = LKA / LDP mode, 3 = Lane Centering mode"; CM_ SG_ 802 LKAS_ACTIVE "Turns on the full LKAS dash display"; -CM_ SG_ 802 LKAS_Alert_Msg "1 = Keep_Hands_On_Wheel, 6 = Pre_Collision_Braking, 7 = Keep_Hands_On_Wheel_Off"; -CM_ SG_ 802 LKAS_Alert "1 = FCW_Cont_Beep, 2 = FCW_Repeated_Beep, 3 = Throttle_Management_Activated_Warning, 4 = Throttle_Management_Activated_Alert, 5 = Pre_Collision_Activated_Alert, 8 = Traffic_Light_Ahead, 9 = Apply_Brake_to_Hold Position, 11 = LDW_Right, 12 = LDW_Left, 13 = Stay_Alert, 14 = Lead_Vehicle_Start_Alert, 18 = Keep_Hands_On_Steering_Alert, 24 = Audio_Beep, 25 = Audio_Lead_Car_Change, 26 = Audio_ACC_Disengaged, 27 = Audio_LKAS_disabled, 28 = Audio_Ding_Ding, 30 = Audio_Repeated_Beep"; +CM_ SG_ 802 LKAS_Alert_Msg "1 = Keep_Hands_On_Wheel (static), 6 = Pre_Collision_Braking, 7 = Keep_Hands_On_Wheel_Red_Flash (flashing red hands); 2-5 = Unused"; +CM_ SG_ 802 LKAS_Alert "1 = FCW_Cont_Beep, 2 = FCW_Repeated_Beep, 3 = Throttle_Management_Activated_Warning, 4 = Throttle_Management_Activated_Alert, 5 = Pre_Collision_Activated_Alert, 8 = Traffic_Light_Ahead, 9 = Apply_Brake_to_Hold Position, 11 = LDW_Right, 12 = LDW_Left, 13 = Stay_Alert, 14 = Lead_Vehicle_Start_Alert, 18 = LC_LDW_Right (lane departure right during Lane Centering), 19 = LC_LDW_Left (lane departure left during Lane Centering), 24 = Audio_Beep, 25 = Audio_Lead_Car_Change, 26 = Audio_ACC_Disengaged, 27 = Audio_LKAS_disabled, 28 = Audio_Ding_Ding, 30 = Audio_Repeated_Beep"; CM_ SG_ 802 LKAS_Left_Line_Visible "0 = Off, 1 = White, 2 = Green, 3 = Orange"; CM_ SG_ 802 LKAS_Dash_State "0 = Off, 1 = Ready, 2 = Active"; CM_ SG_ 802 LKAS_Right_Line_Visible "0 = Off, 1 = White, 2 = Green, 3 = Orange"; +CM_ SG_ 803 LKAS_State_Infotainment "1 = Obstacle_Ahead, 2 = Obstacle_Detected, 3 = Keep_Hands_On_Wheel (adds flashing yellow border on cluster/infotainment), 4 = Keep_Hands_On_Wheel_Off, 5 = Keep_Hands_On_Wheel_Alt; 6-7 = Unused"; +CM_ SG_ 964 LKAS_Alert "11 = LDW_Right (+3 soft chimes), 12 = LDW_Left (+3 soft chimes), 13 = Stay_Alert (+3 soft chimes), 14 = Lead_Vehicle_Start_Alert (+tut-tut chime), 18 = LC_LDW_Right (lane departure right during Lane Centering), 19 = LC_LDW_Left (lane departure left during Lane Centering), 24 = Audio_Beep (soft chirp), 25 = Audio_Lead_Car_Change, 26 = Audio_ACC_Disengaged (1 strong chime), 27 = Audio_LKAS_disabled (1 strong chime), 28 = Audio_Ding_Ding (2 bouncy chimes), 30 = Audio_Repeated_Beep (4 strong chimes); 29,31 = Unused"; +CM_ SG_ 964 LKAS_Alert_Msg "1 = Keep_Hands_On_Wheel (static), 7 = Keep_Hands_On_Wheel_Red_Flash (flashing red hands); 2-5,8 = Unused"; +CM_ SG_ 964 LKAS_HUD_Lights "Windshield HUD LED bitmask: 1 = 2 Yellow Solid, 2 = 2 Yellow Rapid Flash, 4 = 2 Yellow Slow Flash, 16 = 4 Red Solid, 32 = 4 Red Rapid Flash, 48 = 4 Red Solid+Rapid Flash, 64 = 4 Red Slow Flash, 80 = 2 Red Solid + 2 Red Flash Right (0x50), 96 = 2 Red Solid + 2 Red Flash Left (0x60) (8,128 = Unused)"; +CM_ SG_ 964 ACC_Lead_LED "1 = Green_Lead_Tracked"; CM_ SG_ 912 UNITS "0 = Metric, 1 = Imperial"; CM_ SG_ 912 ICY_ROAD "1 = DASHLIGHT ON, 2 = WARNING, 3 = OFF"; +VAL_ 292 SET_3 3 "Lane_Centering" 2 "LKA_LDP" 0 "Off"; VAL_ 544 AEB_Status 12 "AEB related" 8 "AEB actuation" 4 "AEB related" 0 "No AEB actuation"; +VAL_ 803 LKAS_State_Infotainment 7 "Unused_7" 6 "Unused_6" 5 "Keep_Hands_On_Wheel_Alt" 4 "Keep_Hands_On_Wheel_Off" 3 "Keep_Hands_On_Wheel" 2 "Obstacle_Detected" 1 "Obstacle_Ahead" 0 "None"; +VAL_ 964 LKAS_Alert 31 "Unused_31" 30 "Audio_Repeated_Beep" 29 "Unused_29" 28 "Audio_Ding_Ding" 27 "Audio_LKAS_disabled" 26 "Audio_ACC_Disengaged" 25 "Audio_Lead_Car_Change" 24 "Audio_Beep_Chirp" 19 "LC_LDW_Left" 18 "LC_LDW_Right" 14 "Lead_Vehicle_Start_Alert" 13 "Stay_Alert" 12 "LDW_Left" 11 "LDW_Right" 0 "None"; +VAL_ 964 LKAS_Alert_Msg 8 "Unused_8" 7 "Keep_Hands_On_Wheel_Red_Flash" 5 "Unused_5" 4 "Unused_4" 3 "Unused_3" 2 "Unused_2" 1 "Keep_Hands_On_Wheel" 0 "None"; +VAL_ 964 LKAS_HUD_Lights 96 "Red_2_Solid_2_Flash_Left" 80 "Red_2_Solid_2_Flash_Right" 64 "Red_4_Slow_Flash" 48 "Red_4_Flash" 32 "Red_4_Rapid_Flash" 16 "Red_4_Solid" 4 "Yellow_2_Slow_Flash" 2 "Yellow_2_Rapid_Flash" 1 "Yellow_2_Solid" 0 "Off"; +VAL_ 964 ACC_Lead_LED 1 "Green_Lead_Tracked" 0 "Off"; diff --git a/opendbc_repo/opendbc/safety/modes/subaru.h b/opendbc_repo/opendbc/safety/modes/subaru.h index 243ed0e023..1eec9d974d 100644 --- a/opendbc_repo/opendbc/safety/modes/subaru.h +++ b/opendbc_repo/opendbc/safety/modes/subaru.h @@ -343,17 +343,25 @@ static safety_config subaru_init(uint16_t raw_param) { {MSG_SUBARU_ES_LKAS_Alert, SUBARU_MAIN_BUS, 8, .check_relay = true}, }; + static const CanMsg SUBARU_LEGACY_ANGLE_TX_MSGS[] = { + SUBARU_GEN2_ANGLE_TX_MSGS(SUBARU_MAIN_BUS) + {MSG_SUBARU_ES_LKAS_Alert, SUBARU_MAIN_BUS, 8, .check_relay = true}, + }; + static const CanMsg SUBARU_STOP_START_TX_MSGS[] = { SUBARU_GEN2_ANGLE_TX_MSGS(SUBARU_MAIN_BUS) + {MSG_SUBARU_ES_LKAS_Alert, SUBARU_MAIN_BUS, 8, .check_relay = true}, {0x390U, SUBARU_ALT_BUS, 8, .check_relay = false}, }; static const CanMsg SUBARU_AVH_TX_MSGS[] = { SUBARU_GEN2_ANGLE_TX_MSGS(SUBARU_MAIN_BUS) + {MSG_SUBARU_ES_LKAS_Alert, SUBARU_MAIN_BUS, 8, .check_relay = true}, {0x6BBU, SUBARU_ALT_BUS, 8, .check_relay = false}, }; static const CanMsg SUBARU_AVH_STOP_START_TX_MSGS[] = { SUBARU_GEN2_ANGLE_TX_MSGS(SUBARU_MAIN_BUS) + {MSG_SUBARU_ES_LKAS_Alert, SUBARU_MAIN_BUS, 8, .check_relay = true}, {0x6BBU, SUBARU_ALT_BUS, 8, .check_relay = false}, {0x390U, SUBARU_ALT_BUS, 8, .check_relay = false}, }; @@ -400,10 +408,12 @@ static safety_config subaru_init(uint16_t raw_param) { ((unsigned int)alternative_experience == 32U))); subaru_aol_reset(); subaru_aol_gear_bus = (uint8_t)(subaru_d_platform ? SUBARU_ALT_BUS : SUBARU_MAIN_BUS); + const bool legacy_2025 = (base_param == 145U); + subaru_aol_legacy_2025 = legacy_2025; subaru_aol_enabled = ((unsigned int)alternative_experience == 32U) && ((param == 209U) || (param == 465U) || (param == 16U) || (param == 0U) || (param == 1U) || (param == 17U) || (param == 145U) || avh || (param == 177U) || (param == 401U) || (param == 8U) || (param == 520U) || (param == 512U) || (param == 2225U)); - subaru_aol_main_arm = subaru_aol_enabled && ((param == 17U) || impreza_main || subaru_d_platform); + subaru_aol_main_arm = subaru_aol_enabled && ((param == 17U) || impreza_main || subaru_d_platform || legacy_2025); if (subaru_aol_enabled) { static const AolSafetyPolicy policy = { .reset = subaru_aol_reset, @@ -441,6 +451,7 @@ static safety_config subaru_init(uint16_t raw_param) { BUILD_SAFETY_CFG(subaru_rx_workspace, SUBARU_AVH_TX_MSGS)) : stop_start ? BUILD_SAFETY_CFG(subaru_rx_workspace, SUBARU_STOP_START_TX_MSGS) : ascent_alert ? BUILD_SAFETY_CFG(subaru_rx_workspace, SUBARU_ASCENT_ALERT_TX_MSGS) : + legacy_2025 ? BUILD_SAFETY_CFG(subaru_rx_workspace, SUBARU_LEGACY_ANGLE_TX_MSGS) : subaru_angle_main_bus ? BUILD_SAFETY_CFG(subaru_rx_workspace, SUBARU_ASCENT_ANGLE_TX_MSGS_LIST) : BUILD_SAFETY_CFG(subaru_rx_workspace, SUBARU_GEN2_ANGLE_TX_MSGS_LIST); // Keep the original seven checks on other profiles; only MAIN arming needs ACC health. diff --git a/opendbc_repo/opendbc/safety/modes/subaru_avh.h b/opendbc_repo/opendbc/safety/modes/subaru_avh.h index 141cbfce12..38065d5431 100644 --- a/opendbc_repo/opendbc/safety/modes/subaru_avh.h +++ b/opendbc_repo/opendbc/safety/modes/subaru_avh.h @@ -7,7 +7,7 @@ static bool subaru_avh_seen[7]; static bool subaru_avh_seq[7]; static bool subaru_avh_enabled; static bool subaru_avh_done; -static unsigned int subaru_avh_count; +static uint8_t subaru_avh_count; static uint32_t subaru_avh_start; static uint32_t subaru_avh_sent; static uint32_t subaru_avh_template_ts; @@ -109,8 +109,8 @@ static void subaru_avh_rx(const CANPacket_t *msg) { static bool subaru_avh_tx(const CANPacket_t *msg) { const uint32_t now = microsecond_timer_get(); const uint32_t elapsed = safety_get_ts_elapsed(now, subaru_avh_start); - const bool second = subaru_avh_count == 1U; - bool allowed = subaru_avh_enabled && !subaru_avh_done && (subaru_avh_count < 2U) && + const bool followup = subaru_avh_count > 0U; + bool allowed = subaru_avh_enabled && !subaru_avh_done && (subaru_avh_count < 4U) && (msg->addr == 0x6BBU) && (msg->bus == 1U) && (GET_LEN(msg) == 8U) && !relay_malfunction && !safety_rx_checks_invalid && aol_rx_healthy() && !lateral_controls_allowed() && !gas_pressed && !subaru_software_fault && (elapsed >= 10000000U) && (elapsed <= 30000000U) && subaru_avh_ready(now) && @@ -124,10 +124,10 @@ static bool subaru_avh_tx(const CANPacket_t *msg) { } } - if (second) { + if (followup) { const uint32_t spacing = safety_get_ts_elapsed(now, subaru_avh_sent); allowed &= (spacing >= 45000U) && (spacing <= 80000U) && (subaru_avh_ts[0] == subaru_avh_template_ts) && - (safety_get_ts_elapsed(now, subaru_avh_ts[0]) <= 110000U); + (safety_get_ts_elapsed(now, subaru_avh_ts[0]) <= 250000U); } else { allowed &= safety_get_ts_elapsed(now, subaru_avh_ts[0]) <= 30000U; } @@ -135,7 +135,7 @@ static bool subaru_avh_tx(const CANPacket_t *msg) { for (int i = 1; i < 8; i++) { uint8_t expected = subaru_avh_data[0][i]; if (i == 1) { - expected = (expected & 0xF0U) | ((expected + (second ? 2U : 1U)) & 0xFU); + expected = (expected & 0xF0U) | ((expected + subaru_avh_count + 1U) & 0xFU); } else if (i == 2) { expected |= 2U; } else { @@ -149,7 +149,7 @@ static bool subaru_avh_tx(const CANPacket_t *msg) { subaru_avh_count++; subaru_avh_sent = now; subaru_avh_template_ts = subaru_avh_ts[0]; - subaru_avh_done = second; + subaru_avh_done = (subaru_avh_count == 4U); } return allowed; } diff --git a/opendbc_repo/opendbc/safety/modes/subaru_preglobal.h b/opendbc_repo/opendbc/safety/modes/subaru_preglobal.h index cc10569f3c..e137608223 100644 --- a/opendbc_repo/opendbc/safety/modes/subaru_preglobal.h +++ b/opendbc_repo/opendbc/safety/modes/subaru_preglobal.h @@ -17,7 +17,14 @@ #define SUBARU_PG_MAIN_BUS 0U #define SUBARU_PG_CAM_BUS 2U +#define SUBARU_PG_OUTBACK_STOCK_ACC 8U + static bool subaru_pg_reversed_driver_torque = false; +static bool subaru_pg_stock_acc = false; + +static uint8_t subaru_preglobal_counter(const CANPacket_t *msg) { + return msg->data[1] & 0xFU; +} static void subaru_preglobal_rx_hook(const CANPacket_t *msg) { if (msg_matches(msg, MSG_SUBARU_PG_Steering_Torque, SUBARU_PG_MAIN_BUS)) { @@ -68,7 +75,12 @@ static bool subaru_preglobal_tx_hook(const CANPacket_t *msg) { bool steer_req = (msg->data[3] >> 0) & 1U; - if (steer_torque_cmd_checks(desired_torque, steer_req, SUBARU_PG_STEERING_LIMITS)) { + uint8_t checksum = 0U; + for (int i = 0; i < 7; i++) { + checksum += msg->data[i]; + } + if (steer_torque_cmd_checks(desired_torque, steer_req, SUBARU_PG_STEERING_LIMITS) || + (subaru_pg_stock_acc && (checksum != msg->data[7]))) { tx = false; } } @@ -82,8 +94,12 @@ static safety_config subaru_preglobal_init(uint16_t param) { {MSG_SUBARU_PG_ES_LKAS, SUBARU_PG_MAIN_BUS, 8, .check_relay = true}, }; - // TODO: do checksum and counter checks after adding the signals to the outback dbc file - static const RxCheck subaru_preglobal_rx_checks[] = { + static const CanMsg SUBARU_PG_STOCK_ACC_TX_MSGS[] = { + {MSG_SUBARU_PG_ES_LKAS, SUBARU_PG_MAIN_BUS, 8, .check_relay = true}, + }; + + // Only Throttle has a verified payload counter for the 2015–17 Outback. + static RxCheck subaru_preglobal_rx_checks[] = { {.msg = {{MSG_SUBARU_PG_Throttle, SUBARU_PG_MAIN_BUS, 8, 100U, .ignore_checksum = true, .ignore_counter = true, .ignore_quality_flag = true}, { 0 }, { 0 }}}, {.msg = {{MSG_SUBARU_PG_Steering_Torque, SUBARU_PG_MAIN_BUS, 8, 50U, .ignore_checksum = true, .ignore_counter = true, .ignore_quality_flag = true}, { 0 }, { 0 }}}, {.msg = {{MSG_SUBARU_PG_CruiseControl, SUBARU_PG_MAIN_BUS, 8, 50U, .ignore_checksum = true, .ignore_counter = true, .ignore_quality_flag = true}, { 0 }, { 0 }}}, @@ -94,11 +110,18 @@ static safety_config subaru_preglobal_init(uint16_t param) { const uint16_t SUBARU_PG_PARAM_REVERSED_DRIVER_TORQUE = 4; subaru_pg_reversed_driver_torque = GET_FLAG(param, SUBARU_PG_PARAM_REVERSED_DRIVER_TORQUE); - return BUILD_SAFETY_CFG(subaru_preglobal_rx_checks, SUBARU_PG_TX_MSGS); + subaru_pg_stock_acc = param == SUBARU_PG_OUTBACK_STOCK_ACC; + subaru_preglobal_rx_checks[0].msg[0].ignore_counter = !subaru_pg_stock_acc; + subaru_preglobal_rx_checks[0].msg[0].max_counter = subaru_pg_stock_acc ? 15U : 0U; + // Leave the stock EyeSight cruise frame on the normal forwarding path. + safety_config config = subaru_pg_stock_acc ? BUILD_SAFETY_CFG(subaru_preglobal_rx_checks, SUBARU_PG_STOCK_ACC_TX_MSGS) : + BUILD_SAFETY_CFG(subaru_preglobal_rx_checks, SUBARU_PG_TX_MSGS); + return config; } const safety_hooks subaru_preglobal_hooks = { .init = subaru_preglobal_init, .rx = subaru_preglobal_rx_hook, .tx = subaru_preglobal_tx_hook, + .get_counter = subaru_preglobal_counter, }; diff --git a/opendbc_repo/opendbc/safety/modes/subaru_stock_aol.h b/opendbc_repo/opendbc/safety/modes/subaru_stock_aol.h index 8163dedf58..2e1267f257 100644 --- a/opendbc_repo/opendbc/safety/modes/subaru_stock_aol.h +++ b/opendbc_repo/opendbc/safety/modes/subaru_stock_aol.h @@ -25,9 +25,18 @@ static bool subaru_aol_main_arm = false; static bool subaru_aol_main_epoch = false; static bool subaru_aol_main_low_seen = false; static bool subaru_aol_acc_fault = false; +static bool subaru_aol_legacy_2025 = false; +static bool subaru_aol_park_seen = false; + +static bool subaru_aol_drive_gear(uint8_t gear) { + // Drive (121 = 0x79) or CVT manual mode / paddle gears (129..193 step 8) on Legacy 2025. + return (gear == 121U) || + (subaru_aol_legacy_2025 && (gear >= 129U) && (gear <= 193U) && (((gear - 129U) & 7U) == 0U)); +} static void subaru_aol_clear(void) { subaru_aol_main_epoch = false; + subaru_aol_park_seen = false; subaru_aol_armed = false; subaru_aol_token = false; subaru_aol_pending = false; @@ -80,12 +89,14 @@ static void subaru_aol_observe_main(bool main_on) { if (!main_on) { subaru_aol_clear(); subaru_aol_main_low_seen = true; - } else if (subaru_aol_main_arm && subaru_aol_main_low_seen && !subaru_aol_main && - subaru_aol_gear_qualified && subaru_aol_drive && + } else if (subaru_aol_main_arm && + ((subaru_aol_main_low_seen && !subaru_aol_main) || (subaru_aol_legacy_2025 && subaru_aol_park_seen)) && + subaru_aol_gear_qualified && (subaru_aol_drive || subaru_aol_legacy_2025) && (safety_get_ts_elapsed(microsecond_timer_get(), subaru_aol_gear_ts) <= 100000U) && !subaru_aol_permanent && !subaru_aol_temporary && !subaru_aol_acc_fault && !relay_malfunction && !safety_rx_checks_invalid && aol_rx_healthy()) { subaru_aol_main_epoch = true; + subaru_aol_park_seen = false; } else { // No qualified MAIN edge; retain epoch. } @@ -181,11 +192,15 @@ static void subaru_aol_optional_rx(const CANPacket_t *msg) { subaru_aol_gear_seen = true; subaru_aol_gear_counter = counter; subaru_aol_gear_ts = microsecond_timer_get(); - subaru_aol_drive = msg->data[3] == 121U; + subaru_aol_drive = subaru_aol_drive_gear(msg->data[3]); + if (subaru_aol_legacy_2025 && (msg->data[3] == 4U) && !subaru_aol_armed && + !subaru_aol_permanent && !subaru_aol_acc_fault) { + subaru_aol_park_seen = true; + } } else { // A contradictory duplicate must withdraw Drive immediately; it may // neither renew the source receipt nor retain an old Drive permission. - if (((msg->data[3] == 121U) && !subaru_aol_drive) || ((msg->data[3] != 121U) && subaru_aol_drive)) { + if (subaru_aol_drive_gear(msg->data[3]) != subaru_aol_drive) { subaru_aol_gear_qualified = false; subaru_aol_gear_seen = false; } diff --git a/opendbc_repo/opendbc/safety/modes/volkswagen_mqb.h b/opendbc_repo/opendbc/safety/modes/volkswagen_mqb.h index 80a3970940..7fa4902d8c 100644 --- a/opendbc_repo/opendbc/safety/modes/volkswagen_mqb.h +++ b/opendbc_repo/opendbc/safety/modes/volkswagen_mqb.h @@ -234,6 +234,11 @@ static bool volkswagen_mqb_tx_hook(const CANPacket_t *msg) { } } + // The stock camera retains the HUD until an openpilot HCA command owns steering. + if ((msg->addr == MSG_LDW_02) && vw_aol_enabled && !vw_aol_steering_owned()) { + tx = false; + } + vw_aol_tx_commit(msg, tx && !relay_malfunction); return tx; } diff --git a/opendbc_repo/opendbc/safety/modes/volkswagen_stock_aol.h b/opendbc_repo/opendbc/safety/modes/volkswagen_stock_aol.h index 614158a104..a296e93c11 100644 --- a/opendbc_repo/opendbc/safety/modes/volkswagen_stock_aol.h +++ b/opendbc_repo/opendbc/safety/modes/volkswagen_stock_aol.h @@ -255,10 +255,14 @@ static void vw_aol_tx_commit(const CANPacket_t *msg, bool accepted) { } } +static bool vw_aol_steering_owned(void) { + return vw_aol_enabled && vw_aol_owned && ((vw_aol_permission() & 1U) != 0U) && + (safety_get_ts_elapsed(microsecond_timer_get(), vw_aol_accepted_ts[0]) <= AOL_HOST_REQUEST_TIMEOUT_US); +} + static bool vw_aol_fwd(int bus, int addr) { bool blocked = false; - if (vw_aol_enabled && vw_aol_owned && ((vw_aol_permission() & 1U) != 0U) && - (safety_get_ts_elapsed(microsecond_timer_get(), vw_aol_accepted_ts[0]) <= AOL_HOST_REQUEST_TIMEOUT_US)) { + if (vw_aol_steering_owned()) { unsigned int index = 3U; if ((bus == 2) && (addr == (int)MSG_HCA_01)) { index = 0U; diff --git a/opendbc_repo/opendbc/safety/safety.h b/opendbc_repo/opendbc/safety/safety.h index c19b582835..1b7fa364f1 100644 --- a/opendbc_repo/opendbc/safety/safety.h +++ b/opendbc_repo/opendbc/safety/safety.h @@ -451,6 +451,7 @@ int set_safety_hooks(uint16_t mode, uint16_t param) { {SAFETY_HYUNDAI, &hyundai_hooks}, {SAFETY_CHRYSLER, &chrysler_hooks}, {SAFETY_SUBARU, &subaru_hooks}, + {SAFETY_SUBARU_PREGLOBAL, &subaru_preglobal_hooks}, {SAFETY_VOLKSWAGEN_MQB, &volkswagen_mqb_hooks}, {SAFETY_VOLKSWAGEN_MEB, &volkswagen_meb_hooks}, {SAFETY_NISSAN, &nissan_hooks}, @@ -469,7 +470,6 @@ int set_safety_hooks(uint16_t mode, uint16_t param) { {SAFETY_CHRYSLER_CUSW, &chrysler_cusw_hooks}, {SAFETY_PSA, &psa_hooks}, {SAFETY_BYD, &byd_hooks}, - {SAFETY_SUBARU_PREGLOBAL, &subaru_preglobal_hooks}, {SAFETY_VOLKSWAGEN_MLB, &volkswagen_mlb_hooks}, {SAFETY_VOLKSWAGEN_PQ, &volkswagen_pq_hooks}, {SAFETY_ALLOUTPUT, &alloutput_hooks}, @@ -526,6 +526,14 @@ int set_safety_hooks(uint16_t mode, uint16_t param) { int hook_config_count = sizeof(safety_hook_registry) / sizeof(safety_hook_config); for (int i = 0; i < hook_config_count; i++) { if (safety_hook_registry[i].id == mode) { +#ifndef ALLOW_DEBUG + if ((mode == SAFETY_SUBARU_PREGLOBAL) && (param != SUBARU_PG_OUTBACK_STOCK_ACC)) { + current_hooks = &nooutput_hooks; + current_safety_mode = SAFETY_NOOUTPUT; + current_safety_param = 0; + continue; + } +#endif if ((mode == SAFETY_VOLVO) && ((param > 2U) && (param != 5U) && (param != 8U))) { current_hooks = &nooutput_hooks; current_safety_mode = SAFETY_NOOUTPUT; diff --git a/opendbc_repo/opendbc/safety/tests/test_subaru_ascent_alert.py b/opendbc_repo/opendbc/safety/tests/test_subaru_ascent_alert.py index c32728ba21..c2bdd03ae5 100644 --- a/opendbc_repo/opendbc/safety/tests/test_subaru_ascent_alert.py +++ b/opendbc_repo/opendbc/safety/tests/test_subaru_ascent_alert.py @@ -18,14 +18,22 @@ class TestSubaruAscentAlert(unittest.TestCase): return libsafety_py.make_CANPacket(0x3C4, bus, data) def test_exact_parameter_bus_checksum_length_and_forwarding(self): - for flags in (0, 1, 0x11, 0x91, 0xB1, 0x800, 0x811, 0x891, 0x8B3, 0x9B1): + for flags in (0, 1, 0x11, 0xB1, 0x800, 0x811, 0x891, 0x8B3, 0x9B1): self.mode(flags) self.assertFalse(self.safety.safety_tx_hook(self.packet()), hex(flags)) self.assertEqual(self.safety.safety_fwd_hook(2, 0x3C4), 0) + debug = self.safety.set_safety_hooks(structs.CarParams.SafetyModel.allOutput, 0) == 0 + if not debug: + for flags in (1169, 1425): + self.mode(flags) + self.assertFalse(self.safety.safety_tx_hook(self.packet()), hex(flags)) + self.assertEqual(self.safety.safety_fwd_hook(2, 0x3C4), 0) + for flags in (0x8B1, 0x91, 401) + ((1169, 1425) if debug else ()): + self.mode(flags) + self.assertTrue(self.safety.safety_tx_hook(self.packet()), hex(flags)) + self.assertEqual(self.safety.safety_fwd_hook(2, 0x3C4), -1) + self.assertEqual(self.safety.safety_fwd_hook(0, 0x3C4), 2) self.mode(0x8B1) - self.assertTrue(self.safety.safety_tx_hook(self.packet())) - self.assertEqual(self.safety.safety_fwd_hook(2, 0x3C4), -1) - self.assertEqual(self.safety.safety_fwd_hook(0, 0x3C4), 2) for bus in (1, 2): self.assertFalse(self.safety.safety_tx_hook(self.packet(bus=bus))) for data in (bytes.fromhex("0002000104000000"), bytes(7), bytes(12)): diff --git a/opendbc_repo/opendbc/safety/tests/test_subaru_avh_startup.py b/opendbc_repo/opendbc/safety/tests/test_subaru_avh_startup.py index 8902e71e99..009b99664a 100644 --- a/opendbc_repo/opendbc/safety/tests/test_subaru_avh_startup.py +++ b/opendbc_repo/opendbc/safety/tests/test_subaru_avh_startup.py @@ -7,7 +7,22 @@ from opendbc.safety.tests.common import CANPackerSafety from opendbc.safety.tests.libsafety import libsafety_py -def ready(param, ae): +def feed_step(safety, packer, last, tick): + safety.set_timer(1_000_000 + tick * 10_000) + for name, values, bus in [('Transmission', {'Gear': 4}, 0), ('Throttle', {'Engine_RPM': 800}, 0), ('Steering_Torque', {}, 0), ('Steering_2', {}, 0), + ('Wheel_Speeds', dict.fromkeys(('FL', 'FR', 'RL', 'RR'), 0), 1), ('Brake_Status', {}, 1), + ('ES_Status', {}, 1), ('ES_Distance', {}, 1), ('ES_DashStatus', {'Cruise_On': 1}, 2)]: + safety.safety_rx_hook(packer.make_can_msg_safety(name, bus, values)) + for address in (0x6BB, 0x32B, 0x40, 0x48, 0x174): + if address == 0x6BB and tick % 100: + continue + data = sample(address, tick // 100 if address == 0x6BB else tick) + safety.safety_rx_hook(libsafety_py.make_CANPacket(address, 1, data)) + last[address] = data + safety.safety_tick() + + +def _ready_with_packer(param, ae): safety = libsafety_py.libsafety safety.init_tests() safety.set_timer(1_000_000) @@ -16,19 +31,12 @@ def ready(param, ae): packer = CANPackerSafety('subaru_global_2017_generated') last = {} for tick in range(1001): - safety.set_timer(1_000_000 + tick * 10_000) - for name, values, bus in [('Transmission', {'Gear': 4}, 0), ('Throttle', {'Engine_RPM': 800}, 0), ('Steering_Torque', {}, 0), ('Steering_2', {}, 0), - ('Wheel_Speeds', dict.fromkeys(('FL', 'FR', 'RL', 'RR'), 0), 1), ('Brake_Status', {}, 1), - ('ES_Status', {}, 1), ('ES_DashStatus', {'Cruise_On': 1}, 2)]: - raw = packer.make_can_msg_safety(name, bus, values) - safety.safety_rx_hook(raw) - for address in (0x6BB, 0x32B, 0x40, 0x48, 0x174): - if address == 0x6BB and tick % 100: - continue - data = sample(address, tick // 100 if address == 0x6BB else tick) - safety.safety_rx_hook(libsafety_py.make_CANPacket(address, 1, data)) - last[address] = data - safety.safety_tick() + feed_step(safety, packer, last, tick) + return safety, last, packer + + +def ready(param, ae): + safety, last, _ = _ready_with_packer(param, ae) return safety, last @@ -38,13 +46,15 @@ def test_exact_pair_debug_only_and_status_never_tx(param, ae): # Probe the loaded build, not the Subaru authority under test. ready() resets # native state and selects Subaru before any RX or TX checks. debug = libsafety_py.libsafety.set_safety_hooks(structs.CarParams.SafetyModel.allOutput, 0) == 0 - safety, last = ready(param, ae) - for step in (1, 2): - if step == 2: - safety.set_timer(11_060_000) - addr, data, bus = avh_request(last[0x6BB], step) + safety, last, packer = _ready_with_packer(param, ae) + template = last[0x6BB] + for step in (1, 2, 3, 4): + if step > 1: + for offset in range(1, 7): + feed_step(safety, packer, last, 1000 + (step - 2) * 6 + offset) + addr, data, bus = avh_request(template, step) assert bool(safety.safety_tx_hook(libsafety_py.make_CANPacket(addr, bus, data))) == debug - assert not safety.safety_tx_hook(libsafety_py.make_CANPacket(0x6BB, 1, avh_request(last[0x6BB], 2)[1])) + assert not safety.safety_tx_hook(libsafety_py.make_CANPacket(0x6BB, 1, avh_request(template, 4)[1])) assert not safety.safety_tx_hook(libsafety_py.make_CANPacket(0x32B, 1, sample(0x32B, 1))) diff --git a/opendbc_repo/opendbc/safety/tests/test_subaru_gen2_angle_pair.py b/opendbc_repo/opendbc/safety/tests/test_subaru_gen2_angle_pair.py index b2b2a557f7..99568d24b1 100644 --- a/opendbc_repo/opendbc/safety/tests/test_subaru_gen2_angle_pair.py +++ b/opendbc_repo/opendbc/safety/tests/test_subaru_gen2_angle_pair.py @@ -265,7 +265,7 @@ class TestSubaruGen2AnglePair(unittest.TestCase): f'{car.value} {speed=} {target=} {i=} {frame[1].hex()}') seen.append(frame) self.assertGreater(len(seen), 50) - self.assertNotEqual(seen[-1][1][5:7], b'\x00\x00') + self.assertTrue(any(frame[1][5:7] != b'\x00\x00' for frame in seen[-3:])) def test_firmware_complete_partial_and_mixed(self): # Complete supported identities select automatically; partial and diff --git a/opendbc_repo/opendbc/safety/tests/test_subaru_main_aol.py b/opendbc_repo/opendbc/safety/tests/test_subaru_main_aol.py index 8d9086bcb6..9299cc4a67 100644 --- a/opendbc_repo/opendbc/safety/tests/test_subaru_main_aol.py +++ b/opendbc_repo/opendbc/safety/tests/test_subaru_main_aol.py @@ -5,7 +5,7 @@ from opendbc.safety.tests.libsafety import libsafety_py from opendbc.safety.tests import test_subaru_stock_aol as stock_module -@pytest.fixture(params=(17, 209, 465, 4096, 4104, 4608, 4616)) +@pytest.fixture(params=(17, 145, 209, 401, 465, 4096, 4104, 4608, 4616)) def owner(request): item = stock_module.TestSubaruStockAol(methodName='runTest') item.setUp() @@ -71,7 +71,7 @@ def test_new_physical_acc_source_is_required_before_main_edge(owner): def test_acc_wire_checksum_and_counter_cannot_be_faked_by_host(owner): neutral(owner) assert owner.feed() == 1 - bus = 1 if owner.param in (17, 209, 465) else 2 + bus = 1 if owner.param in (17, 145, 209, 401, 465) else 2 bad = owner.frame('ES_Distance', {}, bus) raw = bytearray(bytes(bad.data)) raw[0] ^= 1 @@ -97,9 +97,9 @@ def test_acc_fault_cannot_be_bypassed_by_stock_enable_packets(owner): assert owner.feed() == 1 assert owner.feed(acc_fault=True) == 0 for enabled in (0, 1): - name = 'ES_Status' if owner.param in (17, 209, 465) else 'CruiseControl' + name = 'ES_Status' if owner.param in (17, 145, 209, 401, 465) else 'CruiseControl' values = {'Cruise_Activated': enabled, 'Cruise_On': 1} if name == 'CruiseControl' else {'Cruise_Activated': enabled} - assert owner.safety.safety_rx_hook(owner.frame(name, values, 1 if owner.param in (17, 209, 465) else 0)) + assert owner.safety.safety_rx_hook(owner.frame(name, values, 1 if owner.param in (17, 145, 209, 401, 465) else 0)) owner.safety.aol_set_host_request(1) assert owner.safety.aol_get_permission_mask() == 0 @@ -116,3 +116,29 @@ def test_impreza_main_setting_cannot_select_unqualified_native_output(param, exp assert not item.safety.safety_tx_hook(item.frame('ES_LKAS', {}, 0)) finally: item.tearDown() + + +def test_legacy_2025_cvt_manual_gears(): + item = stock_module.TestSubaruStockAol(methodName='runTest') + item.setUp() + try: + item.configure(145) + neutral(item) + assert item.feed() == 1 + for gear in (137, 145, 153, 161, 169, 177, 185, 193): + assert item.feed(gear=gear) == 1 + assert item.feed(gear=3) == 0 + assert item.feed(gear=145) == 1 + + # Pressing MAIN while in Park (gear=4) then shifting to Drive grants permission. + assert item.feed(main=False, gear=4, speed=0) == 0 + assert item.feed(main=True, gear=4, speed=0) == 0 + assert item.feed(main=True, gear=3, speed=0) == 0 + assert item.feed(main=True, gear=121, speed=54) == 1 + + item.configure(17) + neutral(item) + assert item.feed() == 1 + assert item.feed(gear=137) == 0 + finally: + item.tearDown() diff --git a/opendbc_repo/opendbc/safety/tests/test_subaru_preglobal_stock_acc.py b/opendbc_repo/opendbc/safety/tests/test_subaru_preglobal_stock_acc.py new file mode 100644 index 0000000000..10e02928f2 --- /dev/null +++ b/opendbc_repo/opendbc/safety/tests/test_subaru_preglobal_stock_acc.py @@ -0,0 +1,48 @@ +"""Release steering admission for the 2015–17 Outback with stock EyeSight cruise.""" +import unittest + +from opendbc.car.structs import CarParams +from opendbc.car.subaru.values import SubaruSafetyFlags +from opendbc.safety.tests.libsafety import libsafety_py + + +class TestOutbackPreglobalStockAcc(unittest.TestCase): + def setUp(self): + self.safety = libsafety_py.libsafety + self.addCleanup(self.safety.set_safety_hooks, CarParams.SafetyModel.noOutput, 0) + self.safety.init_tests() + self.assertEqual(self.safety.set_safety_hooks(CarParams.SafetyModel.subaruPreglobal, + SubaruSafetyFlags.PREGLOBAL_OUTBACK_STOCK_ACC), 0) + + def test_stock_cruise_forwarding_and_steering_relay(self): + self.assertEqual(self.safety.safety_fwd_hook(2, 0x161), 0) + self.assertEqual(self.safety.safety_fwd_hook(2, 0x164), -1) + self.assertFalse(self.safety.safety_tx_hook(libsafety_py.make_CANPacket(0x161, 0, bytes(8)))) + self.assertFalse(self.safety.safety_tx_hook(libsafety_py.make_CANPacket(0x164, 2, bytes(8)))) + self.assertTrue(self.safety.safety_tx_hook(libsafety_py.make_CANPacket(0x164, 0, bytes(8)))) + self.assertFalse(self.safety.safety_tx_hook(libsafety_py.make_CANPacket(0x164, 0, bytes(7) + b"\x01"))) + self.safety.set_relay_malfunction(True) + self.assertEqual(self.safety.safety_fwd_hook(2, 0x161), -1) + self.assertFalse(self.safety.safety_tx_hook(libsafety_py.make_CANPacket(0x164, 0, bytes(8)))) + + def test_stuck_throttle_counter_withdraws_controls(self): + throttle = libsafety_py.make_CANPacket(0x140, 0, bytes(8)) + for counter in range(16): + throttle.data[1] = counter + self.assertTrue(self.safety.safety_rx_hook(throttle)) + self.safety.set_controls_allowed(True) + for _ in range(16): + self.safety.safety_rx_hook(throttle) + self.assertFalse(self.safety.get_controls_allowed()) + + +def test_release_rejects_unsupported_preglobal_parameters(): + safety = libsafety_py.ffi.dlopen(libsafety_py._build_libsafety(release=True)) + steering = libsafety_py.make_CANPacket(0x164, 0, bytes(8)) + stock_acc = SubaruSafetyFlags.PREGLOBAL_OUTBACK_STOCK_ACC + for unsupported in (0, SubaruSafetyFlags.PREGLOBAL_REVERSED_DRIVER_TORQUE, + stock_acc | SubaruSafetyFlags.PREGLOBAL_REVERSED_DRIVER_TORQUE): + assert safety.set_safety_hooks(CarParams.SafetyModel.subaruPreglobal, stock_acc) == 0 + assert safety.safety_tx_hook(steering) + assert safety.set_safety_hooks(CarParams.SafetyModel.subaruPreglobal, unsupported) != 0 + assert not safety.safety_tx_hook(steering) diff --git a/opendbc_repo/opendbc/safety/tests/test_subaru_stock_aol.py b/opendbc_repo/opendbc/safety/tests/test_subaru_stock_aol.py index 54daca375b..5d8a3eb221 100644 --- a/opendbc_repo/opendbc/safety/tests/test_subaru_stock_aol.py +++ b/opendbc_repo/opendbc/safety/tests/test_subaru_stock_aol.py @@ -47,8 +47,9 @@ class TestSubaruStockAol(unittest.TestCase): ('ES_Status', {'Cruise_Activated': int(cruise)}, 2 if self.param == 16 else 1), ('ES_DashStatus', {'Cruise_On': int(main)}, 2), ] - if not omit_distance and self.param in (17, 209, 465, 4096, 4104, 4608, 4616): - frames.append(('ES_Distance', {'Cruise_Fault': int(acc_fault)}, 1 if self.param in (17, 209, 465) else 2)) + if not omit_distance and self.param in (17, 145, 209, 401, 465, 1169, 1425, 4096, 4104, 4608, 4616): + frames.append(('ES_Distance', {'Cruise_Fault': int(acc_fault)}, + 1 if self.param in (17, 145, 209, 401, 465, 1169, 1425) else 2)) if not omit_gear: frames.append(('Transmission', {'Gear': gear}, gear_bus)) for name, fields, bus in frames: @@ -79,7 +80,7 @@ class TestSubaruStockAol(unittest.TestCase): self.assertEqual(self.feed(temporary=True), 0) self.assertEqual(self.feed(), 1) self.assertEqual(self.feed(main=False), 0) - self.assertEqual(self.feed(main=True), int(param in (17, 209, 465, 4096, 4104, 4608, 4616))) + self.assertEqual(self.feed(main=True), int(param in (17, 145, 209, 465, 4096, 4104, 4608, 4616))) self.assertEqual(self.feed(cruise=True), 1) def test_permanent_fault_and_rx_fault_require_fresh_ordinary_engagement(self): diff --git a/opendbc_repo/opendbc/safety/tests/test_volkswagen_stock_aol.py b/opendbc_repo/opendbc/safety/tests/test_volkswagen_stock_aol.py index 0529aa8beb..ae4890fda3 100644 --- a/opendbc_repo/opendbc/safety/tests/test_volkswagen_stock_aol.py +++ b/opendbc_repo/opendbc/safety/tests/test_volkswagen_stock_aol.py @@ -145,6 +145,31 @@ class TestVolkswagenStockAol(unittest.TestCase): assert self.safety.aol_get_permission_mask() == 0 assert not self.safety.safety_tx_hook(self.packet("HCA_01", {"HCA_01_LM_Offset": 0, "HCA_01_Sendestatus": 0})) + def test_aol_hud_transmission_matches_forwarding_ownership(self): + for word in (8, 24, 9, 25, 40, 41): + self.configure(word) + assert not self.safety.safety_tx_hook(self.packet('LDW_02', {})) + assert self.safety.safety_fwd_hook(2, 0x397) == 0 + + for word in (8, 24): + self.configure(word) + self.arm() + assert not self.safety.safety_tx_hook(self.packet('LDW_02', {})) + assert self.safety.safety_fwd_hook(2, 0x397) == 0 + + assert self.safety.safety_tx_hook(self.packet('HCA_01', {'HCA_01_LM_Offset': 4, 'HCA_01_Sendestatus': 1})) + assert self.safety.safety_tx_hook(self.packet('LDW_02', {})) + assert self.safety.safety_fwd_hook(2, 0x397) == -1 + + assert self.safety.safety_tx_hook(self.packet('HCA_01', {})) + assert not self.safety.safety_tx_hook(self.packet('LDW_02', {})) + assert self.safety.safety_fwd_hook(2, 0x397) == 0 + + assert self.safety.safety_tx_hook(self.packet('HCA_01', {'HCA_01_LM_Offset': 4, 'HCA_01_Sendestatus': 1})) + self.safety.set_timer(self.time + 300_001) + assert not self.safety.safety_tx_hook(self.packet('LDW_02', {})) + assert self.safety.safety_fwd_hook(2, 0x397) == 0 + def test_fresh_accepted_hud_eps_forwarding_and_ownership_expiry(self): self.configure() self.arm() diff --git a/openpilot/common/hardware/comma/agnos-c3.json b/openpilot/common/hardware/comma/agnos-c3.json index ae1c165c54..38a1d50427 100644 --- a/openpilot/common/hardware/comma/agnos-c3.json +++ b/openpilot/common/hardware/comma/agnos-c3.json @@ -56,30 +56,30 @@ }, { "name": "boot", - "url": "https://files.firestar.link/x/qpboin0zv4z6/boot-60397e34da19778d4520fba43e4202b4a9a714657dcf72a61f081b61c371b692.img.xz", - "hash": "60397e34da19778d4520fba43e4202b4a9a714657dcf72a61f081b61c371b692", - "hash_raw": "60397e34da19778d4520fba43e4202b4a9a714657dcf72a61f081b61c371b692", + "url": "https://files.firestar.link/x/9ap4aonicpfw/boot-5a259ecbf209ccb98f8c2fc64cbb229d18d9c50d1463d202808486d0402b3b8f.img.xz", + "hash": "5a259ecbf209ccb98f8c2fc64cbb229d18d9c50d1463d202808486d0402b3b8f", + "hash_raw": "5a259ecbf209ccb98f8c2fc64cbb229d18d9c50d1463d202808486d0402b3b8f", "size": 49043456, "sparse": false, "full_check": true, "has_ab": true, - "ondevice_hash": "dc8798b668e90698bd6f9a0873e9d633f2654504193caed618663e722d42c983", + "ondevice_hash": "e98a31e106c43944f2061ac810a4404055a5a7fad6c95c54b0a130abfea76fd9", "fallback_urls": [ - "https://files-east.firestar.link/x/reby1gotp8k4/boot-60397e34da19778d4520fba43e4202b4a9a714657dcf72a61f081b61c371b692.img.xz" + "https://files-east.firestar.link/x/faj7a3putgwt/boot-5a259ecbf209ccb98f8c2fc64cbb229d18d9c50d1463d202808486d0402b3b8f.img.xz" ] }, { "name": "system", - "url": "https://files.firestar.link/x/qpboin0zv4z6/system-00eea7b6d5c91d25571e76619d1c4a4ca7e732b701ec35cea6b8d767e3cf85c8.img.xz", - "hash": "f426085b78b068ce752dc14779560fd212647452d701c6ba4a0122d4d70f62ce", - "hash_raw": "00eea7b6d5c91d25571e76619d1c4a4ca7e732b701ec35cea6b8d767e3cf85c8", + "url": "https://files.firestar.link/x/9ap4aonicpfw/system-140d8497bc8f476b2ed2863b7389994e46be47ab94b3fbf4cfc6a23dd32167a6.img.xz", + "hash": "bc499a0253c73fe4426bb5ec49b23f679d2969c8da29626743efbfaef6b66262", + "hash_raw": "140d8497bc8f476b2ed2863b7389994e46be47ab94b3fbf4cfc6a23dd32167a6", "size": 4718592000, "sparse": true, "full_check": false, "has_ab": true, - "ondevice_hash": "d6d9a2ab6d74a0d04fa9758f047e52b80f2a3db0570ce0a4fe40320183342680", + "ondevice_hash": "d1913079953686a44b2e54c59b5b32f51424ca26e298d5f1154bdce86a553ed0", "fallback_urls": [ - "https://files-east.firestar.link/x/reby1gotp8k4/system-00eea7b6d5c91d25571e76619d1c4a4ca7e732b701ec35cea6b8d767e3cf85c8.img.xz" + "https://files-east.firestar.link/x/faj7a3putgwt/system-140d8497bc8f476b2ed2863b7389994e46be47ab94b3fbf4cfc6a23dd32167a6.img.xz" ] } ] diff --git a/openpilot/common/hardware/comma/agnos.json b/openpilot/common/hardware/comma/agnos.json index 70c3ff1ca8..f80ed28cb8 100644 --- a/openpilot/common/hardware/comma/agnos.json +++ b/openpilot/common/hardware/comma/agnos.json @@ -56,30 +56,30 @@ }, { "name": "boot", - "url": "https://files.firestar.link/x/qpboin0zv4z6/boot-60397e34da19778d4520fba43e4202b4a9a714657dcf72a61f081b61c371b692.img.xz", - "hash": "60397e34da19778d4520fba43e4202b4a9a714657dcf72a61f081b61c371b692", - "hash_raw": "60397e34da19778d4520fba43e4202b4a9a714657dcf72a61f081b61c371b692", + "url": "https://files.firestar.link/x/9ap4aonicpfw/boot-5a259ecbf209ccb98f8c2fc64cbb229d18d9c50d1463d202808486d0402b3b8f.img.xz", + "hash": "5a259ecbf209ccb98f8c2fc64cbb229d18d9c50d1463d202808486d0402b3b8f", + "hash_raw": "5a259ecbf209ccb98f8c2fc64cbb229d18d9c50d1463d202808486d0402b3b8f", "size": 49043456, "sparse": false, "full_check": true, "has_ab": true, - "ondevice_hash": "dc8798b668e90698bd6f9a0873e9d633f2654504193caed618663e722d42c983", + "ondevice_hash": "e98a31e106c43944f2061ac810a4404055a5a7fad6c95c54b0a130abfea76fd9", "fallback_urls": [ - "https://files-east.firestar.link/x/reby1gotp8k4/boot-60397e34da19778d4520fba43e4202b4a9a714657dcf72a61f081b61c371b692.img.xz" + "https://files-east.firestar.link/x/faj7a3putgwt/boot-5a259ecbf209ccb98f8c2fc64cbb229d18d9c50d1463d202808486d0402b3b8f.img.xz" ] }, { "name": "system", - "url": "https://files.firestar.link/x/qpboin0zv4z6/system-00eea7b6d5c91d25571e76619d1c4a4ca7e732b701ec35cea6b8d767e3cf85c8.img.xz", - "hash": "f426085b78b068ce752dc14779560fd212647452d701c6ba4a0122d4d70f62ce", - "hash_raw": "00eea7b6d5c91d25571e76619d1c4a4ca7e732b701ec35cea6b8d767e3cf85c8", + "url": "https://files.firestar.link/x/9ap4aonicpfw/system-140d8497bc8f476b2ed2863b7389994e46be47ab94b3fbf4cfc6a23dd32167a6.img.xz", + "hash": "bc499a0253c73fe4426bb5ec49b23f679d2969c8da29626743efbfaef6b66262", + "hash_raw": "140d8497bc8f476b2ed2863b7389994e46be47ab94b3fbf4cfc6a23dd32167a6", "size": 4718592000, "sparse": true, "full_check": false, "has_ab": true, - "ondevice_hash": "d6d9a2ab6d74a0d04fa9758f047e52b80f2a3db0570ce0a4fe40320183342680", + "ondevice_hash": "d1913079953686a44b2e54c59b5b32f51424ca26e298d5f1154bdce86a553ed0", "fallback_urls": [ - "https://files-east.firestar.link/x/reby1gotp8k4/system-00eea7b6d5c91d25571e76619d1c4a4ca7e732b701ec35cea6b8d767e3cf85c8.img.xz" + "https://files-east.firestar.link/x/faj7a3putgwt/system-140d8497bc8f476b2ed2863b7389994e46be47ab94b3fbf4cfc6a23dd32167a6.img.xz" ] } ] diff --git a/openpilot/common/hardware/comma/agnos.py b/openpilot/common/hardware/comma/agnos.py index 084efa31a4..696c62f755 100755 --- a/openpilot/common/hardware/comma/agnos.py +++ b/openpilot/common/hardware/comma/agnos.py @@ -66,6 +66,10 @@ def phone_uplink_active() -> bool: return active() +class AgnosImageError(Exception): + pass + + class StreamingDecompressor: def __init__(self, url: str) -> None: if phone_uplink_active(): @@ -110,12 +114,14 @@ class StreamingDecompressor: def unsparsify(f: StreamingDecompressor) -> Generator[bytes, None, None]: # https://source.android.com/devices/bootloader/images#sparse-format magic = struct.unpack("I", f.read(4))[0] - assert(magic == 0xed26ff3a) + if magic != 0xed26ff3a: + raise AgnosImageError("Invalid sparse image magic") # Version major = struct.unpack("H", f.read(2))[0] minor = struct.unpack("H", f.read(2))[0] - assert(major == 1 and minor == 0) + if (major, minor) != (1, 0): + raise AgnosImageError("Unsupported sparse image version") f.read(2) # file header size f.read(2) # chunk header size @@ -138,7 +144,7 @@ def unsparsify(f: StreamingDecompressor) -> Generator[bytes, None, None]: elif chunk_type == 0xcac3: # Don't care yield b"" else: - raise Exception("Unhandled sparse chunk type") + raise AgnosImageError("Unhandled sparse chunk type") # noop wrapper with same API as unsparsify() for non sparse images @@ -215,7 +221,7 @@ def extract_compressed_image(target_slot_number: int, partition: dict, cloudlog, path = get_partition_path(target_slot_number, partition) downloader = StreamingDecompressor(partition['url']) - with open(path, 'wb+') as out: + with downloader.req, open(path, 'wb+') as out: # Flash partition last_p = 0 raw_hash = hashlib.sha256() @@ -231,13 +237,13 @@ def extract_compressed_image(target_slot_number: int, partition: dict, cloudlog, progress(f"Downloading and writing AGNOS {partition['name']}", p) if raw_hash.hexdigest().lower() != partition['hash_raw'].lower(): - raise Exception(f"Raw hash mismatch '{raw_hash.hexdigest().lower()}'") + raise AgnosImageError(f"Raw hash mismatch '{raw_hash.hexdigest().lower()}'") if downloader.sha256.hexdigest().lower() != partition['hash'].lower(): - raise Exception("Uncompressed hash mismatch") + raise AgnosImageError("Uncompressed hash mismatch") if out.tell() != partition['size']: - raise Exception("Uncompressed size mismatch") + raise AgnosImageError("Uncompressed size mismatch") os.sync() @@ -289,22 +295,20 @@ def flash_agnos_update(manifest_path: str, target_slot_number: int, cloudlog, st subprocess.run(f"abctl --set_unbootable {target_slot_number}", shell=True) for partition in update: - success = False - - for retries in range(10): + urls = [partition['url'], *partition.get('fallback_urls', [])] + for attempt in range(10): + url = urls[attempt % len(urls)] try: if progress is not None: progress(f"Downloading and verifying AGNOS {partition['name']}", None) - flash_partition(target_slot_number, partition, cloudlog, standalone, progress=progress) - success = True + flash_partition(target_slot_number, {**partition, "url": url}, cloudlog, standalone, progress=progress) break - except requests.exceptions.RequestException: - cloudlog.exception("Failed") - cloudlog.info(f"Failed to download {partition['name']}, retrying ({retries})") - time.sleep(10) - - if not success: + except (requests.exceptions.RequestException, AgnosImageError, lzma.LZMAError, struct.error): + cloudlog.exception("Failed to download or verify %s", partition["name"]) + if (attempt + 1) % len(urls) == 0 and attempt < 9: + time.sleep(10) + else: cloudlog.info(f"Failed to flash {partition['name']}, aborting") raise Exception("Maximum retries exceeded") diff --git a/openpilot/common/hardware/comma/tests/test_agnos_updater.py b/openpilot/common/hardware/comma/tests/test_agnos_updater.py index f096426707..d68a85a404 100644 --- a/openpilot/common/hardware/comma/tests/test_agnos_updater.py +++ b/openpilot/common/hardware/comma/tests/test_agnos_updater.py @@ -1,6 +1,7 @@ import json import os import requests +from urllib3.exceptions import HTTPError TEST_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__))) MANIFEST = os.path.join(TEST_DIR, "../agnos.json") @@ -14,8 +15,18 @@ class TestAgnosUpdater(OpenpilotTestCase): m = json.load(f) for img in m: - r = requests.head(img['url'], timeout=10) - r.raise_for_status() - assert r.headers['Content-Type'] == "application/x-xz" + headers = {'Range': 'bytes=0-5', 'Accept-Encoding': 'identity'} + failures = [] + for url in (img['url'], *img.get('fallback_urls', [])): + try: + with requests.get(url, headers=headers, stream=True, timeout=10) as response: + response.raise_for_status() + if response.raw.read(6) == b'\xfd7zXZ\x00': + break + failures.append('response was not XZ') + except (requests.RequestException, HTTPError) as exc: + failures.append(type(exc).__name__) + else: + self.fail(f"{img['name']}: no mirror returned XZ ({', '.join(failures)})") if not img['sparse']: assert img['hash'] == img['hash_raw'] diff --git a/openpilot/common/hardware/comma/tests/test_c3_firmware_compatibility.py b/openpilot/common/hardware/comma/tests/test_c3_firmware_compatibility.py index 4ecd2205f6..c23ef68b80 100644 --- a/openpilot/common/hardware/comma/tests/test_c3_firmware_compatibility.py +++ b/openpilot/common/hardware/comma/tests/test_c3_firmware_compatibility.py @@ -1,7 +1,7 @@ import json from pathlib import Path import subprocess -from unittest.mock import Mock, patch +from unittest.mock import MagicMock, Mock, patch import pytest @@ -13,7 +13,8 @@ ROOT = Path(__file__).resolve().parents[5] @pytest.fixture def manifest(tmp_path): path = tmp_path / 'agnos.json' - path.write_text(json.dumps([{'name': 'abl', 'hash_raw': agnos.INCOMPATIBLE_C3_ABL, 'full_check': True}])) + path.write_text(json.dumps([{'name': 'abl', 'url': 'https://example.invalid/abl.xz', + 'hash_raw': agnos.INCOMPATIBLE_C3_ABL, 'full_check': True}])) return path @@ -189,7 +190,7 @@ def test_agnos_download_reports_partition_progress(tmp_path): data = b'firmware' digest = hashlib.sha256(data).hexdigest() partition = {'name': 'system', 'url': 'https://example.invalid/system.xz', 'size': len(data), 'sparse': False, 'hash': digest, 'hash_raw': digest} - downloader = Mock(sha256=hashlib.sha256(data)) + downloader = Mock(sha256=hashlib.sha256(data), req=MagicMock()) downloader.read.side_effect = [data[:4], data[4:], b''] progress = Mock() with patch.object(agnos, 'get_partition_path', return_value=str(tmp_path / 'partition')), \ @@ -198,3 +199,4 @@ def test_agnos_download_reports_partition_progress(tmp_path): assert [call.args for call in progress.call_args_list] == [ ('Downloading and writing AGNOS system', 50), ('Downloading and writing AGNOS system', 100)] assert (tmp_path / 'partition').read_bytes() == data + downloader.req.__exit__.assert_called_once_with(None, None, None) diff --git a/openpilot/common/libcommon.a b/openpilot/common/libcommon.a index d784b175c6..0994a361b4 100644 Binary files a/openpilot/common/libcommon.a and b/openpilot/common/libcommon.a differ diff --git a/openpilot/common/libparams_c.so b/openpilot/common/libparams_c.so index a8e12ab20d..8a5ce62058 100755 Binary files a/openpilot/common/libparams_c.so and b/openpilot/common/libparams_c.so differ diff --git a/openpilot/common/params_keys.h b/openpilot/common/params_keys.h index 138cd62760..d1d4fd3f34 100644 --- a/openpilot/common/params_keys.h +++ b/openpilot/common/params_keys.h @@ -161,6 +161,7 @@ inline static std::unordered_map keys = { {"LeadDepartingAlert", {PERSISTENT, BOOL, "0"}}, {"LoudBlindspotAlert", {PERSISTENT, BOOL, "0"}}, {"LoudBlindspotAlertWhenDisengaged", {PERSISTENT, BOOL, "0"}}, + {"LoudBlindspotAlertMuteAtStandstill", {PERSISTENT, BOOL, "0"}}, {"SignalMetrics", {PERSISTENT, BOOL, "0"}}, {"PIPPreviewEnabled", {PERSISTENT, BOOL, "0"}}, {"PIPPreviewMask", {PERSISTENT | DONT_LOG, JSON, "{\"width\":1928,\"height\":1208,\"center_left\":[315,548],\"center_right\":[1571,539],\"crop_size\":580}"}}, diff --git a/openpilot/selfdrive/car/card.py b/openpilot/selfdrive/car/card.py index 349ce5f3c2..06b0012027 100644 --- a/openpilot/selfdrive/car/card.py +++ b/openpilot/selfdrive/car/card.py @@ -37,44 +37,25 @@ from openpilot.selfdrive.car.cruise import LOW_SPEED_CRUISE_ON_SET, SlcWheelCont from openpilot.starpilot.speed_limits import physical_actions as slc_physical from openpilot.starpilot.aol.intent import AolProcessFaultContext, independent_axis_requested, read_settings from openpilot.starpilot.aol.transport_pause import TransportPauseFeedback, cp_identity -from opendbc.car.honda.stock_aol import ( - qualified as qualified_honda_stock_aol, native_observation as honda_native_observation, - temporary_restriction as honda_temporary_restriction, -) -from opendbc.car.volkswagen.stock_aol import (native_observation as volkswagen_native_observation, - safety_config as volkswagen_aol_safety_config) -from openpilot.starpilot.car.volkswagen.aol import (qualified as qualified_volkswagen_aol, - temporary_restriction as volkswagen_temporary_restriction) +from opendbc.car.honda.stock_aol import qualified as qualified_honda_stock_aol, native_observation as honda_native_observation +from opendbc.car.volkswagen.stock_aol import safety_config as volkswagen_aol_safety_config +from openpilot.starpilot.car.volkswagen.aol import qualified as qualified_volkswagen_aol from openpilot.starpilot.car.rivian.aol import retained_brake_lateral_intent as rivian_brake_intent_retained -from opendbc.car.rivian.stock_aol import (qualified as qualified_rivian_aol, - native_observation as rivian_native_observation, - temporary_restriction as rivian_temporary_restriction) -from opendbc.car.mazda.stock_aol import (qualified as qualified_mazda_aol, - native_observation as mazda_native_observation, - temporary_restriction as mazda_temporary_restriction) -from opendbc.car.tesla.preap.aol import ( - qualified as qualified_tesla_preap, native_observation as preap_native_observation, - temporary_restriction as preap_temporary_restriction, -) -from opendbc.car.ford.aol import ( - qualified as qualified_ford_aol, native_observation as ford_native_observation, - temporary_restriction as ford_temporary_restriction, -) -from opendbc.car.hyundai.canfd_angle_aol import native_observation, temporary_restriction, qualified as qualified_angle_aol +from opendbc.car.rivian.stock_aol import qualified as qualified_rivian_aol +from opendbc.car.mazda.stock_aol import qualified as qualified_mazda_aol +from opendbc.car.tesla.preap.aol import qualified as qualified_tesla_preap +from opendbc.car.ford.aol import qualified as qualified_ford_aol +from opendbc.car.hyundai.canfd_angle_aol import qualified as qualified_angle_aol from opendbc.car.hyundai.canfd_owner import config_index as hyundai_canfd_config_index from opendbc.car.hyundai.captured_adrv_startup import CapturedADRVStartup -from openpilot.starpilot.car.nissan.aol import ( - qualified as qualified_nissan_aol, native_observation as nissan_native_observation, - temporary_restriction as nissan_temporary_restriction, -) -from openpilot.starpilot.car.volvo.aol import ( - qualified as qualified_volvo_aol, native_observation as volvo_native_observation, - temporary_restriction as volvo_temporary_restriction, -) +from openpilot.starpilot.car.nissan.aol import qualified as qualified_nissan_aol +from openpilot.starpilot.car.volvo.aol import qualified as qualified_volvo_aol from openpilot.starpilot.car.hyundai.aol import aol_safety_config as hyundai_aol_safety_config, pending_stock_angle_arm from openpilot.starpilot.car.hyundai.aol import retained_shared_long_cancel_intent as hkg_cancel_intent_retained from openpilot.starpilot.car.ford.aol import (brake_pause_active as ford_brake_pause_active, awaiting_initial_request as ford_awaiting_initial_request) +from openpilot.starpilot.car.subaru import aol as subaru_aol +from openpilot.starpilot.aol.card_native import native_handlers from openpilot.starpilot.aol.runtime import AXIS_MAX_AGE_NS, current_axis, current_native from openpilot.starpilot.aol.vehicle import create_intent as create_aol_intent, native_latch_rejected, policy_for as aol_policy_for from openpilot.starpilot.aol.wire import IntentState, encode_intent @@ -146,9 +127,9 @@ def can_comm_callbacks(logcan: messaging.SubSocket, sendcan: messaging.PubSocket curve_press_receipt = slc_physical.curve_press_receipt -def alpha_long_requested(params, *, is_release: bool) -> bool: +def alpha_long_requested(params, *, is_release: bool, openpilot_enabled: bool = True) -> bool: """Retain saved intent on release branches without granting Alpha authority.""" - return not is_release and params.get_bool("AlphaLongitudinalEnabled") + return openpilot_enabled and not is_release and params.get_bool("AlphaLongitudinalEnabled") class Car: @@ -189,7 +170,6 @@ class Car: self.switchback_event_sequence = 0 publish_services = ['sendcan', 'carState', 'carParams', 'carOutput', 'radarTracks', 'starpilotCarState'] self.car_gps_publisher = CarGpsPublisher() - # One existing event channel also carries source-qualified Switchback gestures. publish_services.append('slcCruiseEvent') self.wheel_publisher = WheelPublisher(self.params) self.wheel_commands = () @@ -245,14 +225,13 @@ class Car: self.pm.sock['aolIntentWire'] = messaging.pub_sock('aolIntentWire') if CI is None: - # wait for one pandaState and one CAN packet print("Waiting for CAN messages...") while True: can = messaging.recv_one_retry(self.can_sock) if len(can.can) > 0: break - alpha_long_allowed = alpha_long_requested(self.params, is_release=is_release) + alpha_long_allowed = alpha_long_requested(self.params, is_release=is_release, openpilot_enabled=openpilot_enabled_toggle) cached_params = None cached_params_raw = get_cache(self.params, "CarParamsCache") @@ -319,7 +298,7 @@ class Car: from openpilot.starpilot.car.ford.longitudinal_preferences import prepare_release_long as prepare_ford_release_long cp = prepare_ford_release_long(cp, self.params, is_release=is_release, enabled=openpilot_enabled_toggle) return self.vehicle_startup.prepare(cp, interfaces[candidate], self.can_callbacks, - requested=alpha_long_allowed and not is_release and openpilot_enabled_toggle, + requested=alpha_long_allowed, admission=self.startup_diagnostic_admission, defer_until_controls=True) self.CI = get_car(*self.can_callbacks, obd_callback(self.params), alpha_long_allowed, is_release, cached_params, @@ -328,7 +307,6 @@ class Car: self.RI = interfaces[self.CI.CP.carFingerprint].RadarInterface(self.CI.CP) self.CP = self.CI.CP - # continue onto next fingerprinting step in pandad self.params.put_bool("FirmwareQueryDone", True, block=True) else: self.CI, self.CP = CI, CI.CP @@ -367,7 +345,6 @@ class Car: self.vehicle_startup.configure(self.CI) if self.CP.secOcRequired: - # Copy user key if available try: with open("/cache/params/SecOCKey") as f: user_key = f.readline().strip() @@ -460,7 +437,6 @@ class Car: if not self.ioniq6_previous_cp_saved: self.save_previous_car_params() - # Write CarParams for controls and radard self.vehicle_startup.seal_publication() cp_bytes = self.CP.to_bytes() from openpilot.starpilot.car.tesla.pedal_startup import install as install_preap_pedal @@ -535,7 +511,6 @@ class Car: can_received_ns = time.monotonic_ns() can_list = can_capnp_to_list(can_strs) - # Update carState from CAN observe_controller_can(self.CI, can_list) CS = self.CI.update(can_list) self.RI.v_ego = CS.vEgo # the Honda Bosch-A decoder bounds a reversing coast with it @@ -553,8 +528,7 @@ class Car: distance_owner = getattr(self, 'gm_distance', None) distance_observation = distance_owner.update(can_list) if distance_owner is not None else None - # Direct state_update callers retain eager radar behavior. The production - # loop consumes this exact CAN batch after carState and control publication. + # Direct callers run radar eagerly. The loop runs it after control publication. self._deferred_radar_can = can_list if defer_radar else None RD = None if defer_radar else self.radar_update(can_list) @@ -564,7 +538,6 @@ class Car: can_rcv_valid = len(can_strs) > 0 - # Check for CAN timeout if not can_rcv_valid: self.can_rcv_cum_timeout_counter += 1 @@ -705,14 +678,10 @@ class Car: ) native_reset = False if permission_owner: - observe = (volvo_native_observation if volvo_aol else rivian_native_observation if rivian_aol else - volkswagen_native_observation if volkswagen_aol else nissan_native_observation if nissan_aol else - preap_native_observation if preap_aol else mazda_native_observation if mazda_aol else self.aol_honda_native_observation if honda_aol else - ford_native_observation if ford_aol else native_observation) - restrict = (volvo_temporary_restriction if volvo_aol else rivian_temporary_restriction if rivian_aol else - volkswagen_temporary_restriction if volkswagen_aol else nissan_temporary_restriction if nissan_aol else - preap_temporary_restriction if preap_aol else mazda_temporary_restriction if mazda_aol else honda_temporary_restriction if honda_aol else - ford_temporary_restriction if ford_aol else temporary_restriction) + observe, restrict = native_handlers( + self, volvo_aol=volvo_aol, rivian_aol=rivian_aol, volkswagen_aol=volkswagen_aol, nissan_aol=nissan_aol, + preap_aol=preap_aol, mazda_aol=mazda_aol, honda_aol=honda_aol, ford_aol=ford_aol, + ) preap_observation = {} if preap_aol: cancel_stamp = int(self.CI.CS.preap.cancel_echo_stamp_ns) @@ -875,6 +844,10 @@ class Car: self.v_cruise_helper.update_v_cruise(CS, self.sm['carControl'].enabled, self.is_metric, pending, slc_enabled=getattr(self, 'slc_control_enabled', getattr(self, 'slc_replay', False)), wheel_context=wheel_context) + redneck_cruise = getattr(self, 'redneck_cruise', None) + if redneck_cruise is not None and (self.slc_match_on_engage or redneck_cruise.set_match_ns): + now_ns = int(self.can_log_mono_time) if REPLAY and hasattr(self, 'can_log_mono_time') else time.monotonic_ns() + redneck_cruise.match_limit_on_set(self, CS, now_ns) if self.sm['carControl'].enabled and not self.CC_prev.enabled: target, initial = None, None now_ns = int(self.can_log_mono_time) if REPLAY and hasattr(self, 'can_log_mono_time') else time.monotonic_ns() @@ -1086,7 +1059,6 @@ class Car: self.pm.send('carParams', cp_send) self.car_params_published = True - # publish new carOutput co_send = messaging.new_message('carOutput') co_send.valid = self.sm.all_checks(['carControl']) co_send.carOutput.actuatorsOutput = self.last_actuators_output @@ -1417,8 +1389,7 @@ class Car: holder = getattr(self, 'vehicle_startup', None) if holder is None or holder.owner is None: return - # Python controls and receive times use MONOTONIC. Panda/CAN producers - # use BOOTTIME, which can diverge after suspend. + # MONOTONIC controls time can diverge from Panda BOOTTIME after suspend. clocks = clock_pair_ns() mono_ns, boot_ns = clocks if clocks is not None else (0, 0) sm = self.sm @@ -1821,7 +1792,6 @@ class Car: self.ioniq6_restore_callbacks = self.can_callbacks elif self.vehicle_startup.owner is None: self.CI.init(self.CP, *self.can_callbacks) - # signal pandad to switch to car safety mode self.params.put_bool("ControlsReady", True) self.ci_initialized = True @@ -1912,7 +1882,6 @@ class Car: return steering_authority = getattr(self.CI.CS, 'steering_authority', None) monitored_steering = self.CP.brand == 'gm' and steering_authority is not None and steering_authority.enabled - # send car controls over can now_nanos = (self.volt_cc_now_boot_ns if getattr(self, 'volt_cc_selected', False) else self.can_log_mono_time if REPLAY else time.clock_gettime_ns(time.CLOCK_BOOTTIME) if self.volt_startup_keepalive() or monitored_steering else @@ -1932,6 +1901,7 @@ class Car: update_subaru_sng(self, CS, CC, now_nanos) from openpilot.starpilot.car.subaru.stop_start_caller import update as update_subaru_startup update_subaru_startup(self, now_nanos) + subaru_aol.sync_legacy_card_lateral(self, CS, CC) if getattr(self, "redneck_cruise", None): self.redneck_cruise.update(self, CS, CC, now_nanos) self.last_actuators_output, can_sends = self.CI.apply(CC, now_nanos) @@ -2006,6 +1976,7 @@ class Car: self.initial_cruise_speed = self.params.get("InitialCruiseSpeedKph", return_default=True) if self.aol_card_intent is not None: self.aol_card_intent.settings = read_settings(self.params) + subaru_aol.sync_legacy_card_aol(self) now = time.monotonic() if now >= next_cruise_read: self.v_cruise_helper.low_speed_on_set = self.params.get_bool(LOW_SPEED_CRUISE_ON_SET) diff --git a/openpilot/selfdrive/car/tests/test_alpha_long_saved_intent.py b/openpilot/selfdrive/car/tests/test_alpha_long_saved_intent.py index b096896021..4f948d9c12 100644 --- a/openpilot/selfdrive/car/tests/test_alpha_long_saved_intent.py +++ b/openpilot/selfdrive/car/tests/test_alpha_long_saved_intent.py @@ -6,13 +6,35 @@ from openpilot.selfdrive.car.card import alpha_long_requested @pytest.mark.parametrize('release', [False, True]) +@pytest.mark.parametrize('enabled', [False, True]) @pytest.mark.parametrize('raw', [None, b'0', b'1']) -def test_retained_choice_is_separate_from_release_runtime_authority(tmp_path, release, raw): +def test_retained_choice_is_separate_from_release_runtime_authority(tmp_path, release, enabled, raw): params = Params(str(tmp_path)) path = Path(params.get_param_path('AlphaLongitudinalEnabled')) if raw is not None: path.write_bytes(raw) - assert alpha_long_requested(params, is_release=release) == (raw == b'1' and not release) + assert alpha_long_requested(params, is_release=release, openpilot_enabled=enabled) == (raw == b'1' and not release and enabled) assert (path.read_bytes() if path.exists() else None) == raw # Returning to a supported development branch restores intent without a rewrite. assert alpha_long_requested(params, is_release=False) == (raw == b'1') + + +def test_disabled_master_starts_from_stock_radar_hda1_parameters(tmp_path): + from opendbc.car import gen_empty_fingerprint + from opendbc.car.hyundai.interface import CarInterface + from opendbc.car.hyundai.values import CAR + + params = Params(str(tmp_path)) + params.put_bool('AlphaLongitudinalEnabled', True, block=True) + fingerprints = gen_empty_fingerprint() + fingerprints[0].update({0x1CF: 8, 0x130: 32, 0x35: 32, 0x175: 24, 0xA0: 24, 0xEA: 24, 0x1A0: 32}) + identity = CAR.KIA_SORENTO_4TH_GEN + requested = alpha_long_requested(params, is_release=False, openpilot_enabled=False) + cp = CarInterface.get_params(identity, fingerprints, [], requested, False, False) + assert cp.pcmCruise and not cp.openpilotLongitudinalControl + assert not CarInterface.startup_required(cp) + + requested = alpha_long_requested(params, is_release=False, openpilot_enabled=True) + cp = CarInterface.get_params(identity, fingerprints, [], requested, False, False) + assert cp.openpilotLongitudinalControl and CarInterface.startup_required(cp) + assert params.get_bool('AlphaLongitudinalEnabled') diff --git a/openpilot/selfdrive/controls/controlsd.py b/openpilot/selfdrive/controls/controlsd.py index 2621b5541e..b66fd74715 100755 --- a/openpilot/selfdrive/controls/controlsd.py +++ b/openpilot/selfdrive/controls/controlsd.py @@ -29,7 +29,12 @@ from openpilot.starpilot.car.hyundai.lateral_fault import LateralFaultLatch from openpilot.starpilot.feature_runtime import enabled as feature_enabled from openpilot.starpilot.vehicle_preferences import VehicleStartupPreferences from openpilot.starpilot.lateral.pause import LateralPause, read_settings as read_lateral_pause -from openpilot.starpilot.lateral.model_turn_assist import CURVATURE_HOLD_CONFIRM_MIN, ModelTurnAssist, update_twitch_guard +from openpilot.starpilot.lateral.model_turn_assist import ( + CURVATURE_HOLD_CONFIRM_MIN, + ModelTurnAssist, + limit_curvature_to_plan, + update_twitch_guard, +) from openpilot.starpilot.lateral.turn_unlock import TurnUnlock from openpilot.starpilot.lateral.turn_initiation_preferences import TurnInitiationPreference from openpilot.starpilot.aol.runtime import ( @@ -71,6 +76,26 @@ LaneChangeDirection = log.LaneChangeDirection ACTUATOR_FIELDS = tuple(car.CarControl.Actuators.schema.fields.keys()) +def _update_subaru_line_visibility(prev_vis: bool | None, timer: float, prob: float | bool, dt: float) -> tuple[bool, float]: + """Apply confidence hysteresis and asymmetric debounce to Subaru dash lane line visibility.""" + val = (1.0 if prob else 0.0) if isinstance(prob, bool) else float(prob) + if prev_vis is None: + return val >= 0.55, 0.0 + if prev_vis: + if val < 0.40: + timer += max(0.0, dt) + if timer >= 0.25 - 1e-6: + return False, 0.0 + return True, timer + return True, 0.0 + if val >= 0.55: + timer += max(0.0, dt) + if timer >= 1.0 - 1e-6: + return True, 0.0 + return False, timer + return False, 0.0 + + class Controls: def __init__(self, *, predict_lane_clearance: bool = False) -> None: if type(predict_lane_clearance) is not bool: @@ -133,6 +158,19 @@ class Controls: self.model_turn_assist = ModelTurnAssist() self.turn_unlock = TurnUnlock() self.turn_initiation_preferences = TurnInitiationPreference(self.params) + self.subaru_twitch_guard_armed = False + self.aol_enabled_setting = True + self.lateral_off = False + self._aol_left_line_vis: bool | None = None + self._aol_left_line_timer: float = 0.0 + self._aol_right_line_vis: bool | None = None + self._aol_right_line_timer: float = 0.0 + self._subaru_aol_last_read_ns = 0 + self._prev_cruise_available = False + self._prev_aol_enabled: bool | None = None + self._prev_lkas_button_pressed = False + if self.CP.carFingerprint == "SUBARU_LEGACY_2025": + self._refresh_subaru_aol_setting(0, force=True) self.lane_centering_controller = ( LaneCenteringController(body=interface_dimensions(self.CI, self.CP), body_required=True) if predict_lane_clearance else LaneCenteringController() ) @@ -221,6 +259,12 @@ class Controls: assist_enabled = self.vehicle_startup_preferences.turn_assist and model_turn_assist_supported(self.CP) self.turn_assist_enabled = lambda: assist_enabled + def _refresh_subaru_aol_setting(self, now_ns: int, *, force: bool = False) -> None: + if not force and (now_ns - self._subaru_aol_last_read_ns) < 500_000_000: + return + self._subaru_aol_last_read_ns = now_ns + self.aol_enabled_setting = self.params.get_bool("AlwaysOnLateral") + def _configure_route_tune(self, manual_status): from openpilot.starpilot.flm.offroad_runtime import configure @@ -468,6 +512,32 @@ class Controls: if cycle_timing is not None: cycle_timing.mark() + legacy_2025 = self.CP.carFingerprint == "SUBARU_LEGACY_2025" + if legacy_2025: + mode_now_ns = int(self.sm.logMonoTime['carState']) if os.getenv('REPLAY') == '1' else time.monotonic_ns() + self._refresh_subaru_aol_setting(mode_now_ns) + aol = bool(self.aol_enabled_setting) + raw_lkas_pressed = any(be.type == car.CarState.ButtonEvent.Type.lkas and be.pressed for be in CS.buttonEvents) + if not CS.cruiseState.available: + self._prev_lkas_button_pressed = False + lkas_pressed = raw_lkas_pressed and not self._prev_lkas_button_pressed + self._prev_lkas_button_pressed = raw_lkas_pressed + if not CS.cruiseState.available: + self.lateral_off = not aol + else: + entered_mode = (not self._prev_cruise_available) or (aol != self._prev_aol_enabled) + if entered_mode: + self.lateral_off = not aol + elif lkas_pressed and aol: + self.lateral_off = not self.lateral_off + self._prev_cruise_available = bool(CS.cruiseState.available) + self._prev_aol_enabled = aol + else: + self.lateral_off = False + + if legacy_2025 and ((self.aol_enabled_setting and self.lateral_off) or (not self.aol_enabled_setting and not CC.enabled)): + CC.latActive = False + actuators = CC.actuators actuators.longControlState = self.LoC.long_control_state @@ -555,6 +625,14 @@ class Controls: elif getattr(self, 'model_turn_assist', None) is not None: self.model_turn_assist.reset() self.model_turn_assist.twitch_guard_armed = update_twitch_guard(False, CS.vEgo, CS.standstill) + if not assist_ready and self.CP.carFingerprint == "SUBARU_LEGACY_2025": + subaru_gear_ok = CS.gearShifter in (car.CarState.GearShifter.drive, car.CarState.GearShifter.low, car.CarState.GearShifter.manumatic) + if self.sm.all_checks(['modelV2']) and not CS.steerFaultTemporary and not CS.steerFaultPermanent and subaru_gear_ok: + self.subaru_twitch_guard_armed = update_twitch_guard(self.subaru_twitch_guard_armed, CS.vEgo, CS.standstill) + if CC.latActive and not CS.leftBlinker and not CS.rightBlinker and self.subaru_twitch_guard_armed: + new_desired_curvature = limit_curvature_to_plan(model_v2, new_desired_curvature, CS.vEgo, min_reach=4.0) + else: + self.subaru_twitch_guard_armed = update_twitch_guard(False, CS.vEgo, CS.standstill) if self.highway_smoothing_supported: preferences = getattr(self, "live_steering_preferences", None) if preferences is not None: @@ -807,11 +885,49 @@ class Controls: hudControl.leadDistanceBars = self.sm['selfdriveState'].personality.raw + 1 hudControl.visualAlert = self.sm['selfdriveState'].alertHudVisual - hudControl.rightLaneVisible = True - hudControl.leftLaneVisible = True - if self.sm.valid['driverAssistance']: - hudControl.leftLaneDepart = self.sm['driverAssistance'].leftLaneDeparture - hudControl.rightLaneDepart = self.sm['driverAssistance'].rightLaneDeparture + if self.CP.carFingerprint == "SUBARU_LEGACY_2025": + lines_allowed = bool( + CS.cruiseState.available and ( + (self.aol_enabled_setting and not self.lateral_off) or + (not self.aol_enabled_setting and CC.enabled) + ) + ) + if not lines_allowed: + self._aol_left_line_vis = None + self._aol_left_line_timer = 0.0 + self._aol_right_line_vis = None + self._aol_right_line_timer = 0.0 + hudControl.lanesVisible = False + hudControl.leftLaneVisible = False + hudControl.rightLaneVisible = False + hudControl.leftLaneDepart = False + hudControl.rightLaneDepart = False + else: + hudControl.lanesVisible = True + lane_probs = self.sm['modelV2'].laneLineProbs if self.sm.valid['modelV2'] and len(self.sm['modelV2'].laneLineProbs) >= 3 else None + if lane_probs is not None: + left_prob = float(lane_probs[1]) + right_prob = float(lane_probs[2]) + self._aol_left_line_vis, self._aol_left_line_timer = _update_subaru_line_visibility( + self._aol_left_line_vis, self._aol_left_line_timer, left_prob, DT_CTRL + ) + self._aol_right_line_vis, self._aol_right_line_timer = _update_subaru_line_visibility( + self._aol_right_line_vis, self._aol_right_line_timer, right_prob, DT_CTRL + ) + hudControl.leftLaneVisible = bool(self._aol_left_line_vis) + hudControl.rightLaneVisible = bool(self._aol_right_line_vis) + else: + hudControl.leftLaneVisible = True + hudControl.rightLaneVisible = True + if self.sm.valid['driverAssistance']: + hudControl.leftLaneDepart = self.sm['driverAssistance'].leftLaneDeparture + hudControl.rightLaneDepart = self.sm['driverAssistance'].rightLaneDeparture + else: + hudControl.rightLaneVisible = True + hudControl.leftLaneVisible = True + if self.sm.valid['driverAssistance']: + hudControl.leftLaneDepart = self.sm['driverAssistance'].leftLaneDeparture + hudControl.rightLaneDepart = self.sm['driverAssistance'].rightLaneDeparture feedback_input_limited = self.steer_limited_by_safety if CC.latActive: diff --git a/openpilot/selfdrive/monitoring/dmonitoringd.py b/openpilot/selfdrive/monitoring/dmonitoringd.py index f03f8915c5..2bdf90684a 100755 --- a/openpilot/selfdrive/monitoring/dmonitoringd.py +++ b/openpilot/selfdrive/monitoring/dmonitoringd.py @@ -9,6 +9,18 @@ from openpilot.starpilot.aol.runtime import monitoring_lateral_engaged from openpilot.starpilot.feature_runtime import requested as feature_requested +def _read_allow_manumatic(params: Params) -> bool | None: + try: + cp_bytes = params.get("CarParams") + except Exception: + return None + if not cp_bytes: + return None + from opendbc.car.structs import car + with car.CarParams.from_bytes(cp_bytes) as cp: + return cp.carFingerprint == "SUBARU_LEGACY_2025" + + def dmonitoringd_thread(): config_realtime_process([0, 1, 2, 3], 5) @@ -18,7 +30,10 @@ def dmonitoringd_thread(): required = ['driverStateV2', 'extrinsicsCalibration', 'carState', 'selfdriveState', 'modelV2'] sm = messaging.SubMaster(required + (['aolAxisState', 'aolSafetyWire'] if aol_replay else []), poll='driverStateV2') - DM = DriverMonitoring(rhd_saved=params.get_bool("IsRhdDetected"), always_on=params.get_bool("AlwaysOnDM")) + allow_manumatic = _read_allow_manumatic(params) + cp_checked = allow_manumatic is not None + DM = DriverMonitoring(rhd_saved=params.get_bool("IsRhdDetected"), always_on=params.get_bool("AlwaysOnDM"), + allow_manumatic=bool(allow_manumatic)) demo_mode=False # 20Hz <- dmonitoringmodeld @@ -43,6 +58,11 @@ def dmonitoringd_thread(): if sm['driverStateV2'].frameId % 40 == 1: DM.always_on = params.get_bool("AlwaysOnDM") demo_mode = params.get_bool("IsDriverViewEnabled") + if not cp_checked: + allow_manumatic = _read_allow_manumatic(params) + if allow_manumatic is not None: + DM.allow_manumatic = allow_manumatic + cp_checked = True # save rhd virtual toggle every 5 mins if (sm['driverStateV2'].frameId % 6000 == 0 and not demo_mode and diff --git a/openpilot/selfdrive/monitoring/policy.py b/openpilot/selfdrive/monitoring/policy.py index 4ac6056d94..dba559cf9a 100644 --- a/openpilot/selfdrive/monitoring/policy.py +++ b/openpilot/selfdrive/monitoring/policy.py @@ -129,7 +129,7 @@ def face_orientation_from_model(orient_model, pos_model, rpy_calib): class DriverMonitoring: - def __init__(self, rhd_saved=False, settings=None, always_on=False): + def __init__(self, rhd_saved=False, settings=None, always_on=False, allow_manumatic=False): # init policy settings self.settings = settings if settings is not None else DRIVER_MONITOR_SETTINGS() @@ -143,6 +143,7 @@ class DriverMonitoring: self.alert_level = AlertLevel.none self.always_on = always_on + self.allow_manumatic = allow_manumatic self.distracted_types = defaultdict(bool) self.driver_distracted = False self.driver_distraction_filter = FirstOrderFilter(0., self.settings._DISTRACTED_FILTER_TS, DT_DMON) @@ -441,7 +442,12 @@ class DriverMonitoring: else: car_speed = sm['carState'].vEgo enabled = sm['selfdriveState'].enabled or aol_lateral_engaged - wrong_gear = sm['carState'].gearShifter not in (car.CarState.GearShifter.drive, car.CarState.GearShifter.low) + allowed_gears = ( + (car.CarState.GearShifter.drive, car.CarState.GearShifter.low, car.CarState.GearShifter.manumatic) + if self.allow_manumatic else + (car.CarState.GearShifter.drive, car.CarState.GearShifter.low) + ) + wrong_gear = sm['carState'].gearShifter not in allowed_gears lowspeed = car_speed < self.settings._ALERT_MIN_SPEED driver_engaged = sm['carState'].steeringPressed or sm['carState'].gasPressed brake_disengage_prob = sm['modelV2'].meta.disengagePredictions.brakeDisengageProbs[0] # brake disengage prob in next 2s diff --git a/openpilot/selfdrive/pandad/pandad.py b/openpilot/selfdrive/pandad/pandad.py index 3fd338d2ed..0c9fd2409d 100755 --- a/openpilot/selfdrive/pandad/pandad.py +++ b/openpilot/selfdrive/pandad/pandad.py @@ -17,19 +17,52 @@ from openpilot.starpilot.panda_wake import FirmwareChoice, firmware_path, startu DEFAULT_FIRMWARE_CHOICE = FirmwareChoice() +PACKET_VERSIONS = (Panda.HEALTH_PACKET_VERSION, Panda.CAN_PACKET_VERSION) +REGISTER_DIVERGENT = 1 << 18 def get_expected_signature(mcu_type: McuType, choice: FirmwareChoice = DEFAULT_FIRMWARE_CHOICE) -> bytes: fn = firmware_path(FW_PATH, mcu_type.config.app_fn, choice) return Panda.get_signature_from_firmware(fn) -def flash_panda(panda_serial: str, choice: FirmwareChoice = DEFAULT_FIRMWARE_CHOICE): +def recover_internal_bootstub(panda: Panda, panda_serial: str, fw_path: str) -> None: + dfu_serial = panda.get_dfu_serial() + if dfu_serial is None: + raise PandaProtocolMismatch("Internal Panda recovery identity unavailable") + panda.close() + HARDWARE.recover_internal_panda() + if not Panda.wait_for_dfu(dfu_serial, timeout=5): + raise PandaProtocolMismatch("Internal Panda did not enter recovery mode") + with PandaDFU(dfu_serial) as dfu: + dfu.recover() + if not Panda.wait_for_panda(panda_serial, timeout=5): + raise PandaProtocolMismatch("Internal Panda did not return after bootstub recovery") + panda.reconnect() + if not panda.bootstub: + raise PandaProtocolMismatch("Recovered internal Panda did not enter bootstub") + panda.flash(fn=fw_path) + + +def needs_cuatro_bootstub_repair(health, incompatible_app: bool) -> bool: + # An older bootstub can start the signed app with incompatible register state. + if health["ignition_line"] or health["ignition_can"] or health["controls_allowed"]: + return False + faults = health["faults"] + return faults == REGISTER_DIVERGENT or (incompatible_app and faults == 0) + + +def flash_panda(panda_serial: str, choice: FirmwareChoice = DEFAULT_FIRMWARE_CHOICE, *, + bootstub_repairs: set[str] | None = None): panda = Panda(panda_serial) if choice.alternate and panda.get_type() not in (Panda.HW_TYPE_DOS, Panda.HW_TYPE_TRES, Panda.HW_TYPE_RED_PANDA, Panda.HW_TYPE_CUATRO): choice = FirmwareChoice() fw_path = firmware_path(FW_PATH, panda.get_mcu_type().config.app_fn, choice) fw_signature = get_expected_signature(panda.get_mcu_type(), choice) internal_panda = panda.is_internal() + internal_cuatro = HARDWARE.get_device_type() == "mici" and panda.is_connected_spi() and panda.get_type() == Panda.HW_TYPE_CUATRO + if bootstub_repairs is None: + bootstub_repairs = set() + incompatible_app = False panda_version = "bootstub" if panda.bootstub else panda.get_version() panda_signature = b"" if panda.bootstub else panda.get_signature() @@ -37,6 +70,8 @@ def flash_panda(panda_serial: str, choice: FirmwareChoice = DEFAULT_FIRMWARE_CHO if panda.bootstub or panda_signature != fw_signature: cloudlog.info("Panda firmware out of date, update required") + if internal_cuatro and not panda.bootstub: + incompatible_app = panda.get_packets_versions() != PACKET_VERSIONS if not panda.bootstub and panda.get_type() == Panda.HW_TYPE_TRES and panda.is_connected_spi() and HARDWARE.get_device_type() == "tizi": panda.reset(enter_bootstub=True, reconnect=False) if Panda.wait_for_panda(panda_serial, timeout=1): @@ -56,10 +91,20 @@ def flash_panda(panda_serial: str, choice: FirmwareChoice = DEFAULT_FIRMWARE_CHO bootstub_version = panda.get_version() cloudlog.info(f"Flashed firmware not booting, flashing development bootloader. {bootstub_version=}, {internal_panda=}") if internal_panda: - HARDWARE.recover_internal_panda() - panda.recover(reset=(not internal_panda)) + recover_internal_bootstub(panda, panda_serial, fw_path) + incompatible_app = False + bootstub_repairs.add(panda_serial) + elif not panda.recover(): + raise PandaProtocolMismatch("External Panda recovery did not complete") cloudlog.info("Done flashing bootstub") + if (internal_cuatro and panda_serial not in bootstub_repairs and not panda.bootstub + and panda.get_signature() == fw_signature and panda.get_packets_versions() == PACKET_VERSIONS + and needs_cuatro_bootstub_repair(panda.health(), incompatible_app)): + bootstub_repairs.add(panda_serial) + cloudlog.warning("Recovering internal CUATRO bootstub after incompatible firmware") + recover_internal_bootstub(panda, panda_serial, fw_path) + if panda.bootstub: cloudlog.info("Panda still not booting, exiting") raise AssertionError @@ -69,7 +114,7 @@ def flash_panda(panda_serial: str, choice: FirmwareChoice = DEFAULT_FIRMWARE_CHO cloudlog.info("Version mismatch after flashing, exiting") raise AssertionError - if panda.get_packets_versions() != (Panda.HEALTH_PACKET_VERSION, Panda.CAN_PACKET_VERSION): + if panda.get_packets_versions() != PACKET_VERSIONS: panda.close() raise PandaProtocolMismatch("Panda CAN or health protocol hash mismatch after firmware validation") @@ -138,6 +183,7 @@ def main() -> None: count = 0 legacy_migration_attempted = False + bootstub_repairs: set[str] = set() while not do_exit: try: cloudlog.event("pandad.flash_and_connect", count=count) @@ -173,7 +219,7 @@ def main() -> None: choice = startup_choice(Params()) if len(set(panda_serials)) != len(panda_serials): raise ValueError('Duplicate Panda hardware serial') - selected_firmware = {serial: flash_panda(serial, choice) for serial in panda_serials} + selected_firmware = {serial: flash_panda(serial, choice, bootstub_repairs=bootstub_repairs) for serial in panda_serials} ordering = [] for serial in panda_serials: with Panda(serial) as panda: diff --git a/openpilot/selfdrive/selfdrived/selfdrived.py b/openpilot/selfdrive/selfdrived/selfdrived.py index 01acde784b..9bc315483b 100755 --- a/openpilot/selfdrive/selfdrived/selfdrived.py +++ b/openpilot/selfdrive/selfdrived/selfdrived.py @@ -26,7 +26,7 @@ from openpilot.starpilot.gps.source import observation as gps_observation from openpilot.selfdrive.car.car_events import CarEvents from openpilot.selfdrive.locationd.helpers import PoseCalibrator, Pose -from openpilot.selfdrive.selfdrived.events import Events, ET, Alert, Priority as AlertPriority +from openpilot.selfdrive.selfdrived.events import Events, ET, Alert, EngagementAlert, Priority as AlertPriority from openpilot.selfdrive.selfdrived.bookmarks import BookmarkCounter from openpilot.starpilot.bookmark_state import BookmarkCheckpoint from openpilot.starpilot.longitudinal.force_stop_alert import HoldAlertState, EVENT_TYPE as FORCE_STOP_HOLD @@ -41,7 +41,8 @@ from openpilot.starpilot.aol.vehicle import native_bootstrap_supported from opendbc.car.gm.steering_authority import monitored_profile from openpilot.starpilot.car.gm.steering_companion import SteeringCompanion from openpilot.starpilot.car.hyundai.aol import qualified_ioniq6 -from opendbc.car.gm.values import GMFlags, is_volt_ascm_longitudinal, malibu_hybrid_profile +from opendbc.car.gm.values import CAR as GM_CAR +from opendbc.car.gm.values import GMFlags, is_ordinary_camera_profile, is_volt_ascm_longitudinal, malibu_hybrid_profile from openpilot.starpilot.aol.intent import read_settings from openpilot.starpilot.aol.intent_companion import IntentCompanion from openpilot.starpilot.aol.transport_pause import AvailabilityPause, TransportPause, availability_only, cp_identity, healthy_transport @@ -218,7 +219,8 @@ class SelfdriveD: self.disengage_on_accelerator = self.params.get_bool("DisengageOnAccelerator") self.radar_recovery_enabled = self.params.get_bool("RadarRecoveryAlert") self.blindspot_alert_settings = (self.params.get_bool("LoudBlindspotAlert"), - self.params.get_bool("LoudBlindspotAlertWhenDisengaged")) + self.params.get_bool("LoudBlindspotAlertWhenDisengaged"), + self.params.get_bool("LoudBlindspotAlertMuteAtStandstill")) car_recognized = self.CP.brand != 'mock' @@ -253,6 +255,7 @@ class SelfdriveD: self.dm_lockout_set = False self.dm_uncertain_alerted = False self.state_machine = StateMachine() + self.legacy_2025_green_wheel_active = False self.rk = Ratekeeper(100, print_delay_threshold=None) # Observational only. Do not cache this qualification for authority decisions. @@ -1002,8 +1005,9 @@ class SelfdriveD: active_longitudinal and sample.gasPressed and not held_gas or sample.seatbeltUnlatched or sample.accFaulted or sample.doorOpen or physical_cancel(sample, self.CP) or qualified_gm(self.CP) and not sample.cruiseState.available or - sample.gearShifter not in (car.CarState.GearShifter.drive, car.CarState.GearShifter.sport, - car.CarState.GearShifter.low, car.CarState.GearShifter.brake) + (sample.gearShifter not in (car.CarState.GearShifter.drive, car.CarState.GearShifter.sport, + car.CarState.GearShifter.low, car.CarState.GearShifter.brake) and + not (self.CP.carFingerprint == "SUBARU_LEGACY_2025" and sample.gearShifter == car.CarState.GearShifter.manumatic)) for sample, valid in samples): return 0 native = current_native(self.sm, self.CP, now_ns=now_ns, axis_session_id=session) @@ -1187,11 +1191,12 @@ class SelfdriveD: now_ns = time.monotonic_ns() drive = int(self.sm['deviceState'].startedMonoTime) if self.sm['deviceState'].started else 0 from openpilot.starpilot.audio.blindspot_alert import ALERT_TYPE as BSM_ALERT, blindspot_alert - loud, without_lateral = getattr(self, 'blindspot_alert_settings', (False, False)) + loud, without_lateral, mute_at_standstill = getattr(self, 'blindspot_alert_settings', (False, False, False)) blindspot = blindspot_alert(CS, self.sm, loud=loud, without_lateral=without_lateral, lane_change_blocked=EventName.laneChangeBlocked in self.events.names, now_ns=now_ns, car_ns=getattr(self, 'aol_car_state_log_ns', 0), - car_valid=getattr(self, 'conditional_car_state_valid', False)) + car_valid=getattr(self, 'conditional_car_state_valid', False), + mute_at_standstill=mute_at_standstill) if blindspot is not None: alerts = [alert for alert in alerts if alert.alert_type != 'laneChangeBlocked/warning'] self.AM.alerts.pop('laneChangeBlocked/warning', None) @@ -1290,6 +1295,27 @@ class SelfdriveD: # Saturation is already ignored during override; retire its held presentation too. alerts = [alert for alert in alerts if alert.alert_type != 'steerSaturated/warning'] self.AM.alerts.pop('steerSaturated/warning', None) + if self.CP.carFingerprint == "SUBARU_LEGACY_2025": + alerts = [alert for alert in alerts if alert.alert_type not in ("pcmEnable/enable", "pcmDisable/userDisable")] + self.AM.alerts.pop("pcmEnable/enable", None) + self.AM.alerts.pop("pcmDisable/userDisable", None) + if self.CP.passive: + self.legacy_2025_green_wheel_active = False + elif self.sm.seen['carControl'] and self.sm.valid['carControl'] and CS.canValid and not CS.canTimeout: + hud = self.sm['carControl'].hudControl + green_wheel_active = bool( + CS.cruiseState.available and hud.lanesVisible and + not CS.steerFaultTemporary and not CS.steerFaultPermanent + ) + if green_wheel_active != self.legacy_2025_green_wheel_active: + self.legacy_2025_green_wheel_active = green_wheel_active + chime = EngagementAlert( + log.SelfdriveState.AudibleAlert.engage if green_wheel_active else log.SelfdriveState.AudibleAlert.disengage + ) + chime.alert_type = "legacy2025AolEngage/enable" if green_wheel_active else "legacy2025AolDisengage/userDisable" + chime.event_type = "legacy2025AolChime" + self.AM.alerts.pop("legacy2025AolDisengage/userDisable" if green_wheel_active else "legacy2025AolEngage/enable", None) + alerts.append(chime) from openpilot.starpilot.audio.departure_alert import protect_safety_alerts retained = () if departure: @@ -1876,6 +1902,11 @@ class SelfdriveD: pause_brake_mps = self.aol_settings.pause_brake_mps if self.aol_settings is not None else 0.0 if reverse_pause: lateral_events = [event for event in lateral_events if event not in (EventName.wrongGear, EventName.reverseGear)] + # The Trax entry speed must not drop braking during an engaged stop. + trax_below_entry_speed = ( + self.CP.carFingerprint == GM_CAR.CHEVROLET_TRAX and EventName.belowEngageSpeed in lateral_events and + self.enabled and self.active and CS.cruiseState.enabled and not self.CP.flags & GMFlags.NO_CAMERA and + is_ordinary_camera_profile(self.CP, longitudinal=True)) return decide_axes( standard_lateral=self.active, standard_longitudinal=bool(self.enabled and self.CP.openpilotLongitudinalControl and not raw_longitudinal_withdrawal(self.CP, CS, self.sm, native, session=self.aol_session_id, now_ns=now_ns) and @@ -1911,7 +1942,7 @@ class SelfdriveD: source_ns=getattr(self, 'aol_car_state_log_ns', 0), now_ns=now_ns, axis_session_id=getattr(self, 'aol_session_id', '')), cruise_main_required=getattr(self, 'aol_cruise_main_required', True), - allow_below_engage_speed=bool((is_volt_ascm_longitudinal(self.CP) or + allow_below_engage_speed=trax_below_entry_speed or bool((is_volt_ascm_longitudinal(self.CP) or stock_ascm_independent_lateral(self.CP) or independent_lateral_below_engage(self.CP, intent, enabled=self.enabled, active=self.active)) and @@ -1927,7 +1958,8 @@ class SelfdriveD: self.sm['driverMonitoringState'].alertLevel == AlertLevel.three)), pause_brake_mps=pause_brake_mps, gear_pause=reverse_pause, - lateral_inhibit=self.aol_dm_lateral_inhibit or sng_standstill_lateral_inhibit(self.CP, CS) or + lateral_inhibit=self.aol_dm_lateral_inhibit or sng_standstill_lateral_inhibit( + self.CP, CS, initial_wait=bool(native is None or not native.lateralAllowed)) or volkswagen_lateral_output_inhibited(self.CP, CS) or any( sample.steerFaultTemporary or pause_brake_mps > 0 and sample.brakePressed and not sample.standstill and sample.vEgo < pause_brake_mps @@ -2437,7 +2469,8 @@ class SelfdriveD: self.disengage_on_accelerator = self.params.get_bool("DisengageOnAccelerator") self.radar_recovery_enabled = self.params.get_bool("RadarRecoveryAlert") self.blindspot_alert_settings = (self.params.get_bool("LoudBlindspotAlert"), - self.params.get_bool("LoudBlindspotAlertWhenDisengaged")) + self.params.get_bool("LoudBlindspotAlertWhenDisengaged"), + self.params.get_bool("LoudBlindspotAlertMuteAtStandstill")) self.departure_alert_settings = (self.params.get_bool("GreenLightAlert"), self.params.get_bool("LeadDepartingAlert")) self.nostalgia_enabled = nostalgia_saved_enabled(self.params) self.refresh_saved_driving_mode(time.monotonic_ns()) diff --git a/openpilot/selfdrive/ui/mici/onroad/cameraview.py b/openpilot/selfdrive/ui/mici/onroad/cameraview.py index 3e063b595d..8dc2efce37 100644 --- a/openpilot/selfdrive/ui/mici/onroad/cameraview.py +++ b/openpilot/selfdrive/ui/mici/onroad/cameraview.py @@ -15,80 +15,79 @@ from openpilot.starpilot.ui.camera_color import ROAD_COLOR_SHADER, road_color_st -# Choose fragment shader based on platform capabilities -if COMMA_HARDWARE: - FRAME_FRAGMENT_SHADER = """ - #version 300 es - #extension GL_OES_EGL_image_external_essl3 : enable - precision mediump float; - in vec2 fragTexCoord; - uniform samplerExternalOES texture0; - out vec4 fragColor; - uniform int engaged; - uniform int enhance_driver; - uniform float color_strength; - """ + ROAD_COLOR_SHADER + """ +FRAME_FRAGMENT_SHADER = """ + #version 300 es + #extension GL_OES_EGL_image_external_essl3 : enable + precision mediump float; + in vec2 fragTexCoord; + uniform samplerExternalOES texture0; + out vec4 fragColor; + uniform int engaged; + uniform int enhance_driver; + uniform float color_strength; + """ + ROAD_COLOR_SHADER + """ - void main() { - vec4 color = texture(texture0, fragTexCoord); - if (enhance_driver == 1) { - if (engaged == 1) { - float gray = dot(color.rgb, vec3(0.299, 0.587, 0.114)); - color.rgb = mix(vec3(gray), color.rgb, 0.2); - color.rgb = clamp((color.rgb - 0.5) * 1.2 + 0.5, 0.0, 1.0); - color.rgb = pow(color.rgb, vec3(1.0/1.28)); - } else { - color.rgb *= 0.85; - } - float brightness = 1.1; - color.rgb = color.rgb + 0.15; - color.rgb = clamp((color.rgb - 0.5) * (brightness * 0.8) + 0.5, 0.0, 1.0); - color.rgb = color.rgb * color.rgb * (3.0 - 2.0 * color.rgb); - color.rgb = pow(color.rgb, vec3(0.8)); + void main() { + vec4 color = texture(texture0, fragTexCoord); + if (enhance_driver == 1) { + if (engaged == 1) { + float gray = dot(color.rgb, vec3(0.299, 0.587, 0.114)); + color.rgb = mix(vec3(gray), color.rgb, 0.2); + color.rgb = clamp((color.rgb - 0.5) * 1.2 + 0.5, 0.0, 1.0); + color.rgb = pow(color.rgb, vec3(1.0/1.28)); } else { - color.rgb = road_color(color.rgb, color_strength); + color.rgb *= 0.85; } - fragColor = vec4(color.rgb, color.a); + float brightness = 1.1; + color.rgb = color.rgb + 0.15; + color.rgb = clamp((color.rgb - 0.5) * (brightness * 0.8) + 0.5, 0.0, 1.0); + color.rgb = color.rgb * color.rgb * (3.0 - 2.0 * color.rgb); + color.rgb = pow(color.rgb, vec3(0.8)); + } else { + color.rgb = road_color(color.rgb, color_strength); } - """ -else: - FRAME_FRAGMENT_SHADER = VERSION + """ - in vec2 fragTexCoord; - uniform sampler2D texture0; - uniform sampler2D texture1; - out vec4 fragColor; - uniform int engaged; - uniform int enhance_driver; - uniform float color_strength; - """ + ROAD_COLOR_SHADER + """ + fragColor = vec4(color.rgb, color.a); + } + """ - void main() { - float y = texture(texture0, fragTexCoord).r; - vec2 uv = texture(texture1, fragTexCoord).ra - 0.5; - vec3 rgb = vec3(y + 1.402*uv.y, y - 0.344*uv.x - 0.714*uv.y, y + 1.772*uv.x); - if (enhance_driver == 1) { - if (engaged == 1) { - float gray = dot(rgb, vec3(0.299, 0.587, 0.114)); - rgb = mix(vec3(gray), rgb, 0.2); - rgb = clamp((rgb - 0.5) * 1.2 + 0.5, 0.0, 1.0); - } else { - rgb *= 0.85; - } - float brightness = 1.1; - rgb = rgb + 0.15; - rgb = clamp((rgb - 0.5) * (brightness * 0.8) + 0.5, 0.0, 1.0); - rgb = rgb * rgb * (3.0 - 2.0 * rgb); - rgb = pow(rgb, vec3(0.8)); +TEXTURE_FRAGMENT_SHADER = VERSION + """ + in vec2 fragTexCoord; + uniform sampler2D texture0; + uniform sampler2D texture1; + out vec4 fragColor; + uniform int engaged; + uniform int enhance_driver; + uniform float color_strength; + """ + ROAD_COLOR_SHADER + """ + + void main() { + float y = texture(texture0, fragTexCoord).r; + vec2 uv = texture(texture1, fragTexCoord).ra - 0.5; + vec3 rgb = vec3(y + 1.402*uv.y, y - 0.344*uv.x - 0.714*uv.y, y + 1.772*uv.x); + if (enhance_driver == 1) { + if (engaged == 1) { + float gray = dot(rgb, vec3(0.299, 0.587, 0.114)); + rgb = mix(vec3(gray), rgb, 0.2); + rgb = clamp((rgb - 0.5) * 1.2 + 0.5, 0.0, 1.0); } else { - rgb = road_color(rgb, color_strength); + rgb *= 0.85; } - fragColor = vec4(rgb, 1.0); + float brightness = 1.1; + rgb = rgb + 0.15; + rgb = clamp((rgb - 0.5) * (brightness * 0.8) + 0.5, 0.0, 1.0); + rgb = rgb * rgb * (3.0 - 2.0 * rgb); + rgb = pow(rgb, vec3(0.8)); + } else { + rgb = road_color(rgb, color_strength); } - """ + fragColor = vec4(rgb, 1.0); + } + """ class CameraView(BaseCameraView): FRAGMENT_SHADER = FRAME_FRAGMENT_SHADER + TEXTURE_FRAGMENT_SHADER = TEXTURE_FRAGMENT_SHADER def __init__(self, name: str, stream_type: VisionStreamType): super().__init__(name, stream_type) @@ -245,14 +244,6 @@ class CameraView(BaseCameraView): # Initialize textures for new stream self._initialize_textures() - def _initialize_textures(self): - self._clear_textures() - if not COMMA_HARDWARE: - self.texture_y = rl.load_texture_from_image(rl.Image(None, int(self.client.stride), - int(self.client.height), 1, rl.PixelFormat.PIXELFORMAT_UNCOMPRESSED_GRAYSCALE)) - self.texture_uv = rl.load_texture_from_image(rl.Image(None, int(self.client.stride // 2), - int(self.client.height // 2), 1, rl.PixelFormat.PIXELFORMAT_UNCOMPRESSED_GRAY_ALPHA)) - if __name__ == "__main__": diff --git a/openpilot/selfdrive/ui/onroad/cameraview.py b/openpilot/selfdrive/ui/onroad/cameraview.py index d51bb824b6..93fb9a064b 100644 --- a/openpilot/selfdrive/ui/onroad/cameraview.py +++ b/openpilot/selfdrive/ui/onroad/cameraview.py @@ -41,51 +41,50 @@ void main() { } """ -# Choose fragment shader based on platform capabilities -if COMMA_HARDWARE: - FRAME_FRAGMENT_SHADER = """ - #version 300 es - #extension GL_OES_EGL_image_external_essl3 : enable - precision mediump float; - in vec2 fragTexCoord; - uniform samplerExternalOES texture0; - out vec4 fragColor; - uniform float color_strength; - uniform int road_camera; - """ + ROAD_COLOR_SHADER + """ - void main() { - vec4 color = texture(texture0, fragTexCoord); - if (road_camera == 1) { - color.rgb = road_color(color.rgb, color_strength); - } else { - color.rgb = pow(color.rgb, vec3(1.0/1.28)); - } - fragColor = vec4(color.rgb, color.a); +FRAME_FRAGMENT_SHADER = """ + #version 300 es + #extension GL_OES_EGL_image_external_essl3 : enable + precision mediump float; + in vec2 fragTexCoord; + uniform samplerExternalOES texture0; + out vec4 fragColor; + uniform float color_strength; + uniform int road_camera; + """ + ROAD_COLOR_SHADER + """ + void main() { + vec4 color = texture(texture0, fragTexCoord); + if (road_camera == 1) { + color.rgb = road_color(color.rgb, color_strength); + } else { + color.rgb = pow(color.rgb, vec3(1.0/1.28)); } - """ -else: - FRAME_FRAGMENT_SHADER = VERSION + """ - in vec2 fragTexCoord; - uniform sampler2D texture0; - uniform sampler2D texture1; - out vec4 fragColor; - uniform float color_strength; - uniform int road_camera; - """ + ROAD_COLOR_SHADER + """ - void main() { - float y = texture(texture0, fragTexCoord).r; - vec2 uv = texture(texture1, fragTexCoord).ra - 0.5; - vec3 rgb = vec3(y + 1.402*uv.y, y - 0.344*uv.x - 0.714*uv.y, y + 1.772*uv.x); - if (road_camera == 1) { - rgb = road_color(rgb, color_strength); - } - fragColor = vec4(rgb, 1.0); + fragColor = vec4(color.rgb, color.a); + } + """ + +TEXTURE_FRAGMENT_SHADER = VERSION + """ + in vec2 fragTexCoord; + uniform sampler2D texture0; + uniform sampler2D texture1; + out vec4 fragColor; + uniform float color_strength; + uniform int road_camera; + """ + ROAD_COLOR_SHADER + """ + void main() { + float y = texture(texture0, fragTexCoord).r; + vec2 uv = texture(texture1, fragTexCoord).ra - 0.5; + vec3 rgb = vec3(y + 1.402*uv.y, y - 0.344*uv.x - 0.714*uv.y, y + 1.772*uv.x); + if (road_camera == 1) { + rgb = road_color(rgb, color_strength); } - """ + fragColor = vec4(rgb, 1.0); + } + """ class CameraView(Widget): FRAGMENT_SHADER = FRAME_FRAGMENT_SHADER + TEXTURE_FRAGMENT_SHADER = TEXTURE_FRAGMENT_SHADER def __init__(self, name: str, stream_type: VisionStreamType): super().__init__() @@ -101,8 +100,10 @@ class CameraView(Widget): self._texture_needs_update = True self.last_connection_attempt: float = 0.0 - self.shader = rl.load_shader_from_memory(VERTEX_SHADER, self.FRAGMENT_SHADER) - self._texture1_loc: int = rl.get_shader_location(self.shader, "texture1") if not COMMA_HARDWARE else -1 + self._use_egl = COMMA_HARDWARE and init_egl() + fragment = self.FRAGMENT_SHADER if self._use_egl else self.TEXTURE_FRAGMENT_SHADER + self.shader = rl.load_shader_from_memory(VERTEX_SHADER, fragment) + self._texture1_loc = -1 if self._use_egl else rl.get_shader_location(self.shader, "texture1") self._init_color_uniforms(stream_type) self.frame: VisionBuf | None = None @@ -116,10 +117,7 @@ class CameraView(Widget): self._placeholder_color: rl.Color | None = None # Initialize EGL for zero-copy rendering on COMMA_HARDWARE - if COMMA_HARDWARE: - if not init_egl(): - raise RuntimeError("Failed to initialize EGL") - + if self._use_egl: # Create a 1x1 pixel placeholder texture for EGL image binding temp_image = rl.gen_image_color(1, 1, rl.BLACK) self.egl_texture = rl.load_texture_from_image(temp_image) @@ -250,7 +248,7 @@ class CameraView(Widget): dst_rect = rl.Rectangle(x_offset, y_offset, scale_x, scale_y) # Render with appropriate method - if COMMA_HARDWARE: + if self._use_egl: self._render_egl(src_rect, dst_rect) else: self._render_textures(src_rect, dst_rect) @@ -295,8 +293,14 @@ class CameraView(Widget): # Update textures with new frame data if self._texture_needs_update: - y_data = self.frame.data[: self.frame.uv_offset] - uv_data = self.frame.data[self.frame.uv_offset:] + y_size = self.texture_y.width * self.texture_y.height + uv_size = 2 * self.texture_uv.width * self.texture_uv.height + uv_offset = self.frame.uv_offset + data = self.frame.data + if uv_offset < y_size or len(data) < uv_offset + uv_size: + return + y_data = data[:y_size] + uv_data = data[uv_offset:uv_offset + uv_size] rl.update_texture(self.texture_y, y_data) rl.update_texture(self.texture_uv, uv_data) @@ -372,9 +376,10 @@ class CameraView(Widget): def _initialize_textures(self): self._clear_textures() - if not COMMA_HARDWARE: - stride, height = self.client.stride, self.client.height - assert stride is not None and height is not None + if not self._use_egl: + width, stride, height = self.client.width, self.client.stride, self.client.height + if width is None or stride is None or height is None or not 0 < width <= stride or height <= 0 or stride % 2 or height % 2: + return self.texture_y = rl.load_texture_from_image(rl.Image(None, stride, height, 1, rl.PixelFormat.PIXELFORMAT_UNCOMPRESSED_GRAYSCALE)) self.texture_uv = rl.load_texture_from_image(rl.Image(None, stride // 2, height // 2, 1, rl.PixelFormat.PIXELFORMAT_UNCOMPRESSED_GRAY_ALPHA)) @@ -388,10 +393,9 @@ class CameraView(Widget): self.texture_uv = None # Clean up EGL resources - if COMMA_HARDWARE: - for data in self.egl_images.values(): - destroy_egl_image(data) - self.egl_images = {} + for image in self.egl_images.values(): + destroy_egl_image(image) + self.egl_images.clear() if __name__ == "__main__": diff --git a/openpilot/selfdrive/ui/soundd.py b/openpilot/selfdrive/ui/soundd.py index 4d58d19b5a..a43eb0b899 100644 --- a/openpilot/selfdrive/ui/soundd.py +++ b/openpilot/selfdrive/ui/soundd.py @@ -107,6 +107,8 @@ class Soundd: self.stream_report_at = None self.native_audio = None self.axis_alerts = AxisAlerts() + self._cp_checked = False + self._refresh_car_fingerprint() self.spl_filter_weighted = FirstOrderFilter(0, 2.5, FILTER_DT, initialized=False) @@ -152,11 +154,25 @@ class Soundd: immediate_ramp=self.current_volume if producing_alert in (AudibleAlert.warningSoft, AudibleAlert.warningImmediate) else None) return ret * gain + def _refresh_car_fingerprint(self) -> None: + if getattr(self, "_cp_checked", False) or not hasattr(self, "axis_alerts"): + return + try: + cp_bytes = self.volume_params.get("CarParams") + except Exception: + cp_bytes = None + if cp_bytes: + from opendbc.car.structs import car + with car.CarParams.from_bytes(cp_bytes) as cp: + self.axis_alerts.suppress_lateral = (cp.carFingerprint == "SUBARU_LEGACY_2025") + self._cp_checked = True + def refresh_saved_volumes(self, now: float) -> None: """Read slow Params state from the service loop, never the audio callback.""" if now - self.volume_read_at < 0.25: return self.volume_read_at = now + self._refresh_car_fingerprint() self.saved_volumes = {key: read_volume(self.volume_params, key).value for key, _, _ in VOLUMES} def callback(self, data_out: np.ndarray, frames: int, time, status) -> None: diff --git a/openpilot/starpilot/analytics/settings.py b/openpilot/starpilot/analytics/settings.py index dee9364b6a..ec632b356e 100644 --- a/openpilot/starpilot/analytics/settings.py +++ b/openpilot/starpilot/analytics/settings.py @@ -110,7 +110,7 @@ def _owner_rows(params, CP, profile): parked = params.get("IsOffroad") is True profile = Profile(profile) if profile is not None else Profile.COMPACT if HARDWARE.get_device_type() == "mici" else Profile.LARGE context = AuthorityContext(parked, CP, None) - owner = FeatureSettingsOwner(params, lambda group: _qualified(context, group), + owner = FeatureSettingsOwner(params, lambda group: _qualified(context, group, params=params), vehicle_fingerprint=lambda: str(CP.carFingerprint) if CP is not None else None, vehicle_params=lambda: CP, show_cruise_intervals=True) system_long = bool(CP is not None and CP.openpilotLongitudinalControl) diff --git a/openpilot/starpilot/aol/card_native.py b/openpilot/starpilot/aol/card_native.py new file mode 100644 index 0000000000..41958f867d --- /dev/null +++ b/openpilot/starpilot/aol/card_native.py @@ -0,0 +1,32 @@ +"""Select Card's existing native AOL observation and restriction handlers.""" + +from opendbc.car.ford.aol import (native_observation as ford_native_observation, + temporary_restriction as ford_temporary_restriction) +from opendbc.car.honda.stock_aol import temporary_restriction as honda_temporary_restriction +from opendbc.car.hyundai.canfd_angle_aol import native_observation, temporary_restriction +from opendbc.car.mazda.stock_aol import (native_observation as mazda_native_observation, + temporary_restriction as mazda_temporary_restriction) +from opendbc.car.rivian.stock_aol import (native_observation as rivian_native_observation, + temporary_restriction as rivian_temporary_restriction) +from opendbc.car.tesla.preap.aol import (native_observation as preap_native_observation, + temporary_restriction as preap_temporary_restriction) +from opendbc.car.volkswagen.stock_aol import native_observation as volkswagen_native_observation +from openpilot.starpilot.car.nissan.aol import (native_observation as nissan_native_observation, + temporary_restriction as nissan_temporary_restriction) +from openpilot.starpilot.car.volkswagen.aol import temporary_restriction as volkswagen_temporary_restriction +from openpilot.starpilot.car.volvo.aol import (native_observation as volvo_native_observation, + temporary_restriction as volvo_temporary_restriction) + + +def native_handlers(card, *, volvo_aol: bool, rivian_aol: bool, volkswagen_aol: bool, nissan_aol: bool, preap_aol: bool, + mazda_aol: bool, honda_aol: bool, ford_aol: bool): + # The caller determines permission. Honda's bound handler is only read if Honda wins. + observe = (volvo_native_observation if volvo_aol else rivian_native_observation if rivian_aol else + volkswagen_native_observation if volkswagen_aol else nissan_native_observation if nissan_aol else + preap_native_observation if preap_aol else mazda_native_observation if mazda_aol else card.aol_honda_native_observation if honda_aol else + ford_native_observation if ford_aol else native_observation) + restrict = (volvo_temporary_restriction if volvo_aol else rivian_temporary_restriction if rivian_aol else + volkswagen_temporary_restriction if volkswagen_aol else nissan_temporary_restriction if nissan_aol else + preap_temporary_restriction if preap_aol else mazda_temporary_restriction if mazda_aol else honda_temporary_restriction if honda_aol else + ford_temporary_restriction if ford_aol else temporary_restriction) + return observe, restrict diff --git a/openpilot/starpilot/aol/dm.py b/openpilot/starpilot/aol/dm.py index d442e03733..df99a72ed3 100644 --- a/openpilot/starpilot/aol/dm.py +++ b/openpilot/starpilot/aol/dm.py @@ -7,8 +7,9 @@ def armed_lateral_current(cp, cs, intent, native, *, source_ns, now_ns, axis_ses return bool(policy_for(cp).intent_supported and cs.canValid and not cs.canTimeout and not cs.accFaulted and not cs.doorOpen and not cs.steerFaultTemporary and not cs.steerFaultPermanent and cs.cruiseState.available and - cs.gearShifter in (car.CarState.GearShifter.drive, car.CarState.GearShifter.low, - car.CarState.GearShifter.sport, car.CarState.GearShifter.brake) and + (cs.gearShifter in (car.CarState.GearShifter.drive, car.CarState.GearShifter.low, + car.CarState.GearShifter.sport, car.CarState.GearShifter.brake) or + cp.carFingerprint == 'SUBARU_LEGACY_2025' and cs.gearShifter == car.CarState.GearShifter.manumatic) and intent is not None and intent.settingsQualified and intent.allowedLatch and intent.lateralArmed and intent.producerSessionId and intent.carStateLogMonoTime == source_ns and 0 < source_ns <= intent.observedMonoTime <= now_ns <= intent.validUntilMonoTime and diff --git a/openpilot/starpilot/aol/intent.py b/openpilot/starpilot/aol/intent.py index e8116a7263..b2b00b24aa 100644 --- a/openpilot/starpilot/aol/intent.py +++ b/openpilot/starpilot/aol/intent.py @@ -328,7 +328,7 @@ class AolCardIntent: # owners keep their current event and native contracts. main_toggle = (not independent_buttons or main_managed) and not ( self.independent_cruise_buttons and self.settings.main_wheel_action) - lkas_toggle = not independent_buttons or lkas_managed + lkas_toggle = (not independent_buttons or lkas_managed) and not getattr(self, 'allow_manumatic', False) previously_held = (self._main_held and main_toggle) or (self._lkas_held and lkas_toggle) cancel_pressed = False for event in CS.buttonEvents: diff --git a/openpilot/starpilot/aol/panda_faults.py b/openpilot/starpilot/aol/panda_faults.py index aab07782b6..853e2cd120 100644 --- a/openpilot/starpilot/aol/panda_faults.py +++ b/openpilot/starpilot/aol/panda_faults.py @@ -10,14 +10,16 @@ from opendbc.car.gm.cancel_remap import aol_enabled def _diagnostic_mask(cp): try: if cp.brand == 'honda': - from opendbc.car.honda.stock_aol import qualified, CLASSIC_BOSCH, RADARLESS + from opendbc.car.honda.stock_aol import qualified, CLASSIC_BOSCH, RADARLESS, CANFD_STOCK if (cp.carFingerprint in CLASSIC_BOSCH and cp.openpilotLongitudinalControl) or str(cp.fingerprintSource) == 'fixed': return 0 # New alpha owner and explicit selection cannot borrow the recorded exception. from opendbc.car.honda.values import HondaFlags # Only the reported CAN2 interrupt-rate diagnostic is exempt. Qualification # requires a marked, supported, single-panda Bosch AOL configuration. # Other interrupt rates and mixed faults remain blocking. - return (1 << 3) if ((cp.carFingerprint in CLASSIC_BOSCH or cp.carFingerprint in RADARLESS) and + return (1 << 3) if ((cp.carFingerprint in CLASSIC_BOSCH or cp.carFingerprint in RADARLESS or + cp.carFingerprint in CANFD_STOCK and len(cp.safetyConfigs) == 1 and + str(cp.fingerprintSource) == 'fw') and int(cp.flags) & int(HondaFlags.BOSCH) and qualified(cp, marked_only=True)) else 0 if cp.brand == 'hyundai': from opendbc.car.hyundai.values import CAR, HyundaiFlags diff --git a/openpilot/starpilot/aol/seatbelt.py b/openpilot/starpilot/aol/seatbelt.py index f92696435d..13cf2663aa 100644 --- a/openpilot/starpilot/aol/seatbelt.py +++ b/openpilot/starpilot/aol/seatbelt.py @@ -7,8 +7,10 @@ def seatbelt_lateral_soft_event_allowed(cp, cs, intent, native, event, *, source from openpilot.starpilot.aol.runtime import AXIS_MAX_AGE_NS, SAFETY_MAX_AGE_NS, native_inventory_matches_cp try: gears = car.CarState.GearShifter - paused_gear = bool(gear_pause is True and cs.gearShifter in - (gears.drive, gears.low, gears.sport, gears.brake, gears.neutral, gears.reverse)) + legacy_manumatic = cp.carFingerprint == 'SUBARU_LEGACY_2025' and cs.gearShifter == gears.manumatic + paused_gear = bool(gear_pause is True and (cs.gearShifter in + (gears.drive, gears.low, gears.sport, gears.brake, gears.neutral, gears.reverse) or + legacy_manumatic)) paused_native = bool(paused_gear and native is not None and not native.requestedLateral and not native.lateralAllowed and not native.requestedLongitudinal and not native.longitudinalAllowed) @@ -23,7 +25,7 @@ def seatbelt_lateral_soft_event_allowed(cp, cs, intent, native, event, *, source event.noEntry and not event.immediateDisable and not event.userDisable and cs.seatbeltUnlatched and cs.canValid and not cs.canTimeout and not cs.accFaulted and not cs.doorOpen and (not cs.steerFaultTemporary or paused_eps) and not cs.steerFaultPermanent and cs.cruiseState.available and - (paused_gear or cs.gearShifter in (gears.drive, gears.low, gears.sport, gears.brake)) and + (paused_gear or cs.gearShifter in (gears.drive, gears.low, gears.sport, gears.brake) or legacy_manumatic) and intent is not None and intent.settingsQualified and ((intent.allowedLatch or paused_gear) and intent.lateralArmed or pending_native and not intent.allowedLatch and not intent.lateralArmed) and diff --git a/openpilot/starpilot/aol/source_availability.py b/openpilot/starpilot/aol/source_availability.py index 9d769ed226..a89a265fc5 100644 --- a/openpilot/starpilot/aol/source_availability.py +++ b/openpilot/starpilot/aol/source_availability.py @@ -13,6 +13,12 @@ EventName = log.OnroadEvent.EventName AlertLevel = log.DriverMonitoringState.AlertLevel +def _forward_gear_allowed(cp, gear) -> bool: + gears = car.CarState.GearShifter + return gear in (gears.drive, gears.sport, gears.low, gears.brake) or ( + cp.carFingerprint == 'SUBARU_LEGACY_2025' and gear == gears.manumatic) + + def stock_lateral_role(self, CS, native, intent=None, *, allow_independent_cancel=False, allow_independent_brake=False, allow_independent_gas=False, allow_expired_source=False, now_ns=0): """Current stock USER role while an established independent LAT owner remains.""" @@ -65,7 +71,8 @@ def stock_lateral_role(self, CS, native, intent=None, *, allow_independent_cance getattr(self, 'aol_fault_reason', 'none') == 'availabilityPause' and previous.desired_lateral) and (previous.native_acknowledged or allow_expired_source) and not previous.longitudinal_active and (CS.gearShifter == car.CarState.GearShifter.drive or self.CP.brand == 'gm' and - CS.gearShifter == car.CarState.GearShifter.low) and isfinite(CS.vEgoRaw) and isfinite(CS.vEgo)) + CS.gearShifter == car.CarState.GearShifter.low or + self.CP.carFingerprint == 'SUBARU_LEGACY_2025' and CS.gearShifter == car.CarState.GearShifter.manumatic) and isfinite(CS.vEgoRaw) and isfinite(CS.vEgo)) rules = self.events.event_rules stock_user = stock_lateral_user_event(self.CP) users = [name for name in self.events.names if ET.USER_DISABLE in rules.get(name, {})] @@ -128,8 +135,7 @@ def stock_lateral_fault_proof(self, CS, message, now_ns): if any(not valid or not sample.canValid or sample.canTimeout or sample.steerFaultPermanent or sample.steerFaultTemporary or sample.accFaulted or sample.doorOpen or sample.seatbeltUnlatched or sample.brakePressed or sample.regenBraking or sample.gasPressed or physical_cancel(sample, self.CP) or - sample.gearShifter not in (car.CarState.GearShifter.drive, car.CarState.GearShifter.sport, - car.CarState.GearShifter.low, car.CarState.GearShifter.brake) for sample, valid in samples): + not _forward_gear_allowed(self.CP, sample.gearShifter) for sample, valid in samples): return None return (published, stock_user) @@ -266,8 +272,7 @@ def ordinary_source_availability(self, CS, now_ns, native=None, *, replay: bool, (sample.brakePressed or sample.regenBraking) and not held_pedal or sample.gasPressed and not (toyota_pedal or stock_gas or ford_gas or toyota_gas) or (stock_gas or ford_gas or toyota_gas) and sample.gasPressed != accepted_state.gasPressed or physical_cancel(sample, self.CP) or - sample.gearShifter not in (car.CarState.GearShifter.drive, car.CarState.GearShifter.sport, - car.CarState.GearShifter.low, car.CarState.GearShifter.brake) + not _forward_gear_allowed(self.CP, sample.gearShifter) for sample, valid in samples): return False def valid_metadata(stamp, value): @@ -374,6 +379,5 @@ def fresh_ordinary_lag_continuation(self, CS, intent, native, now_ns): return not any(not valid or not sample.canValid or sample.canTimeout or sample.steerFaultPermanent or sample.steerFaultTemporary or sample.accFaulted or sample.doorOpen or sample.seatbeltUnlatched or sample.brakePressed or sample.regenBraking or sample.gasPressed or physical_cancel(sample, self.CP) or - sample.gearShifter not in (car.CarState.GearShifter.drive, car.CarState.GearShifter.sport, - car.CarState.GearShifter.low, car.CarState.GearShifter.brake) + not _forward_gear_allowed(self.CP, sample.gearShifter) for sample, valid in samples) diff --git a/openpilot/starpilot/aol/temporary_steering.py b/openpilot/starpilot/aol/temporary_steering.py index 39384f264d..abefc1881f 100644 --- a/openpilot/starpilot/aol/temporary_steering.py +++ b/openpilot/starpilot/aol/temporary_steering.py @@ -158,7 +158,8 @@ def temporary_steering_intent_current(self, sm, cp, cs, axis, stamp, now_ns, *, (previous[9] and previous[11] and previous[13] or self.temporary_eps_event_ns and previous[6] == self.temporary_eps_event_ns)) stock_subaru_eps = bool(subaru_temporary_restriction(cp, cs) and subaru_predecessor and - cs.gearShifter == structs.CarState.GearShifter.drive and not cs.doorOpen and + (cs.gearShifter == structs.CarState.GearShifter.drive or + cp.carFingerprint == 'SUBARU_LEGACY_2025' and cs.gearShifter == structs.CarState.GearShifter.manumatic) and not cs.doorOpen and not cs.vehicleSensorsInvalid and not cs.steeringDisengage and not cs.buttonEvents and all(not event.userDisable or event.name == log.OnroadEvent.EventName.pcmDisable and not event.softDisable and not event.immediateDisable for event in events)) diff --git a/openpilot/starpilot/aol/tests/test_card_native_handlers.py b/openpilot/starpilot/aol/tests/test_card_native_handlers.py new file mode 100644 index 0000000000..a28cf13dbf --- /dev/null +++ b/openpilot/starpilot/aol/tests/test_card_native_handlers.py @@ -0,0 +1,43 @@ +from itertools import product + +import pytest + +from opendbc.car.ford import aol as ford +from opendbc.car.honda import stock_aol as honda +from opendbc.car.hyundai import canfd_angle_aol as hyundai +from opendbc.car.mazda import stock_aol as mazda +from opendbc.car.rivian import stock_aol as rivian +from opendbc.car.tesla.preap import aol as preap +from opendbc.car.volkswagen import stock_aol as volkswagen_observer +from openpilot.starpilot.car.nissan import aol as nissan +from openpilot.starpilot.car.volkswagen import aol as volkswagen_restriction +from openpilot.starpilot.car.volvo import aol as volvo +from openpilot.starpilot.aol.card_native import native_handlers + + +class _Card: + honda_lookups = 0 + + def honda_observer(self): + raise AssertionError("Selection must not call the handler") + + @property + def aol_honda_native_observation(self): + self.honda_lookups += 1 + return self.honda_observer + + +@pytest.mark.parametrize('admitted', product((False, True), repeat=8)) +def test_native_handlers_keep_card_priority_and_lazy_honda_binding(admitted): + card = _Card() + observations = (volvo.native_observation, rivian.native_observation, volkswagen_observer.native_observation, nissan.native_observation, + preap.native_observation, mazda.native_observation, card.honda_observer, ford.native_observation, + hyundai.native_observation) + restrictions = (volvo.temporary_restriction, rivian.temporary_restriction, volkswagen_restriction.temporary_restriction, nissan.temporary_restriction, + preap.temporary_restriction, mazda.temporary_restriction, honda.temporary_restriction, ford.temporary_restriction, + hyundai.temporary_restriction) + expected = next((i for i, flag in enumerate(admitted) if flag), len(admitted)) + names = ('volvo_aol', 'rivian_aol', 'volkswagen_aol', 'nissan_aol', 'preap_aol', 'mazda_aol', 'honda_aol', 'ford_aol') + selected = native_handlers(card, **dict(zip(names, admitted, strict=True))) + assert selected == (observations[expected], restrictions[expected]) + assert card.honda_lookups == int(expected == 6) diff --git a/openpilot/starpilot/aol/tests/test_gm_zero_engage_minimum.py b/openpilot/starpilot/aol/tests/test_gm_zero_engage_minimum.py index b8cfb760aa..8e2610423c 100644 --- a/openpilot/starpilot/aol/tests/test_gm_zero_engage_minimum.py +++ b/openpilot/starpilot/aol/tests/test_gm_zero_engage_minimum.py @@ -79,3 +79,29 @@ def test_combined_authority_survives_repeated_standstill_undershoot(): cs.brakePressed = True _, _, control = step(25, observed_state=cs) assert not control.longActive + + +@pytest.mark.parametrize('engaged', [False, True]) +def test_trax_keeps_braking_below_entry_speed_only_when_engaged(engaged): + with OpenpilotPrefix(), ExitStack() as cleanup: + case = fixture.IoniqAvailabilityTests(methodName='runTest') + cleanup.callback(case.doCleanups) + cp = params(CAR.CHEVROLET_TRAX, alpha=True) + assert cp.safetyConfigs[0].safetyParam == 0xC170 + sd, _, step = case._authority_callers(engaged, cp=cp, genuine_events=True) + sd.aol_settings = read_settings(sd.params) + speeds = (1.44, 1.39, 1.36, 1.43, 1.34, .7, .2, 0.) if engaged else (1.34, .7) + for tick, speed in enumerate(speeds): + cs = stopped(speed) + cs.vEgoRaw, cs.standstill, cs.cruiseState.standstill = speed, speed == 0., speed == 0. + cs.buttonEnable = not engaged + axis, host, control = step(tick, observed_state=cs) + assert (EventName.belowEngageSpeed in sd.events.names) == (speed < cp.minEnableSpeed) + assert host.enabled == axis.longitudinalActive == control.longActive == engaged + if engaged: + _, _, control = step(len(speeds), observed_state=stopped(0.), long_allowed=False) + assert not control.longActive + cs = stopped(0.) + cs.brakePressed = True + _, _, control = step(len(speeds) + 1, observed_state=cs) + assert not control.longActive diff --git a/openpilot/starpilot/aol/tests/test_honda_canfd_lifecycle.py b/openpilot/starpilot/aol/tests/test_honda_canfd_lifecycle.py index 712da2474d..83e1d2c554 100644 --- a/openpilot/starpilot/aol/tests/test_honda_canfd_lifecycle.py +++ b/openpilot/starpilot/aol/tests/test_honda_canfd_lifecycle.py @@ -24,3 +24,21 @@ class TestHondaCanfdCaller(CurrentCaller): def test_accord_mvl_eps_reverse_recovery(self): self.run_current_caller(candidate=CAR.HONDA_ACCORD_11G, word=80) + + def test_canfd_crv_can2_diagnostic_from_start(self): + self.run_current_caller(candidate=CAR.HONDA_CRV_6G, word=16, diagnostic_from_start=True, hybrid=True) + + def test_canfd_pilot_can2_diagnostic_from_start(self): + self.run_current_caller(candidate=CAR.HONDA_PILOT_4G, word=16, diagnostic_from_start=True) + + def test_canfd_passport_can2_diagnostic_from_start(self): + self.run_current_caller(candidate=CAR.HONDA_PASSPORT_4G, word=16, diagnostic_from_start=True) + + def test_canfd_mdx_can2_diagnostic_from_start(self): + self.run_current_caller(candidate=CAR.ACURA_MDX_4G_MMR, word=16, diagnostic_from_start=True) + + def test_canfd_tlx_can2_diagnostic_from_start(self): + self.run_current_caller(candidate=CAR.ACURA_TLX_2G_MMR, word=16, diagnostic_from_start=True) + + def test_canfd_alternate_brake_can2_diagnostic_from_start(self): + self.run_current_caller(candidate=CAR.HONDA_CRV_6G, word=17, alternate_brake=True, diagnostic_from_start=True) diff --git a/openpilot/starpilot/aol/tests/test_honda_panda_faults.py b/openpilot/starpilot/aol/tests/test_honda_panda_faults.py index 9c3be454c2..b8d2116cdd 100644 --- a/openpilot/starpilot/aol/tests/test_honda_panda_faults.py +++ b/openpilot/starpilot/aol/tests/test_honda_panda_faults.py @@ -7,7 +7,7 @@ import pytest from opendbc.car import gen_empty_fingerprint, structs from opendbc.car.honda.interface import CarInterface from opendbc.car.honda.stock_aol import qualified -from opendbc.car.honda.values import CAR +from opendbc.car.honda.values import CAR, HondaFlags from openpilot.cereal import log from openpilot.starpilot.aol.panda_faults import blocking_fault_mask, blocking_fault_list from openpilot.starpilot.aol.runtime import current_native, decide_axes @@ -16,7 +16,9 @@ from openpilot.starpilot.aol.tests.test_runtime import car_state PROFILES = ((CAR.HONDA_CIVIC_BOSCH, False), (CAR.HONDA_ACCORD, False), - (CAR.HONDA_CIVIC_2022, False), (CAR.HONDA_CIVIC_2022, True)) + (CAR.HONDA_CIVIC_2022, False), (CAR.HONDA_CIVIC_2022, True), + (CAR.HONDA_CRV_6G, False), (CAR.HONDA_PILOT_4G, False), (CAR.HONDA_PASSPORT_4G, False), + (CAR.ACURA_MDX_4G_MMR, False), (CAR.ACURA_TLX_2G_MMR, False)) def honda(identity=CAR.HONDA_CIVIC_BOSCH, alpha=False): @@ -87,9 +89,10 @@ def test_unknown_or_malformed_faults_are_not_diagnostic(mask): assert blocking_fault_list([31], cp) +@pytest.mark.parametrize('identity', (CAR.HONDA_CIVIC_BOSCH, CAR.HONDA_CRV_6G)) @pytest.mark.parametrize('mutation', ('none', 'rx', 'heartbeat', 'relay', 'expired', 'wrong_session', 'denied')) -def test_real_inventory_exception_does_not_create_authority_or_bypass_vetoes(mutation): - cp = honda() +def test_real_inventory_exception_does_not_create_authority_or_bypass_vetoes(mutation, identity): + cp = honda(identity) state = bound_state(cp) slot = replace(state.pandaInventory[0], faults=1 << 3) if mutation == 'rx': @@ -114,3 +117,31 @@ def test_real_inventory_exception_does_not_create_authority_or_bypass_vetoes(mut immediate_disable=False, dm_lockout=False, pause_brake_mps=0.) assert decision.lateral_active == (mutation == 'none') assert not decision.longitudinal_active + + +@pytest.mark.parametrize('mutation', ('none', 'hybrid', 'alternate_brake', 'two_pandas', 'fixed', + 'can_fingerprint', 'unmarked', 'alpha', 'wrong_word')) +def test_canfd_diagnostic_requires_the_qualified_single_panda_stock_owner(mutation): + cp = honda(CAR.HONDA_CRV_6G) + if mutation == 'hybrid': + cp.flags |= int(HondaFlags.HYBRID) + elif mutation == 'alternate_brake': + cp.flags |= int(HondaFlags.BOSCH_ALT_BRAKE) + cp.safetyConfigs[0].safetyParam = 17 + elif mutation == 'two_pandas': + cp.safetyConfigs = [{'safetyModel': 'noOutput', 'safetyParam': 0}, cp.safetyConfigs[0].to_dict()] + assert qualified(cp, marked_only=True) + elif mutation == 'fixed': + cp.fingerprintSource = 'fixed' + elif mutation == 'can_fingerprint': + cp.fingerprintSource = 'can' + elif mutation == 'unmarked': + cp.alternativeExperience = 0 + elif mutation == 'alpha': + cp.openpilotLongitudinalControl = True + cp.pcmCruise = False + elif mutation == 'wrong_word': + cp.safetyConfigs[0].safetyParam = 8 + blocks = mutation not in ('none', 'hybrid', 'alternate_brake') + assert blocking_fault_mask(1 << 3, cp) == blocks + assert blocking_fault_list([log.PandaState.FaultType.interruptRateCan2], cp) == blocks diff --git a/openpilot/starpilot/aol/tests/test_honda_recovery_lifecycle.py b/openpilot/starpilot/aol/tests/test_honda_recovery_lifecycle.py index 633fd73a10..e06a91ba09 100644 --- a/openpilot/starpilot/aol/tests/test_honda_recovery_lifecycle.py +++ b/openpilot/starpilot/aol/tests/test_honda_recovery_lifecycle.py @@ -104,7 +104,7 @@ class TestHondaCurrentCaller(unittest.TestCase): 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, native_brake_first=False): + eps_repeat=None, eps_brake_end=None, native_brake_first=False, diagnostic_from_start=False): safety = libsafety_py.libsafety with ( OpenpilotPrefix(), @@ -179,6 +179,8 @@ class TestHondaCurrentCaller(unittest.TestCase): self.assertEqual(safety.set_safety_hooks(cp.safetyConfigs[0].safetyModel.raw, word), 0) safety.set_aol_test_heartbeat(False) pandad = PandadOrder(safety, Path(os.environ['HONDA_NATIVE_LIBRARY']), Path(os.environ['HONDA_PANDAD_BRIDGE'])) + if diagnostic_from_start: + pandad.reported_diagnostic_mask = 1 << 3 # Decode the actual controller's on-wire fields; never substitute command flags. tx_dbc = ci.CC.packer.dbc steer_msg = tx_dbc.name_to_msg['STEERING_CONTROL'] @@ -244,6 +246,8 @@ class TestHondaCurrentCaller(unittest.TestCase): panda.pandaStates[0].safetyModel = cp.safetyConfigs[0].safetyModel panda.pandaStates[0].safetyParam, panda.pandaStates[0].alternativeExperience = word, 32 panda.pandaStates[0].ignitionLine = True + if diagnostic_from_start: + panda.pandaStates[0].faults = ['interruptRateCan2'] if tick >= 110 and fault in ('relay', 'diagnostic'): panda.pandaStates[0].faults = ['relayMalfunction' if fault == 'relay' else 'interruptRateCan2'] panda.pandaStates[0].controlsAllowed = bool(safety.get_controls_allowed()) diff --git a/openpilot/starpilot/aol/tests/test_mazda_event_input_reconciliation.py b/openpilot/starpilot/aol/tests/test_mazda_event_input_reconciliation.py index a39874cdec..f1e540a55f 100644 --- a/openpilot/starpilot/aol/tests/test_mazda_event_input_reconciliation.py +++ b/openpilot/starpilot/aol/tests/test_mazda_event_input_reconciliation.py @@ -13,7 +13,7 @@ from openpilot.starpilot.aol.tests.test_carstate_queue import message from openpilot.starpilot.aol.tests.test_input_deadline_continuity import BASE, intent -@pytest.mark.parametrize('identity', (CAR.MAZDA_CX5_2022, CAR.MAZDA_CX9_2021)) +@pytest.mark.parametrize('identity', (CAR.MAZDA_CX5, CAR.MAZDA_CX5_2022, CAR.MAZDA_CX9_2021)) @pytest.mark.parametrize('pulse', ('healthy', 'cancel', 'permanent_eps', 'invalid_can')) def test_mazda_consumes_input_arriving_during_car_event_work(identity, pulse): with OpenpilotPrefix(), ExitStack() as cleanup: diff --git a/openpilot/starpilot/aol/tests/test_mazda_source_deadline.py b/openpilot/starpilot/aol/tests/test_mazda_source_deadline.py index 8b30d4fd6d..a1064a2f54 100644 --- a/openpilot/starpilot/aol/tests/test_mazda_source_deadline.py +++ b/openpilot/starpilot/aol/tests/test_mazda_source_deadline.py @@ -14,7 +14,7 @@ from openpilot.starpilot.aol.tests.test_input_deadline_continuity import BASE, i from openpilot.starpilot.aol.wire import decode_intent, encode_intent -@pytest.mark.parametrize('identity', (CAR.MAZDA_CX5_2022, CAR.MAZDA_CX9_2021)) +@pytest.mark.parametrize('identity', (CAR.MAZDA_CX5, CAR.MAZDA_CX5_2022, CAR.MAZDA_CX9_2021)) @pytest.mark.parametrize('condition', ('healthy', 'deadline', 'native_denied', 'cancel', 'brake', 'main_off', 'eps_fault', 'invalid_can', 'producer', 'pause', 'repeated')) def test_mazda_source_cutoff_preserves_only_original_command_lease(identity, condition): @@ -81,7 +81,7 @@ def test_mazda_source_cutoff_preserves_only_original_command_lease(identity, con assert log.OnroadEvent.EventName.controlsMismatch not in sd.events.names -@pytest.mark.parametrize('identity', (CAR.MAZDA_CX5_2022, CAR.MAZDA_CX9_2021)) +@pytest.mark.parametrize('identity', (CAR.MAZDA_CX5, CAR.MAZDA_CX5_2022, CAR.MAZDA_CX9_2021)) def test_mazda_actual_step_defers_warning_then_consumes_fresh_successor(identity): with OpenpilotPrefix(), ExitStack() as cleanup: case = fixture.IoniqAvailabilityTests(methodName='runTest') diff --git a/openpilot/starpilot/aol/tests/test_mqb_actual_callers.py b/openpilot/starpilot/aol/tests/test_mqb_actual_callers.py index 438e494eb6..179192b2c2 100644 --- a/openpilot/starpilot/aol/tests/test_mqb_actual_callers.py +++ b/openpilot/starpilot/aol/tests/test_mqb_actual_callers.py @@ -476,6 +476,10 @@ def test_mqb_full_engagement_brake_reverse_drive_actual_callers(gearbox, alpha, card.controls_update(state, card.sm['carControl']) for addr, data, bus in sent: assert offset <= bus < offset + 4 + if addr == 0x397 and not pq: + # The HUD runs after the steering frame on this tick. + hca = next(data for address, data, _ in sent if address == 0x126) + assert command.latActive and (int.from_bytes(hca, 'little') >> 16) & 511 accepted = native.safety_tx_hook(make_msg(bus - offset, addr, dat=data)) if cancel_override and alpha and state.gasPressed and addr in (0x122, 0x12E): raw_accel = ((data[4] & 7) << 8 | data[3]) if addr == 0x122 else ((data[7] << 3) | (data[6] >> 5)) diff --git a/openpilot/starpilot/aol/transport_pause.py b/openpilot/starpilot/aol/transport_pause.py index 47f9ba0c18..b1f2418a98 100644 --- a/openpilot/starpilot/aol/transport_pause.py +++ b/openpilot/starpilot/aol/transport_pause.py @@ -2,7 +2,8 @@ from openpilot.cereal import log from openpilot.starpilot.aol.transport_pause_conditions import ( AVAILABILITY_EVENTS as AVAILABILITY_EVENTS, HOST_SOURCE_AVAILABILITY_EVENTS as HOST_SOURCE_AVAILABILITY_EVENTS, - availability_only as availability_only, host_source_availability_only, stock_lateral_off, + availability_only as availability_only, forward_gear_allowed, host_source_availability_only, stock_lateral_off, + subaru_stop_drive_gear, ) from openpilot.starpilot.aol.transport_pause_session import ( AvailabilityPause as AvailabilityPause, TransportPause as TransportPause, cp_identity as cp_identity, @@ -303,7 +304,6 @@ class TransportPauseFeedback: def _ordinary_warning_intent_current(self, sm, cp, cs, axis, stamp, now_ns, *, latched, producer): from openpilot.starpilot.aol.vehicle import policy_for from openpilot.starpilot.nostalgia import physical_cancel - from opendbc.car import structs pending_baseline = self.ordinary_warning_pending_baseline pending = bool(pending_baseline is not None and self.pending_event) @@ -316,8 +316,7 @@ class TransportPauseFeedback: axis.intentIntegrityEpoch != self.availability_epoch or not cs.canValid or cs.canTimeout or cs.steerFaultPermanent or cs.accFaulted or cs.doorOpen or cs.steeringDisengage or - cs.gearShifter not in (structs.CarState.GearShifter.drive, structs.CarState.GearShifter.sport, - structs.CarState.GearShifter.low, structs.CarState.GearShifter.brake) or + not forward_gear_allowed(cp, cs.gearShifter) or not 0 < self.lateral_source_ns <= axis.sourceCarStateMonoTime <= stamp <= now_ns or now_ns - axis.sourceCarStateMonoTime > AXIS_MAX_AGE_NS or str(axis.faultReason) not in ('none', 'availabilityPause') or @@ -450,8 +449,6 @@ class TransportPauseFeedback: from opendbc.car.hyundai.canfd_angle_aol import qualified as angle_qualified from opendbc.car.hyundai.canfd_stock_aol import qualified as stock_canfd_qualified from opendbc.car.hyundai.classic_scc_aol import qualified as stock_classic_qualified - from opendbc.car import structs - gears = structs.CarState.GearShifter # PCM-off is not AOL-off: retain intent for location/EPS recovery; recovering_user = bool((location_fault or eps_recovery) and users) @@ -468,7 +465,7 @@ class TransportPauseFeedback: or cp.brand == 'volkswagen' and volkswagen_qualified(cp, marked_only=True)) and users and not axis.desiredLongitudinal and not axis.longitudinalActive and (cs.cruiseState.available or classic_eps_recovery) and not cs.cruiseState.enabled and - cs.gearShifter in (gears.drive, gears.low, gears.sport, gears.brake) and + forward_gear_allowed(cp, cs.gearShifter) and not cs.doorOpen and (not cs.seatbeltUnlatched or belt_eps_recovery) and not cs.brakePressed and not cs.regenBraking and (not cs.gasPressed or stock_angle or classic_eps_recovery or eps_recovery and stock_canfd_qualified(cp, marked_only=True)) and all((event.name == stock_user or classic_eps_recovery and not cs.cruiseState.available and @@ -1078,7 +1075,6 @@ class TransportPauseFeedback: return True def _angle_stop_intent_current(self, sm, cp, cs, axis, stamp, now_ns, *, latched, producer): - from opendbc.car.structs import car from opendbc.car.hyundai.canfd_angle_aol import qualified, temporary_restriction from opendbc.car.mazda.stock_aol import qualified as mazda_qualified, temporary_restriction as mazda_restriction from opendbc.car.subaru.stock_aol import temporary_restriction as subaru_restriction @@ -1091,7 +1087,7 @@ class TransportPauseFeedback: pending_stop = bool(ccnc_stop and axis.desiredLongitudinal and not axis.longitudinalActive and not axis.lateralActive) subaru_stop = cs.standstill and subaru_restriction(cp, cs) if (not (qualified(cp, marked_only=True) or mazda_qualified(cp, marked_only=True) or subaru_stop or ccnc_stop) or - cs.gearShifter != car.CarState.GearShifter.drive or + not subaru_stop_drive_gear(cp, cs.gearShifter, subaru_stop) or not (temporary_restriction(cp, cs) or mazda_restriction(cp, cs) or subaru_stop) or cs.steerFaultTemporary or cs.steerFaultPermanent or not latched or self.failed or self.paused or self.pending_event or self.retention_started_ns or not (self.lateral_only_baseline or ccnc_stop) or not self.lateral_inventory or not self.lateral_baseline_ns or @@ -1174,7 +1170,6 @@ class TransportPauseFeedback: from openpilot.starpilot.car.subaru.paused_intent import retain_stopped_source_feedback if retain_stopped_source_feedback(self, sm, cp, cs, axis, stamp, now_ns, latched=latched, producer=producer): return True - from opendbc.car import structs previous = self.signature if (not latched or self.failed or self.paused or self.pending_event or self.retention_started_ns or self.source_retention_started_ns or not self.ever_lateral_active or previous is None or @@ -1183,8 +1178,7 @@ class TransportPauseFeedback: not producer or previous[14] != producer or not 0 < previous[8] <= previous[2] <= self.healthy_feedback_ns <= now_ns or now_ns - previous[8] > SAFETY_MAX_AGE_NS or - cs.gearShifter not in (structs.CarState.GearShifter.drive, structs.CarState.GearShifter.low, - structs.CarState.GearShifter.sport, structs.CarState.GearShifter.brake) or + not forward_gear_allowed(cp, cs.gearShifter) or not cs.canValid or cs.canTimeout or cs.steerFaultTemporary or cs.steerFaultPermanent or cs.accFaulted or cs.vehicleSensorsInvalid or cs.doorOpen or cs.seatbeltUnlatched or cs.steeringDisengage or not cs.cruiseState.available or cs.buttonEvents or @@ -1557,8 +1551,7 @@ class TransportPauseFeedback: str(axis.mode) == 'off' and not any(signature[9:13]) and cs.cruiseState.available and not cs.accFaulted and not cs.vehicleSensorsInvalid and not cs.doorOpen and not cs.steeringDisengage and - (cs.gearShifter in (structs.CarState.GearShifter.drive, structs.CarState.GearShifter.sport, - structs.CarState.GearShifter.low, structs.CarState.GearShifter.brake) or + (forward_gear_allowed(cp, cs.gearShifter) or intent_paused and cs.gearShifter in (structs.CarState.GearShifter.reverse, structs.CarState.GearShifter.neutral)) and sm.seen['onroadEvents'] and sm.valid['onroadEvents'] and sm.alive['onroadEvents'] and 0 < int(sm.logMonoTime['onroadEvents']) <= now_ns and diff --git a/openpilot/starpilot/aol/transport_pause_conditions.py b/openpilot/starpilot/aol/transport_pause_conditions.py index b75e7dc766..eec861daf0 100644 --- a/openpilot/starpilot/aol/transport_pause_conditions.py +++ b/openpilot/starpilot/aol/transport_pause_conditions.py @@ -51,3 +51,17 @@ def stock_lateral_off(cp, cs, native, *, allow_independent_cancel=False, allow_i cp.brand == 'hyundai' and (stock_canfd_qualified(cp, marked_only=True) or classic_stock))) and (not physical_cancel(cs, cp) or independent_angle and allow_independent_cancel) and native is not None and native.requestedLateral and native.lateralAllowed and not native.requestedLongitudinal) + + +def forward_gear_allowed(cp, gear) -> bool: + from opendbc.car import structs + gears = structs.CarState.GearShifter + return gear in (gears.drive, gears.sport, gears.low, gears.brake) or ( + cp.carFingerprint == 'SUBARU_LEGACY_2025' and gear == gears.manumatic) + + +def subaru_stop_drive_gear(cp, gear, subaru_stop: bool) -> bool: + from opendbc.car import structs + gears = structs.CarState.GearShifter + return gear == gears.drive or ( + subaru_stop and cp.carFingerprint == 'SUBARU_LEGACY_2025' and gear == gears.manumatic) diff --git a/openpilot/starpilot/audio/axis_alerts.py b/openpilot/starpilot/audio/axis_alerts.py index 1d1fed6824..405db2f8e6 100644 --- a/openpilot/starpilot/audio/axis_alerts.py +++ b/openpilot/starpilot/audio/axis_alerts.py @@ -96,6 +96,7 @@ class AxisAlerts: self.steering_session = None self.steering_warned = False self.steering_recovered_since = 0 + self.suppress_lateral = False def temporary_steering_sound(self, sm, intent, native_sound, now_ns, state_fresh): if intent is None or not state_fresh: @@ -132,9 +133,10 @@ class AxisAlerts: sm.valid['selfdriveState'] and sm.alive['selfdriveState']) lateral_known = intent is not None and (intent.pauseLateral or intent.lateralArmed or state_fresh) axis = current_axis(sm, now_ns=now_ns) if 'aolAxisState' in sm.logMonoTime else None - lateral = self.lateral.update(intent if lateral_known else None, - bool(intent and not intent.pauseLateral and - (intent.lateralArmed or (state_fresh and sm['selfdriveState'].active))), axis, now_ns) + lateral = 0 if self.suppress_lateral else self.lateral.update( + intent if lateral_known else None, + bool(intent and not intent.pauseLateral and + (intent.lateralArmed or (state_fresh and sm['selfdriveState'].active))), axis, now_ns) longitudinal = self.longitudinal.update( intent.producerSessionId if intent is not None and state_fresh else None, intent.sequence if intent is not None else 0, diff --git a/openpilot/starpilot/audio/blindspot_alert.py b/openpilot/starpilot/audio/blindspot_alert.py index 9a37ebcadc..d6d22c0449 100644 --- a/openpilot/starpilot/audio/blindspot_alert.py +++ b/openpilot/starpilot/audio/blindspot_alert.py @@ -1,12 +1,12 @@ """Optional blind-spot presentation; never changes lane-change or control authority.""" -KEYS = ("LoudBlindspotAlert", "LoudBlindspotAlertWhenDisengaged") +KEYS = ("LoudBlindspotAlert", "LoudBlindspotAlertWhenDisengaged", "LoudBlindspotAlertMuteAtStandstill") ALERT_TYPE = "blindSpotAdvisory/warning" EVENT_TYPE = "blindSpotAdvisory" def blindspot_alert(cs, sm, *, loud: bool, without_lateral: bool, lane_change_blocked: bool, now_ns: int, - car_ns: int, car_valid: bool): + car_ns: int, car_valid: bool, mute_at_standstill: bool = False): if not loud and not without_lateral: return None try: @@ -21,8 +21,10 @@ def blindspot_alert(cs, sm, *, loud: bool, without_lateral: bool, lane_change_bl return None matching_signal = (bool(cs.leftBlinker) != bool(cs.rightBlinker) and (cs.leftBlinker and cs.leftBlindspot or cs.rightBlinker and cs.rightBlindspot)) + standstill = bool(getattr(cs, 'standstill', False) or float(getattr(cs, 'vEgo', 1.0)) < 0.5) if not (loud and lane_change_blocked or - without_lateral and not sm['carControl'].latActive and matching_signal): + without_lateral and not sm['carControl'].latActive and matching_signal and + not (mute_at_standstill and standstill)): return None except (AttributeError, KeyError, TypeError, ValueError, OverflowError): return None diff --git a/openpilot/starpilot/audio/tests/test_blindspot_alert.py b/openpilot/starpilot/audio/tests/test_blindspot_alert.py index 81199ae206..5d7fcb15a5 100644 --- a/openpilot/starpilot/audio/tests/test_blindspot_alert.py +++ b/openpilot/starpilot/audio/tests/test_blindspot_alert.py @@ -45,6 +45,19 @@ def test_no_wrong_side_hazards_or_invalid_can(fields): lane_change_blocked=False, now_ns=NOW, car_ns=NOW - 10_000_000, car_valid=True) +def test_standstill_mute_only_applies_without_lateral_when_enabled(): + for fields in ({'standstill': True}, {'vEgo': 0.49}): + assert blindspot_alert(car(**fields), Messages(), loud=False, without_lateral=True, + lane_change_blocked=False, now_ns=NOW, car_ns=NOW - 10_000_000, car_valid=True) + assert not blindspot_alert(car(**fields), Messages(), loud=False, without_lateral=True, + lane_change_blocked=False, now_ns=NOW, car_ns=NOW - 10_000_000, car_valid=True, + mute_at_standstill=True) + # LoudBlindspotAlert during an active/blocked lane change is never muted at standstill. + assert blindspot_alert(car(**fields), Messages(active=True), loud=True, without_lateral=False, + lane_change_blocked=True, now_ns=NOW, car_ns=NOW - 10_000_000, car_valid=True, + mute_at_standstill=True) + + def test_right_side_and_stale_or_offroad_inputs(): cs = car(leftBlinker=False, leftBlindspot=False, rightBlinker=True, rightBlindspot=True) sm = Messages() @@ -84,13 +97,23 @@ def test_switch_defaults_persistence_and_exact_authority(tmp_path): params = Params(str(tmp_path)) allowed = True owner = SoundsOwner(params, lambda: allowed) - for key in KEYS: + mute_row = next(row for row in owner.snapshot().rows if row.key == KEYS[2]) + assert not mute_row.available + assert not owner.apply(FeatureSettingsRequest(KEYS[2], mute_row.source, 'On')) + for key in KEYS[:2]: row = next(row for row in owner.snapshot().rows if row.key == key) assert row.value == 'Off' and row.default_value == 'Off' request = FeatureSettingsRequest(key, row.source, 'On') assert owner.apply(request) assert params.get_bool(key) assert not owner.apply(request) + if key == KEYS[1]: + mute_row = next(row for row in owner.snapshot().rows if row.key == KEYS[2]) + assert mute_row.available + assert owner.apply(FeatureSettingsRequest(KEYS[2], mute_row.source, 'On')) + assert params.get_bool(KEYS[2]) + assert owner.apply(FeatureSettingsRequest(KEYS[2], b'1', 'Off')) + assert not params.get_bool(KEYS[2]) allowed = False assert not owner.apply(FeatureSettingsRequest(key, b'1', 'Off')) allowed = True @@ -106,7 +129,10 @@ def test_galaxy_sounds_switches_save_and_reset_with_session_checks(tmp_path): context = Context() gateway = SettingsGateway(params, context) - for key, label in zip(KEYS, ('Loud Blindspot Alert', 'Blindspot Alert While Lateral Is Off'), strict=True): + for key, label in zip(KEYS, ('Loud Blindspot Alert', 'Blindspot Alert While Lateral Is Off', + 'Mute Blindspot Alert at Standstill'), strict=True): + if key == KEYS[2]: + params.put_bool(KEYS[1], True, block=True) page = gateway.page('sounds', 'session', b'generation') index, row = next((i, row) for i, row in enumerate(page['rows']) if row['label'] == label) assert row['choices'] == ['Off', 'On'] and row['defaultValue'] == 'Off' @@ -121,6 +147,7 @@ def test_galaxy_sounds_switches_save_and_reset_with_session_checks(tmp_path): reset = gateway.preview(page['view'], index, 0, 'session', b'generation', reset_default=True) assert gateway.confirm(reset['intent'], 'session', b'generation') assert not params.get_bool(key) + params.put_bool(KEYS[1], False, block=True) @pytest.mark.parametrize('car_ns,valid', [(0, True), (NOW + 1, True), (NOW - 200_000_001, True), (NOW, False)]) @@ -178,7 +205,7 @@ def test_actual_selfdrived_socket_live_setting_publication_and_sound(tmp_path): stop = threading.Event() with patch('openpilot.selfdrive.selfdrived.selfdrived.time.sleep', side_effect=lambda _: stop.set()): sd.params_thread(stop) - assert sd.blindspot_alert_settings == (False, True) + assert sd.blindspot_alert_settings == (False, True, False) state, stamp = sample(20) assert sd.AM.current_alert.alert_type == ALERT_TYPE, 'BLINDSPOT_CALLER_SILENT' output = {} @@ -200,9 +227,17 @@ def test_actual_selfdrived_socket_live_setting_publication_and_sound(tmp_path): (23, {'age': -1}), (24, {'active': True})]: sample(tick, **fields) assert ALERT_TYPE not in sd.AM.alerts - params.put_bool(KEYS[1], False, block=True) + params.put_bool(KEYS[2], True, block=True) stop.clear() with patch('openpilot.selfdrive.selfdrived.selfdrived.time.sleep', side_effect=lambda _: stop.set()): sd.params_thread(stop) + assert sd.blindspot_alert_settings == (False, True, True) sample(25) + assert ALERT_TYPE in sd.AM.alerts # vEgo == 8.0 is above standstill mute threshold + params.put_bool(KEYS[1], False, block=True) + params.put_bool(KEYS[2], False, block=True) + stop.clear() + with patch('openpilot.selfdrive.selfdrived.selfdrived.time.sleep', side_effect=lambda _: stop.set()): + sd.params_thread(stop) + sample(26) assert ALERT_TYPE not in sd.AM.alerts diff --git a/openpilot/starpilot/car/events.py b/openpilot/starpilot/car/events.py index a9ce19f1ea..8890b31bc0 100644 --- a/openpilot/starpilot/car/events.py +++ b/openpilot/starpilot/car/events.py @@ -12,4 +12,8 @@ def unsupported_gear(cp, gear) -> bool: if cp.brand == "gm": from openpilot.starpilot.car.gm.events import unsupported_gear as gm_unsupported return gm_unsupported(cp, gear) + if cp.brand == "subaru": + from opendbc.car.structs import car + from opendbc.car.subaru.values import CAR + return cp.carFingerprint != CAR.SUBARU_LEGACY_2025 and gear == car.CarState.GearShifter.manumatic return False diff --git a/openpilot/starpilot/car/hyundai/redneck_cruise.py b/openpilot/starpilot/car/hyundai/redneck_cruise.py index 7e79007447..cda6d908c1 100644 --- a/openpilot/starpilot/car/hyundai/redneck_cruise.py +++ b/openpilot/starpilot/car/hyundai/redneck_cruise.py @@ -4,7 +4,7 @@ from opendbc.car.structs import car from opendbc.car import apply_hysteresis from openpilot.common.constants import CV from openpilot.common.realtime import DT_CTRL -from openpilot.selfdrive.car.cruise import V_CRUISE_UNSET +from openpilot.selfdrive.car.cruise import V_CRUISE_MIN, V_CRUISE_UNSET, slc_target_kph def ready(cs, cc): return (cc.enabled and cs.canValid and not cs.canTimeout and cs.gearShifter == car.CarState.GearShifter.drive and @@ -184,6 +184,7 @@ class RedneckCruise: self.is_ready = False self.is_ready_prev = False self.cruise_button_timers = dict(CRUISE_BUTTON_TIMERS) + self.set_match_ns = 0 @staticmethod def _send_button_for_state(state: str) -> int: @@ -284,6 +285,41 @@ class RedneckCruise: return send_button, self.v_target + def match_limit_on_set(self, card, cs, now_ns: int) -> None: + cc = card.sm['carControl'] + if (not card.slc_match_on_engage or not card.slc_control_enabled or not cs.canValid or cs.canTimeout or + not cs.cruiseState.available or cs.gearShifter != car.CarState.GearShifter.drive or + cs.standstill or cs.brakePressed or cs.gasPressed or cs.accFaulted): + self.set_match_ns = 0 + return + if not self.set_match_ns and not cs.buttonEvents: + return + pressed = {button.type.raw for button in cs.buttonEvents if button.pressed} + if pressed.intersection((ButtonType.accelCruise, ButtonType.resumeCruise, ButtonType.cancel, ButtonType.mainCruise)): + self.set_match_ns = 0 + return + if (not cc.enabled and not card.CS_prev.cruiseState.enabled and + pressed.intersection((ButtonType.decelCruise, ButtonType.setCruise))): + self.set_match_ns = now_ns + if not 0 < self.set_match_ns <= now_ns <= self.set_match_ns + 500_000_000: + self.set_match_ns = 0 + return + + helper = card.v_cruise_helper + if (not cc.enabled or not cs.cruiseState.enabled or not current(card.sm, 'carControl', now_ns) or + not V_CRUISE_MIN <= helper.v_cruise_kph < V_CRUISE_UNSET): + return + self.set_match_ns = 0 + from openpilot.starpilot.speed_limits.physical_actions import engagement_state + evidence = getattr(card.CI.CS, 'dashboard_limit', None) + state = engagement_state(card.sm, evidence.observation if evidence is not None else None, card.slc_producer_session, + now_ns, after_ns=card.slc_source_floor_ns) + if state is not None: + target = slc_target_kph(state.presentationAdjustedLimit, card.is_metric) + minimum = get_minimum_set_speed(card.is_metric) * (1. if card.is_metric else CV.MPH_TO_KPH) + if minimum <= target < helper.v_cruise_kph: + helper.apply_slc_target(state.presentationAdjustedLimit, card.is_metric) + def update(self, card, cs, cc, now_ns): update(card, cs, cc, now_ns) @@ -332,7 +368,7 @@ def update(card, cs, cc, now_ns): lead_distance = lead_rel_speed = 0.0 if current(card.sm, "radarState", now_ns): lead = card.sm["radarState"].leadOne - if lead.status and math.isfinite(lead.dRel) and math.isfinite(lead.vRel): + if lead.present and math.isfinite(lead.dRel) and math.isfinite(lead.vRel): lead_distance, lead_rel_speed = float(lead.dRel), float(lead.vRel) speeds = [float(speed) for speed in plan.speeds if math.isfinite(speed)] target = select_redneck_target_speed(ceiling_kph, cluster, 0.0, speeds, len(speeds) if plan.hasLead else 10, diff --git a/openpilot/starpilot/car/hyundai/software_cruise_settings.py b/openpilot/starpilot/car/hyundai/software_cruise_settings.py index 7900dc95b9..511fce7f76 100644 --- a/openpilot/starpilot/car/hyundai/software_cruise_settings.py +++ b/openpilot/starpilot/car/hyundai/software_cruise_settings.py @@ -2,13 +2,18 @@ from dataclasses import replace -from opendbc.car.hyundai.software_cruise import eligible +from opendbc.car.hyundai.software_cruise import eligible, selected from openpilot.starpilot.saved_document import commit_exact +from openpilot.starpilot.saved_source import read_saved from openpilot.starpilot.vehicle_selection import read_selection KEY = 'RedneckCruise' +def slc_configurable(cp, params): + return eligible(cp) and (selected(cp) or (params is not None and read_saved(params, KEY, 8) == (b'1', True))) + + def capability(owner): cp = owner.vehicle_params() selection = read_selection(owner.params) diff --git a/openpilot/starpilot/car/hyundai/tests/test_redneck_cruise.py b/openpilot/starpilot/car/hyundai/tests/test_redneck_cruise.py index 1d3f65f3d0..0291a04ff9 100644 --- a/openpilot/starpilot/car/hyundai/tests/test_redneck_cruise.py +++ b/openpilot/starpilot/car/hyundai/tests/test_redneck_cruise.py @@ -1,3 +1,5 @@ +import pytest + from opendbc.car.hyundai import software_cruise from opendbc.car.hyundai.non_scc_aol import aol_word, NON_SCC_IDS from opendbc.car.hyundai.interface import CarInterface @@ -130,7 +132,8 @@ def test_vehicle_setting_saves_only_with_confirmed_parked_authority(tmp_path): lateral_context=True, metric=True).rows) -def test_fresh_limit_drives_only_set_button_and_renewal_requires_all_inputs(): +@pytest.mark.parametrize('lead_present', [False, True]) +def test_fresh_limit_drives_only_set_button_and_renewal_requires_all_inputs(lead_present): from types import SimpleNamespace from opendbc.car.structs import CarControl, CarState from openpilot.cereal import messaging @@ -159,7 +162,13 @@ def test_fresh_limit_drives_only_set_button_and_renewal_requires_all_inputs(): assert output.message.slcState.hasCeiling plan = messaging.new_message('longitudinalPlan').longitudinalPlan plan.speeds = [22.] * 17 + plan.hasLead = lead_present + radar = messaging.new_message('radarState') + radar.radarState.leadOne.present = lead_present + radar.radarState.leadOne.dRel = 35. + radar.radarState.leadOne.vRel = -2. services = {'carControl': command, 'selfdriveState': sm['selfdriveState'], 'longitudinalPlan': plan, + 'radarState': radar.as_reader().radarState, 'pandaStates': [SimpleNamespace(controlsAllowed=True, faults=[])], 'slcState': output.message.slcState} link = ReplaySM(services, 2_000_000_000) link.seen = dict(link.valid) diff --git a/openpilot/starpilot/car/subaru/aol.py b/openpilot/starpilot/car/subaru/aol.py index 157a6ae535..2c344ff599 100644 --- a/openpilot/starpilot/car/subaru/aol.py +++ b/openpilot/starpilot/car/subaru/aol.py @@ -6,18 +6,26 @@ from openpilot.starpilot.aol.intent import AolCardIntent from openpilot.starpilot.aol.policy import AolVehiclePolicy +def _drive_gear(cp, state): + if cp is not None and cp.carFingerprint == CAR.SUBARU_LEGACY_2025: + return state.gearShifter in (structs.CarState.GearShifter.drive, structs.CarState.GearShifter.manumatic) + return state.gearShifter == structs.CarState.GearShifter.drive + + class SubaruStockCardIntent(AolCardIntent): observe_stock_engagement = True - def __init__(self, settings, *, main_arm=False): + def __init__(self, settings, *, main_arm=False, allow_manumatic=False): super().__init__(settings, explicit_latch=True, lkas_button_supported=False) self.main_arm = main_arm + self.allow_manumatic = allow_manumatic self._previous_main = None self._main_observed_ns = 0 self._main_event_ns = 0 self._pending_main_ns = 0 self._pending_main_after_ns = 0 self._pending_main_restriction_ns = 0 + self._deferred_park_main = False self.main_arm_ns = 0 def observe_startup_readiness(self, sm, CS, *, now_ns, **kwargs): @@ -31,12 +39,23 @@ class SubaruStockCardIntent(AolCardIntent): now_ns = kwargs.get('now_ns', 0) main = bool(CS.cruiseState.available) fresh_main = self._previous_main is False and main - physical_safe = (self.settings.enabled and CS.canValid and not CS.canTimeout and - not self._calibration_inhibit and not self._calibration_rearm_required and - not CS.steerFaultPermanent and not CS.accFaulted and - not any(e.type == structs.CarState.ButtonEvent.Type.cancel and e.pressed for e in CS.buttonEvents) and - CS.gearShifter == structs.CarState.GearShifter.drive) - if self.main_arm and fresh_main and physical_safe: + allowed_gears = ( + (structs.CarState.GearShifter.drive, structs.CarState.GearShifter.manumatic) + if self.allow_manumatic else + (structs.CarState.GearShifter.drive,) + ) + base_safe = (self.settings.enabled and CS.canValid and not CS.canTimeout and + not self._calibration_inhibit and not self._calibration_rearm_required and + not CS.steerFaultPermanent and not CS.accFaulted and + not any(e.type == structs.CarState.ButtonEvent.Type.cancel and e.pressed for e in CS.buttonEvents)) + physical_safe = base_safe and CS.gearShifter in allowed_gears + if not main or not base_safe: + self._deferred_park_main = False + elif self.main_arm and self.allow_manumatic and not physical_safe: + if fresh_main or (self._previous_main is None and CS.gearShifter == structs.CarState.GearShifter.park): + self._deferred_park_main = True + if self.main_arm and (fresh_main or self._deferred_park_main) and physical_safe: + self._deferred_park_main = False self._pending_main_ns = now_ns self._pending_main_after_ns = self._main_observed_ns self._pending_main_restriction_ns = 0 @@ -63,6 +82,7 @@ class SubaruStockCardIntent(AolCardIntent): self._pending_main_ns = 0 if not main: self.main_arm_ns = 0 + self._deferred_park_main = False self._record_latch_clear('subaru_main_off') self.allowed_latch = False self._withdraw_full_engagement() @@ -102,14 +122,16 @@ def ordinary_axis_request_allowed(cp, state): def create_intent(cp, settings): main_arm = (cp.carFingerprint in (CAR.SUBARU_CROSSTREK_2025, CAR.SUBARU_IMPREZA_2025) or - (cp.carFingerprint in (CAR.SUBARU_IMPREZA_2020, CAR.SUBARU_OUTBACK_2023) and qualified(cp))) - return SubaruStockCardIntent(settings, main_arm=main_arm) + (cp.carFingerprint in (CAR.SUBARU_IMPREZA_2020, CAR.SUBARU_LEGACY_2025, CAR.SUBARU_OUTBACK_2023) and qualified(cp))) + return SubaruStockCardIntent(settings, main_arm=main_arm, + allow_manumatic=(cp.carFingerprint == CAR.SUBARU_LEGACY_2025)) -def sng_standstill_lateral_inhibit(cp, state): - # All stock Subaru native profiles require movement. Withdraw the request before its expected denial, - # preserving ordinary stock ACC without granting either active axis. - return bool(qualified(cp, marked_only=True) and state.standstill) +def sng_standstill_lateral_inhibit(cp, state, *, initial_wait: bool = False): + # All stock Subaru native profiles require movement (and Legacy 2025 waits for !brake_pressed before initial grant). + # Withdraw the request before its expected denial, preserving ordinary stock ACC without granting either axis. + legacy_brake_wait = bool(cp.carFingerprint == CAR.SUBARU_LEGACY_2025 and initial_wait and state.brakePressed) + return bool(qualified(cp, marked_only=True) and (state.standstill or legacy_brake_wait)) def temporary_eps_brake_recovery(cp, state, *, previous_brake=False): @@ -117,7 +139,7 @@ def temporary_eps_brake_recovery(cp, state, *, previous_brake=False): not state.steerFaultPermanent and not state.accFaulted and not state.doorOpen and not state.vehicleSensorsInvalid and not state.steeringDisengage and not state.buttonEvents and state.cruiseState.available and not state.cruiseState.enabled and - state.gearShifter == structs.CarState.GearShifter.drive and + _drive_gear(cp, state) and (state.brakePressed or previous_brake) and not state.regenBraking and not state.gasPressed) @@ -127,7 +149,7 @@ def retain_braked_main_intent(feedback, sm, cp, state, axis, now_ns, *, arm_ns, from openpilot.starpilot.aol.transport_pause import _configured_transport_native pending = feedback.subaru_braked_main epoch = int(axis.intentIntegrityEpoch) - if (cp.carFingerprint not in (CAR.SUBARU_IMPREZA_2020, CAR.SUBARU_IMPREZA_2025) or not qualified(cp, marked_only=True) or + if (cp.carFingerprint not in (CAR.SUBARU_IMPREZA_2020, CAR.SUBARU_IMPREZA_2025, CAR.SUBARU_LEGACY_2025) or not qualified(cp, marked_only=True) or feedback.failed or feedback.paused or feedback.pending_event or arm_ns <= feedback.subaru_lateral_grant_ns or not producer or axis.intentProducerSessionId != producer or not 0 < arm_ns <= axis.sourceCarStateMonoTime <= now_ns or @@ -137,7 +159,7 @@ def retain_braked_main_intent(feedback, sm, cp, state, axis, now_ns, *, arm_ns, state.accFaulted or state.vehicleSensorsInvalid or state.doorOpen or state.seatbeltUnlatched or state.steeringDisengage or state.buttonEvents or state.gasPressed or state.regenBraking or not state.cruiseState.available or state.cruiseState.enabled or - state.gearShifter != structs.CarState.GearShifter.drive): + not _drive_gear(cp, state)): return False if pending is None: if (not state.brakePressed or now_ns - arm_ns > SAFETY_MAX_AGE_NS or @@ -170,7 +192,7 @@ def retain_stopped_intent(feedback, sm, cp, state, axis, now_ns, *, latched, pro from openpilot.starpilot.aol.transport_pause import _healthy_transport_native, cp_identity previous = feedback.signature - if (cp.carFingerprint != CAR.SUBARU_IMPREZA_2020 or not qualified(cp, marked_only=True) or + if (cp.carFingerprint not in (CAR.SUBARU_IMPREZA_2020, CAR.SUBARU_LEGACY_2025) or not qualified(cp, marked_only=True) or not latched or not feedback.ever_lateral_active or feedback.failed or feedback.paused or feedback.pending_event or feedback.retention_started_ns or feedback.source_retention_started_ns or not feedback.session or cp_identity(cp) != feedback.cp or previous is None or signature != previous or @@ -182,7 +204,7 @@ def retain_stopped_intent(feedback, sm, cp, state, axis, now_ns, *, latched, pro previous[2] - previous[8] > AXIS_MAX_AGE_NS or previous[4] != previous[2] + AXIS_MAX_AGE_NS or not previous[4] < now_ns or now_ns - previous[8] > SAFETY_MAX_AGE_NS or not state.canValid or state.canTimeout or not state.standstill or not state.brakePressed or - state.gearShifter != structs.CarState.GearShifter.drive or not state.cruiseState.available or + not _drive_gear(cp, state) or not state.cruiseState.available or state.cruiseState.enabled or state.gasPressed or state.regenBraking or state.buttonEvents or state.steerFaultTemporary or state.steerFaultPermanent or state.accFaulted or state.doorOpen or state.seatbeltUnlatched or state.vehicleSensorsInvalid or state.steeringDisengage): @@ -201,3 +223,17 @@ def retain_stopped_intent(feedback, sm, cp, state, axis, now_ns, *, latched, pro not (native.requestedLateral or native.lateralAllowed or native.requestedLongitudinal or native.longitudinalAllowed) and native.observedMonoTime >= feedback.healthy_native_ns and feedback.healthy_inventory == (native.pandaSerial, tuple(slot.hardwareSerial for slot in native.pandaInventory))) + + +def sync_legacy_card_lateral(card, cs, cc) -> None: + if (card.CP.carFingerprint == CAR.SUBARU_LEGACY_2025 and cs.cruiseState.available and + getattr(card.CI.CS, "_lkas_mode_settle_frames", 0) == 0): + card.CI.CS.lateral_off = not bool(cc.hudControl.lanesVisible) + + +def sync_legacy_card_aol(card) -> None: + cs = getattr(getattr(card, "CI", None), "CS", None) + if cs is not None and getattr(getattr(cs, "CP", None), "carFingerprint", None) == CAR.SUBARU_LEGACY_2025: + intent = getattr(card, "aol_card_intent", None) + settings = getattr(intent, "settings", None) + cs.aol_enabled = bool(settings.enabled) if settings is not None else bool(card.params.get_bool("AlwaysOnLateral")) diff --git a/openpilot/starpilot/car/subaru/paused_intent.py b/openpilot/starpilot/car/subaru/paused_intent.py index 2cbe4ca577..bd4297d50c 100644 --- a/openpilot/starpilot/car/subaru/paused_intent.py +++ b/openpilot/starpilot/car/subaru/paused_intent.py @@ -155,7 +155,9 @@ def retain_paused_restriction(feedback, sm, cp, state, axis, stamp, now_ns, *, l not 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.gasPressed or state.regenBraking or - state.gearShifter != structs.CarState.GearShifter.drive or not state.cruiseState.available or state.cruiseState.enabled or + (state.gearShifter != structs.CarState.GearShifter.drive and + not (cp.carFingerprint == CAR.SUBARU_LEGACY_2025 and state.gearShifter == structs.CarState.GearShifter.manumatic)) or + not state.cruiseState.available or state.cruiseState.enabled or not 0 < feedback.healthy_feedback_ns <= now_ns or not feedback.healthy_inventory): return False event_ns = int(sm.logMonoTime['onroadEvents']) @@ -220,7 +222,9 @@ def retain_pending_restriction_recovery(feedback, sm, cp, state, axis, stamp, no 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): + (state.gearShifter != structs.CarState.GearShifter.drive and + not (cp.carFingerprint == CAR.SUBARU_LEGACY_2025 and state.gearShifter == structs.CarState.GearShifter.manumatic)) 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) diff --git a/openpilot/starpilot/car/subaru/tests/test_avh.py b/openpilot/starpilot/car/subaru/tests/test_avh.py index 8bc5ddcebc..cfed185897 100644 --- a/openpilot/starpilot/car/subaru/tests/test_avh.py +++ b/openpilot/starpilot/car/subaru/tests/test_avh.py @@ -70,6 +70,10 @@ def test_release_saved_choice_retained_without_avh_marker(tmp_path): def test_original_source_clock_and_conflicting_duplicate(): from opendbc.car.subaru.avh import AvhSources, INPUTS, checksum from opendbc.car.subaru.tests.test_avh import sample + batch_source = AvhSources() + batch_frames = [(a, sample(a, counter), 1) for counter in (1, 2) for a in INPUTS] + batch_source.observe([(10_020_000_000, batch_frames)], boot_ns=10_020_000_000, mono_ns=1_020_000_000) + assert not batch_source.blocked and batch_source.fresh(1.02) for target in INPUTS: source = AvhSources() for counter in (1, 2): diff --git a/openpilot/starpilot/car/subaru/tests/test_avh_callers.py b/openpilot/starpilot/car/subaru/tests/test_avh_callers.py index 58df703e4f..694c6bbaf3 100644 --- a/openpilot/starpilot/car/subaru/tests/test_avh_callers.py +++ b/openpilot/starpilot/car/subaru/tests/test_avh_callers.py @@ -190,8 +190,18 @@ def test_actual_startup_factory_card_controls_native(enabled, combined, aol, sub if any(address == 0x322 for address, _, _ in outgoing): dash = dash_decoder.vl['ES_LKAS_State'] expected = ci.CC.angle_was_active if steering_name == 'ES_LKAS_ANGLE' else card.sm['carControl'].latActive - assert bool(dash['LKAS_ACTIVE']) == expected, (candidate, tick, expected, dash) - assert dash['LKAS_Dash_State'] == (2 if expected else 0), (candidate, tick, expected, dash) + if candidate == 'SUBARU_LEGACY_2025': + assert bool(dash['LKAS_ACTIVE']), (candidate, tick, expected, dash) + if not cs.cruiseState.available or cs.steerFaultTemporary or cs.steerFaultPermanent: + assert not ci.CC.aol_dash_green_last, (candidate, tick, dash) + if expected: + assert ci.CC.aol_dash_green_last, (candidate, tick, dash) + ready_wheel = cs.cruiseState.available and bool(getattr(ci.CS, 'aol_enabled', True)) + expected_dash = 2 if ci.CC.aol_dash_green_last else (1 if ready_wheel else 0) + assert dash['LKAS_Dash_State'] == expected_dash, (candidate, tick, expected, expected_dash, dash) + else: + assert bool(dash['LKAS_ACTIVE']) == expected, (candidate, tick, expected, dash) + assert dash['LKAS_Dash_State'] == (2 if expected else 0), (candidate, tick, expected, dash) assert all(accepted == (tick >= configure_delay) for address, _, _, accepted in tx if address == 0x322) dash_emissions += 1 for address, data_hex, bus, accepted in tx: @@ -236,9 +246,9 @@ def test_actual_startup_factory_card_controls_native(enabled, combined, aol, sub assert bool(stop_start_emissions) == combined assert dash_emissions >= 20 assert bool(startup_emissions) == enabled - assert len(startup_emissions) == (2 if enabled else 0) + assert len(startup_emissions) == (4 if enabled else 0) if startup_emissions: - assert 45_000_000 <= startup_emissions[-1][0] - startup_emissions[0][0] <= 80_000_000 + assert all(45_000_000 <= b[0] - a[0] <= 80_000_000 for a, b in zip(startup_emissions, startup_emissions[1:], strict=False)) earliest = 10_000_000_000 + configure_delay * 10_000_000 assert all(earliest <= stamp - base < earliest + 1_500_000_000 for stamp, _ in startup_emissions) finally: diff --git a/openpilot/starpilot/car/subaru/tests/test_main_aol.py b/openpilot/starpilot/car/subaru/tests/test_main_aol.py index 301246220a..e6cefe691e 100644 --- a/openpilot/starpilot/car/subaru/tests/test_main_aol.py +++ b/openpilot/starpilot/car/subaru/tests/test_main_aol.py @@ -116,7 +116,206 @@ def test_outback_main_intent_uses_only_existing_exact_native_profiles(): assert qualified(cp, marked_only=True) cp.safetyConfigs[0].safetyParam |= 2 assert not qualified(cp) and not create_intent(cp, owner().settings).main_arm - for candidate in (CAR.SUBARU_OUTBACK, CAR.SUBARU_LEGACY_2025): - cp = CarInterface.get_non_essential_params(candidate) - cp.alternativeExperience = 32 - assert qualified(cp) and not create_intent(cp, owner().settings).main_arm + legacy = CarInterface.get_non_essential_params(CAR.SUBARU_LEGACY_2025) + legacy.alternativeExperience = 32 + legacy_intent = create_intent(legacy, owner().settings) + assert qualified(legacy) and legacy_intent.main_arm and legacy_intent.allow_manumatic + legacy_cs = state() + legacy_cs.gearShifter = structs.CarState.GearShifter.manumatic + observe(legacy_intent, legacy_cs, 1_000_000, 1_000_000, False) + legacy_cs.cruiseState.available = True + observe(legacy_intent, legacy_cs, 10_000_000, 1_000_000, False) + observe(legacy_intent, legacy_cs, 20_000_000, 10_000_000, False) + assert legacy_intent.allowed_latch + + # Pressing MAIN while still in Park, passing through Reverse, then shifting to Drive arms AOL. + park_intent = create_intent(legacy, owner().settings) + park_cs = state() + park_cs.gearShifter = structs.CarState.GearShifter.park + observe(park_intent, park_cs, 1_000_000, 1_000_000, False) + park_cs.cruiseState.available = True + observe(park_intent, park_cs, 10_000_000, 1_000_000, False) + assert not park_intent.allowed_latch + park_cs.gearShifter = structs.CarState.GearShifter.reverse + observe(park_intent, park_cs, 20_000_000, 10_000_000, False) + assert not park_intent.allowed_latch + park_cs.gearShifter = structs.CarState.GearShifter.drive + observe(park_intent, park_cs, 30_000_000, 20_000_000, False) + observe(park_intent, park_cs, 40_000_000, 30_000_000, False) + assert park_intent.allowed_latch + + outback = CarInterface.get_non_essential_params(CAR.SUBARU_OUTBACK) + outback.alternativeExperience = 32 + assert qualified(outback) and not create_intent(outback, owner().settings).main_arm + + +def test_legacy_2025_manumatic_and_aol_intent(): + from opendbc.car.subaru.interface import CarInterface + from opendbc.car.subaru.stock_aol import qualified + from opendbc.car.subaru.values import CAR + from openpilot.starpilot.aol.intent import independent_axis_requested + from openpilot.starpilot.car.events import unsupported_gear + from openpilot.starpilot.car.subaru.aol import create_intent + + Gear = structs.CarState.GearShifter + ButtonEvent = structs.CarState.ButtonEvent + ButtonType = ButtonEvent.Type + + assert Gear.manumatic in CarInterface.DRIVABLE_GEARS + + legacy = CarInterface.get_non_essential_params(CAR.SUBARU_LEGACY_2025) + legacy.alternativeExperience = 32 + outback_2023 = CarInterface.get_non_essential_params(CAR.SUBARU_OUTBACK_2023) + ascent_2023 = CarInterface.get_non_essential_params(CAR.SUBARU_ASCENT_2023) + assert not unsupported_gear(legacy, Gear.manumatic) + assert unsupported_gear(outback_2023, Gear.manumatic) + assert unsupported_gear(ascent_2023, Gear.manumatic) + + aol_settings = AolSettings(True, 0., 0, 0, (0, 0, 0), (0, 0, 0)) + disabled_settings = AolSettings(False, 0., 0, 0, (0, 0, 0), (0, 0, 0)) + assert independent_axis_requested(aol_settings) + assert not independent_axis_requested(disabled_settings) + + legacy_intent = create_intent(legacy, aol_settings) + assert qualified(legacy) and legacy_intent.main_arm and legacy_intent.allow_manumatic + + legacy_cs = state() + legacy_cs.gearShifter = Gear.drive + observe(legacy_intent, legacy_cs, 1_000_000, 1_000_000, False) + legacy_cs.cruiseState.available = True + observe(legacy_intent, legacy_cs, 10_000_000, 1_000_000, False) + observe(legacy_intent, legacy_cs, 20_000_000, 10_000_000, False) + assert legacy_intent.allowed_latch + + legacy_cs.gearShifter = Gear.manumatic + legacy_cs.buttonEvents = [ + ButtonEvent.new_message(type=ButtonType.lkas, pressed=True), + ButtonEvent.new_message(type=ButtonType.lkas, pressed=False), + ] + observe(legacy_intent, legacy_cs, 30_000_000, 20_000_000, False) + assert legacy_intent.allowed_latch + + legacy_cs.buttonEvents = [] + observe(legacy_intent, legacy_cs, 40_000_000, 30_000_000, False) + assert legacy_intent.allowed_latch + + +def test_legacy_2025_line_visibility_and_passive_dashcam_chimes(): + import time + from openpilot.cereal import log, messaging + from openpilot.common.params import Params + from openpilot.selfdrive.controls.controlsd import _update_subaru_line_visibility + from openpilot.selfdrive.selfdrived.alertmanager import AlertManager + from openpilot.selfdrive.selfdrived.events import Events + from openpilot.selfdrive.selfdrived.selfdrived import SelfdriveD + from openpilot.starpilot.controllers.mode_actions import SwitchbackCooldown + + vis, timer = _update_subaru_line_visibility(None, 0.0, 0.55, 0.01) + assert vis and timer == 0.0 + vis, timer = _update_subaru_line_visibility(vis, timer, 0.42, 0.01) + assert vis and timer == 0.0 + for _ in range(24): + vis, timer = _update_subaru_line_visibility(vis, timer, 0.35, 0.01) + assert vis + vis, timer = _update_subaru_line_visibility(vis, timer, 0.35, 0.01) + assert not vis + for _ in range(99): + vis, timer = _update_subaru_line_visibility(vis, timer, 0.56, 0.01) + assert not vis + vis, timer = _update_subaru_line_visibility(vis, timer, 0.56, 0.01) + assert vis + + now = time.monotonic_ns() + names = ('deviceState', 'carControl', 'longitudinalPlan', 'starpilotLongitudinalPlan', 'modelV2', 'slcState') + data = {name: getattr(messaging.new_message(name), name) for name in names} + data['carControl'].hudControl.lanesVisible = True + + class _Sm: + def __init__(self): + self.frame = 1 + self.seen = dict.fromkeys(names, True) + self.valid = dict.fromkeys(names, True) + self.alive = dict.fromkeys(names, True) + self.logMonoTime = dict.fromkeys(names, now) + self.recv_time = dict.fromkeys(names, now / 1e9) + + def __getitem__(self, key): + return data[key] + + drive = SelfdriveD.__new__(SelfdriveD) + drive.CP = structs.CarParams(carFingerprint="SUBARU_LEGACY_2025", passive=True) + drive.enabled = False + drive.personality = log.LongitudinalPersonality.standard + drive.is_metric = False + drive.events = Events() + drive.AM = AlertManager() + drive.params = Params() + drive.switchback_capable = False + drive.switchback_setting_ns = now + drive.switchback_cooldown_ns = 0 + drive.switchback_cooldown = SwitchbackCooldown() + drive.aol_axis_decision = None + drive.aol_fault_reason = 'none' + drive.radar_recovery_enabled = False + drive.legacy_2025_green_wheel_active = True + vars(drive)['state_machine'] = SimpleNamespace(current_alert_types=[], soft_disable_timer=0) + vars(drive)['sm'] = _Sm() + + cs = structs.CarState(canValid=True, canTimeout=False) + cs.cruiseState.available = True + + drive.update_alerts(cs) + assert not drive.legacy_2025_green_wheel_active + assert drive.AM.current_alert.alert_type == "" + + drive.CP.passive = False + drive.sm.frame += 1 + drive.update_alerts(cs) + assert drive.legacy_2025_green_wheel_active + assert drive.AM.current_alert.alert_type == "legacy2025AolEngage/enable" + + +def test_legacy_2025_manumatic_driver_monitoring_isolation(tmp_path): + from unittest.mock import patch + from openpilot.cereal import messaging + from openpilot.common.params import Params + from openpilot.selfdrive.monitoring.dmonitoringd import _read_allow_manumatic + from openpilot.selfdrive.monitoring.policy import DriverMonitoring + + params = Params(str(tmp_path)) + assert _read_allow_manumatic(params) is None + for fingerprint, expected in (("SUBARU_OUTBACK_2023", False), ("SUBARU_LEGACY_2025", True)): + params.put("CarParams", structs.CarParams(carFingerprint=fingerprint).to_bytes(), block=True) + assert _read_allow_manumatic(params) is expected + + car_state = structs.CarState(vEgo=10.0, gearShifter=structs.CarState.GearShifter.manumatic) + selfdrive_state = messaging.new_message('selfdriveState').selfdriveState + model_v2 = messaging.new_message('modelV2').modelV2 + model_v2.meta.disengagePredictions.brakeDisengageProbs = [0.0] + extrinsics = messaging.new_message('extrinsicsCalibration').extrinsicsCalibration + extrinsics.rpyCalib = [0.0, 0.0, 0.0] + driver_state = messaging.new_message('driverStateV2').driverStateV2 + driver_state.leftDriverData.faceOrientation = [0.0, 0.0, 0.0] + driver_state.leftDriverData.facePosition = [0.0, 0.0] + driver_state.leftDriverData.faceOrientationStd = [0.0, 0.0] + driver_state.leftDriverData.facePositionStd = [0.0, 0.0] + sm = { + 'carState': car_state, + 'selfdriveState': selfdrive_state, + 'modelV2': model_v2, + 'extrinsicsCalibration': extrinsics, + 'driverStateV2': driver_state, + } + + with patch('openpilot.selfdrive.monitoring.policy.Params', return_value=params): + default_dm = DriverMonitoring(always_on=True) + default_dm.awareness = 0.8 + default_dm.run_step(sm) + assert default_dm.awareness == 1.0 + + legacy_dm = DriverMonitoring(always_on=True, allow_manumatic=True) + legacy_dm.run_step(sm) + car_state.gearShifter = structs.CarState.GearShifter.drive + drive_dm = DriverMonitoring(always_on=True, allow_manumatic=True) + drive_dm.run_step(sm) + assert legacy_dm.awareness == drive_dm.awareness < 1.0 diff --git a/openpilot/starpilot/car/subaru/tests/test_sng.py b/openpilot/starpilot/car/subaru/tests/test_sng.py index 5a84bd3ce9..14e91240f8 100644 --- a/openpilot/starpilot/car/subaru/tests/test_sng.py +++ b/openpilot/starpilot/car/subaru/tests/test_sng.py @@ -142,6 +142,16 @@ def test_sng_standstill_request_withdrawal_is_exact_and_does_not_grant_axis(): assert sng_standstill_lateral_inhibit(cp, stopped) stopped.standstill = False assert not sng_standstill_lateral_inhibit(cp, stopped) + # Non-Legacy Subarus keep upstream standstill-only inhibit even with initial_wait=True. + stopped.brakePressed = True + assert not sng_standstill_lateral_inhibit(cp, stopped, initial_wait=True) + # Legacy 2025 rolling with foot lightly on brake waits before Panda's initial !brake_pressed grant, then releases once brake lifts. + legacy_cp = CarInterface.get_params(CAR.SUBARU_LEGACY_2025, gen_empty_fingerprint(), [], False, False, False) + legacy_cp.alternativeExperience = 32 + assert sng_standstill_lateral_inhibit(legacy_cp, stopped, initial_wait=True) + assert not sng_standstill_lateral_inhibit(legacy_cp, stopped, initial_wait=False) + stopped.brakePressed = False + assert not sng_standstill_lateral_inhibit(legacy_cp, stopped, initial_wait=True) cp.openpilotLongitudinalControl = True stopped.standstill = True assert not sng_standstill_lateral_inhibit(cp, stopped) diff --git a/openpilot/starpilot/car/subaru/tests/test_stock_aol_callers.py b/openpilot/starpilot/car/subaru/tests/test_stock_aol_callers.py index b370c1c5a5..2120460bcc 100644 --- a/openpilot/starpilot/car/subaru/tests/test_stock_aol_callers.py +++ b/openpilot/starpilot/car/subaru/tests/test_stock_aol_callers.py @@ -334,8 +334,18 @@ def test_actual_full_engage_brake_reverse_temporary_recovery_mainoff(candidate, if any(address == 0x322 for address, _, _ in outgoing): dash = dash_decoder.vl['ES_LKAS_State'] expected = ci.CC.angle_was_active if steering_name == 'ES_LKAS_ANGLE' else card.sm['carControl'].latActive - assert bool(dash['LKAS_ACTIVE']) == expected, (candidate, tick, expected, dash) - assert dash['LKAS_Dash_State'] == (2 if expected else 0), (candidate, tick, expected, dash) + if candidate == 'SUBARU_LEGACY_2025': + assert bool(dash['LKAS_ACTIVE']), (candidate, tick, expected, dash) + if not cs.cruiseState.available or cs.steerFaultTemporary or cs.steerFaultPermanent: + assert not ci.CC.aol_dash_green_last, (candidate, tick, dash) + if expected: + assert ci.CC.aol_dash_green_last, (candidate, tick, dash) + ready_wheel = cs.cruiseState.available and bool(getattr(ci.CS, 'aol_enabled', True)) + expected_dash = 2 if ci.CC.aol_dash_green_last else (1 if ready_wheel else 0) + assert dash['LKAS_Dash_State'] == expected_dash, (candidate, tick, expected, expected_dash, dash) + else: + assert bool(dash['LKAS_ACTIVE']) == expected, (candidate, tick, expected, dash) + assert dash['LKAS_Dash_State'] == (2 if expected else 0), (candidate, tick, expected, dash) assert all(accepted for address, _, _, accepted in tx if address == 0x322) dash_emissions += 1 decoded_steering = [] @@ -445,7 +455,8 @@ def test_actual_full_engage_brake_reverse_temporary_recovery_mainoff(candidate, bool(intent and intent.lateralArmed) == aol and row['cardLatch'] == aol and row['permission'] == 0), row if 240 <= tick < 255: assert not command.latActive and bool(intent and intent.lateralArmed) == aol and row['cardLatch'] == aol and row['permission'] == 0, row - main_rearm = aol and candidate in (CAR.SUBARU_CROSSTREK_2025, CAR.SUBARU_IMPREZA_2025, CAR.SUBARU_IMPREZA_2020, CAR.SUBARU_OUTBACK_2023) + main_rearm = aol and candidate in (CAR.SUBARU_CROSSTREK_2025, CAR.SUBARU_IMPREZA_2025, CAR.SUBARU_IMPREZA_2020, + CAR.SUBARU_LEGACY_2025, CAR.SUBARU_OUTBACK_2023) if 330 <= tick < (350 if main_rearm else 400): assert not command.latActive and not bool(intent and intent.allowedLatch), row if rearm_on_brake and 355 <= tick < 365: @@ -698,7 +709,7 @@ 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), + CAR.SUBARU_IMPREZA_2020, CAR.SUBARU_IMPREZA_2025, CAR.SUBARU_CROSSTREK_2025, CAR.SUBARU_LEGACY_2025, CAR.SUBARU_OUTBACK_2023), eps_clear_join=recovery, eps_clear_axis_first=axis_first, preferences={'PauseLateralOnSignal': True, 'PauseLateralSpeed': 100., 'LateralResumeDelay': 0.}) @@ -724,7 +735,7 @@ def test_actual_subaru_stop_creep_restriction_preserves_armed_intent( subaru_native_pair, tmp_path, restriction, cold_stop, 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), + CAR.SUBARU_IMPREZA_2020, CAR.SUBARU_IMPREZA_2025, CAR.SUBARU_CROSSTREK_2025, CAR.SUBARU_LEGACY_2025, CAR.SUBARU_OUTBACK_2023), stop_resume=True, hard_stop_native_first=not cold_stop, stop_creep_eps=restriction, cold_stop=cold_stop) rows = json.loads((tmp_path / (str(candidate) + '-True-actual.json')).read_text()) assert any(row['cardLatch'] and row['armed'] and not row['lat'] and row['permission'] == 0 for row in rows if 135 <= row['tick'] < 137) diff --git a/openpilot/starpilot/car/subaru/tests/test_stop_start_callers.py b/openpilot/starpilot/car/subaru/tests/test_stop_start_callers.py index 1c108cd650..464a0ab69f 100644 --- a/openpilot/starpilot/car/subaru/tests/test_stop_start_callers.py +++ b/openpilot/starpilot/car/subaru/tests/test_stop_start_callers.py @@ -175,8 +175,18 @@ def test_actual_startup_factory_card_controls_native(enabled, manual, aol, subar if any(address == 0x322 for address, _, _ in outgoing): dash = dash_decoder.vl['ES_LKAS_State'] expected = ci.CC.angle_was_active if steering_name == 'ES_LKAS_ANGLE' else card.sm['carControl'].latActive - assert bool(dash['LKAS_ACTIVE']) == expected, (candidate, tick, expected, dash) - assert dash['LKAS_Dash_State'] == (2 if expected else 0), (candidate, tick, expected, dash) + if candidate == 'SUBARU_LEGACY_2025': + assert bool(dash['LKAS_ACTIVE']), (candidate, tick, expected, dash) + if not cs.cruiseState.available or cs.steerFaultTemporary or cs.steerFaultPermanent: + assert not ci.CC.aol_dash_green_last, (candidate, tick, dash) + if expected: + assert ci.CC.aol_dash_green_last, (candidate, tick, dash) + ready_wheel = cs.cruiseState.available and bool(getattr(ci.CS, 'aol_enabled', True)) + expected_dash = 2 if ci.CC.aol_dash_green_last else (1 if ready_wheel else 0) + assert dash['LKAS_Dash_State'] == expected_dash, (candidate, tick, expected, expected_dash, dash) + else: + assert bool(dash['LKAS_ACTIVE']) == expected, (candidate, tick, expected, dash) + assert dash['LKAS_Dash_State'] == (2 if expected else 0), (candidate, tick, expected, dash) assert all(accepted == (tick >= configure_delay) for address, _, _, accepted in tx if address == 0x322) dash_emissions += 1 for address, data_hex, bus, accepted in tx: diff --git a/openpilot/starpilot/car/toyota/tests/test_legacy_advert_lateral.py b/openpilot/starpilot/car/toyota/tests/test_legacy_advert_lateral.py index fccb987641..a1e78e9213 100644 --- a/openpilot/starpilot/car/toyota/tests/test_legacy_advert_lateral.py +++ b/openpilot/starpilot/car/toyota/tests/test_legacy_advert_lateral.py @@ -2,6 +2,7 @@ from dataclasses import replace import pytest from opendbc.car import gen_empty_fingerprint +from opendbc.car.toyota import legacy_advert_filter from opendbc.car.toyota.interface import CarInterface from opendbc.car.toyota.values import CAR from openpilot.starpilot.car.toyota.tests import test_legacy_sdsu_lateral as original @@ -22,6 +23,8 @@ def bind_evidence(candidate, monkeypatch): fp = gen_empty_fingerprint() fp[0][0x2FF] = 4 cp = CarInterface.get_params(candidate, fp, firmware(candidate), False, False, False) + if candidate == CAR.TOYOTA_HIGHLANDER: + assert legacy_advert_filter.prepare_stock(cp) cp.alternativeExperience = previous.alternativeExperience slot = replace(native.pandaInventory[0], safetyParam=cp.safetyConfigs[0].safetyParam) native = replace(native, safetyParam=slot.safetyParam, pandaInventory=(slot,)) diff --git a/openpilot/starpilot/car/toyota/tests/test_legacy_eps5_sdsu.py b/openpilot/starpilot/car/toyota/tests/test_legacy_eps5_sdsu.py index 3e46b11522..91316c9111 100644 --- a/openpilot/starpilot/car/toyota/tests/test_legacy_eps5_sdsu.py +++ b/openpilot/starpilot/car/toyota/tests/test_legacy_eps5_sdsu.py @@ -23,8 +23,10 @@ def test_sdsu_factory_changes_only_owned_hardware_fields(candidate): expected['safetyConfigs'][0]['safetyParam']=0x9049 if candidate == CAR.TOYOTA_SIENNA: expected['longitudinalActuatorDelay'] = pytest.approx(.5) - elif candidate == CAR.TOYOTA_HIGHLANDER and not cp.flags & ToyotaFlags.HYBRID: - expected['longitudinalActuatorDelay'] = pytest.approx(.4) + elif candidate == CAR.TOYOTA_HIGHLANDER: + expected['minEnableSpeed'] = -1. + if not cp.flags & ToyotaFlags.HYBRID: + expected['longitudinalActuatorDelay'] = pytest.approx(.4) assert cp.to_dict()==expected assert configured(cp) and qualified(cp) assert not toyota_auto_hold_supported(cp) diff --git a/openpilot/starpilot/car/toyota/tests/test_legacy_eps5_sdsu_callers.py b/openpilot/starpilot/car/toyota/tests/test_legacy_eps5_sdsu_callers.py index 75e5f761fe..572c0e6dde 100644 --- a/openpilot/starpilot/car/toyota/tests/test_legacy_eps5_sdsu_callers.py +++ b/openpilot/starpilot/car/toyota/tests/test_legacy_eps5_sdsu_callers.py @@ -18,16 +18,14 @@ def test_legacy_sdsu_real_callers(candidate,stock,scenario,host_heartbeat_bridge def observe(tick, host, cs, command, native, wires): if highlander_stop and 341 <= tick <= 350: - # The 10 Hz producer still holds the withdrawal sampled before this request. - # Real live permission cannot replace its missing serialized acknowledgment. + assert host.CP.minEnableSpeed < 0 wire = next(event for event in wires if event.which() == 'aolSafetyWire') state = decode_safety(bytes(wire.aolSafetyWire)) - assert state is not None and not state.requestedLateral + assert state is not None and state.requestedLateral and state.lateralAllowed assert native.aol_get_request_mask() == native.aol_get_permission_mask() == 1 - assert not command.latActive and not command.longActive + assert command.latActive and not command.longActive - helpers.run_case(stock,scenario,candidate=candidate,bridge=host_heartbeat_bridge,input_clock=True, - brake_stop_check_start=355 if highlander_stop else 350,on_sample=observe) + helpers.run_case(stock,scenario,candidate=candidate,bridge=host_heartbeat_bridge,input_clock=True,on_sample=observe) @pytest.mark.parametrize('candidate',MODELS) diff --git a/openpilot/starpilot/car/toyota/tests/test_legacy_sdsu_lateral.py b/openpilot/starpilot/car/toyota/tests/test_legacy_sdsu_lateral.py index 1c149762fd..d272692769 100644 --- a/openpilot/starpilot/car/toyota/tests/test_legacy_sdsu_lateral.py +++ b/openpilot/starpilot/car/toyota/tests/test_legacy_sdsu_lateral.py @@ -1,6 +1,7 @@ from dataclasses import replace import pytest from opendbc.car import structs, gen_empty_fingerprint +from opendbc.car.toyota import rav4h_filter from opendbc.car.toyota.interface import CarInterface from opendbc.car.toyota.values import CAR from openpilot.starpilot.car.toyota.legacy_lateral import below_engage_lateral_allowed @@ -16,6 +17,7 @@ def evidence(): fp=gen_empty_fingerprint() fp[0][0x2FF]=8 cp=CarInterface.get_params(CAR.TOYOTA_HIGHLANDER,fp,firmware(CAR.TOYOTA_HIGHLANDER),False,False,False) + assert rav4h_filter.prepare_stock(cp) cp.alternativeExperience=32 cs=structs.CarState(canValid=True,vEgo=0.,gearShifter=structs.CarState.GearShifter.drive) cs.cruiseState.available=True diff --git a/openpilot/starpilot/flm/diagnostic_state.py b/openpilot/starpilot/flm/diagnostic_state.py index 8a7e7b426c..3c05f4fbdb 100644 --- a/openpilot/starpilot/flm/diagnostic_state.py +++ b/openpilot/starpilot/flm/diagnostic_state.py @@ -12,7 +12,7 @@ from openpilot.starpilot.saved_source import read_saved MAX_BYTES = 65_536 MAX_EVENTS = 12 -ACTIVE = ('starting_analysis', 'reading_recording', 'checking_recommendations') +ACTIVE = ('starting_analysis', 'reading_recording', 'verifying_recording', 'checking_recommendations') FIELDS = {'stage', 'reason', 'build', 'recording_sha256', 'analysis_counts', 'recommendation_count', 'saved_adjustments', 'configuration_state', 'qualification', 'interrupted_stage', 'enabled', 'skipped_reasons'} @@ -102,8 +102,8 @@ def read_state(params): def _stage(value): reason = str(value.get('reason', '')) if value.get('status') == 'fitting': - return ('starting_analysis' if reason == 'loading_parked_analysis' else - 'reading_recording' if reason == 'analyzing_last_completed_drive' else 'checking_recommendations') + return {'loading_parked_analysis': 'starting_analysis', 'analyzing_last_completed_drive': 'reading_recording', + 'verifying_recorded_drive': 'verifying_recording'}.get(reason, 'checking_recommendations') if value.get('status') == 'unavailable': return 'analysis_error' if reason.startswith('waiting_for_'): diff --git a/openpilot/starpilot/flm/manual_coordinates.py b/openpilot/starpilot/flm/manual_coordinates.py index 2a144620ad..8a4488c4aa 100644 --- a/openpilot/starpilot/flm/manual_coordinates.py +++ b/openpilot/starpilot/flm/manual_coordinates.py @@ -27,6 +27,8 @@ def baseline_settings(cp, params): raw, readable = read_saved(params, DOCUMENT_KEY, MAX_DOCUMENT_BYTES) if not readable: raise ValueError('Readable selected baseline settings required') + if cp.lateralTuning.which() != 'torque': + raise ValueError('Selected steering tune does not contain torque settings') tune = cp.lateralTuning.torque basis = (float(tune.latAccelFactor), float(tune.latAccelOffset), float(tune.friction)) fingerprint = str(cp.carFingerprint) diff --git a/openpilot/starpilot/flm/offroad_daemon.py b/openpilot/starpilot/flm/offroad_daemon.py index c4aa660bee..9b16a45060 100644 --- a/openpilot/starpilot/flm/offroad_daemon.py +++ b/openpilot/starpilot/flm/offroad_daemon.py @@ -61,8 +61,8 @@ class StatusReport: counts = value.get('analysis_counts', {}) if type(counts) is not dict: counts = {} - phase = ('preparing' if value['reason'] == 'loading_parked_analysis' else - 'reading' if value['reason'] == 'analyzing_last_completed_drive' else 'checking') + phase = {'loading_parked_analysis': 'preparing', 'analyzing_last_completed_drive': 'reading', + 'verifying_recorded_drive': 'verifying'}.get(value['reason'], 'checking') progress = value.get('analysis_progress', {'phase': phase, 'completed': counts.get('original_segments_reviewed'), 'total': counts.get('original_segments_available')}) self.set({**(previous or value), 'status': 'fitting', 'reason': value['reason'], 'retained_analysis': bool(previous), @@ -342,13 +342,16 @@ def wait_for_parked(sm, params, *, stopped=lambda: False, clock=time.monotonic, timeout = 20 -def run_parked_analysis(worker, report): +def run_parked_analysis(worker, report, *, permission_loss=lambda: None): """Advance promptly only after an unreadable input was durably skipped.""" from openpilot.starpilot.flm.offroad_route import RouteInputError try: report.set(worker.run_once()) except (ValueError, OSError, RuntimeError) as error: + if (blocker := permission_loss()) is not None: + report.set({'status': 'unavailable', 'reason': blocker}) + return False if isinstance(error, RouteInputError): cloudlog.warning( 'FLM skipped unreadable drive %s: %s; continuing with other drives', @@ -371,7 +374,7 @@ def _run(): from openpilot.starpilot.drive_state.evidence import PhysicalSource from openpilot.starpilot.drive_state.owner import DriveStateOwner, Mode from openpilot.starpilot.flm.offroad_cache import directory_for_params - from openpilot.starpilot.flm.diagnostic_state import DiagnosticState + from openpilot.starpilot.flm.diagnostic_state import ACTIVE, DiagnosticState from openpilot.starpilot.storage import starpilot_storage_root params = Params() @@ -397,16 +400,29 @@ def _run(): return drive_state.snapshot().mode is Mode.OFFROAD and physical.update_ready(params.get_bool('IsOffroad')) def parked(): - allowed = wait_for_parked(sm, params, stopped=lambda: stopped, powered_offroad=powered_offroad) - if not allowed and not stopped and params.get_bool('IsOffroad'): - reason = parked_blocker(sm, params, powered_offroad=powered_offroad) - report.set({'status': 'collecting', 'reason': reason or 'waiting_for_parked_permission'}) - return allowed + return wait_for_parked(sm, params, stopped=lambda: stopped, powered_offroad=powered_offroad) + + def blocker(): + return parked_blocker(sm, params, stopped=stopped, powered_offroad=powered_offroad) or 'waiting_for_parked_permission' + + interrupted = None def permitted(): - okay = parked() + nonlocal interrupted + allowed = parked() + if not allowed and interrupted is None: + interrupted = blocker() + report.publish() + return allowed + + def last_blocker(): + return interrupted + + def on_progress(progress): + reason = {'verifying': 'verifying_recorded_drive', 'checking': 'checking_recorded_steering_recommendations'}.get( + progress['phase'], 'analyzing_last_completed_drive') + report.analyzing({'status': 'fitting', 'reason': reason, 'analysis_progress': progress}) report.publish() - return okay cache = directory_for_params(params) worker = None @@ -434,7 +450,12 @@ def _run(): report.publish(), ), ) - elif parked() and time.monotonic() >= next_analysis: + elif not parked(): + if not stopped and params.get_bool('IsOffroad'): + reason = blocker() + if report.current.get('reason') != reason: + report.set({'status': 'collecting', 'reason': reason}) + elif time.monotonic() >= next_analysis: if worker is None: report.analyzing({'status': 'fitting', 'reason': 'loading_parked_analysis'}) report.publish() @@ -446,9 +467,7 @@ def _run(): cache, permitted=permitted, on_analysis=lambda: report.analyzing({'status': 'fitting', 'reason': 'analyzing_last_completed_drive'}), - on_progress=lambda progress: report.analyzing({'status': 'fitting', 'reason': - 'checking_recorded_steering_recommendations' if progress['phase'] == 'checking' else 'analyzing_last_completed_drive', - 'analysis_progress': progress}), + on_progress=on_progress, on_assessment=lambda a: report.analyzing( { 'status': 'fitting', @@ -463,7 +482,8 @@ def _run(): ) report.restore(worker.cache) next_analysis = time.monotonic() + 10.0 - if run_parked_analysis(worker, report): + interrupted = None + if run_parked_analysis(worker, report, permission_loss=last_blocker): next_analysis = time.monotonic() report.publish() if not stopped: @@ -474,9 +494,7 @@ def _run(): raise finally: diagnostics = getattr(report, 'diagnostics', None) - if diagnostics is not None and diagnostics.state['current'] is not None and diagnostics.state['current']['stage'] in ( - 'starting_analysis', 'reading_recording', 'checking_recommendations' - ): + if diagnostics is not None and diagnostics.state['current'] is not None and diagnostics.state['current']['stage'] in ACTIVE: diagnostics.observe({'status': 'unavailable', 'reason': 'analysis_interrupted_by_shutdown'}) try: if sm is not None: diff --git a/openpilot/starpilot/flm/tests/test_diagnostic_state.py b/openpilot/starpilot/flm/tests/test_diagnostic_state.py index 7949a01125..465b8dd0dd 100644 --- a/openpilot/starpilot/flm/tests/test_diagnostic_state.py +++ b/openpilot/starpilot/flm/tests/test_diagnostic_state.py @@ -81,6 +81,34 @@ class TestDiagnosticState(unittest.TestCase): self.assertEqual(report.current['analysis_counts']['recorded_tracking'], 99) self.assertEqual(read_state(self.params)['last_attempt']['analysis_counts']['recorded_tracking'], 1234) + def test_current_verification_and_its_interruption_are_distinct_from_previous_drive(self): + from openpilot.starpilot.flm.offroad_route import RouteInputCancelled + + report = daemon.StatusReport(path=self.root / 'report.json') + report.diagnostics = DiagnosticState(self.params) + report.previous = {'completed_route': 'earlier-drive', 'vehicle': 'KIA_NIRO_PHEV_2022', + 'analysis_counts': {'original_segments_reviewed': 3, 'original_segments_available': 3}} + report.analyzing({'status': 'fitting', 'reason': 'verifying_recorded_drive', + 'analysis_progress': {'phase': 'verifying', 'completed': 2, 'total': 2}}) + report.publish() + active = self.exported(json.loads(report.path.read_bytes())) + self.assertEqual(active['current']['analysis']['Parked analysis progress'], ['verifying', 2, 2]) + self.assertTrue(active['current']['analysis']['Earlier analysis shown while updating']) + self.assertEqual(active['current']['analysis']['Recorded drive coverage'], '3 of 3 original recorded segments reviewed') + + def cancelled(): + raise RouteInputCancelled('Parked route input collection cancelled') + + worker = SimpleNamespace(run_once=cancelled) + reason = 'waiting_for_fresh_deviceState' + self.assertFalse(daemon.run_parked_analysis(worker, report, permission_loss=lambda: reason)) + self.assertEqual(report.current['reason'], reason) + outcome = self.exported()['learning_diagnostics']['last_result'] + self.assertEqual(outcome['reason'], reason) + self.assertEqual(outcome['interrupted_stage'], 'verifying_recording') + self.assertEqual(report.previous['completed_route'], 'earlier-drive') + self.assertFalse(directory_for_params(self.params).exists()) + def test_worker_startup_failure_is_captured_before_assessment_cache_exists(self): self.params.put_bool('IsOffroad', True, block=True) self.params.put('AutomaticSteeringProfiles', b'preserved-original', block=True) diff --git a/openpilot/starpilot/galaxy/flm_diagnostics.py b/openpilot/starpilot/galaxy/flm_diagnostics.py index 8873fa7b59..f729b79025 100644 --- a/openpilot/starpilot/galaxy/flm_diagnostics.py +++ b/openpilot/starpilot/galaxy/flm_diagnostics.py @@ -22,6 +22,8 @@ def _explanation(reason): 'recording_for_offroad_analysis': 'Recording while driving. Route analysis runs after parking; this is not an analysis result.', 'loading_parked_analysis': 'Starting the parked analysis worker.', 'analyzing_last_completed_drive': 'Reading recorded drive data.', + 'verifying_recorded_drive': 'The sections were read. FLM is verifying that the recording is unchanged.', + 'Parked route input collection cancelled': 'Reading was interrupted before the drive assessment finished. This report has no specific blocker.', 'checking_recorded_steering_recommendations': 'Checking recommendations against recorded controller and steering-delivery evidence.', 'previous_analysis_interrupted_before_completion': 'The learner restarted before its previous analysis reported an outcome.', 'analysis_interrupted_by_shutdown': 'Analysis was interrupted by shutdown or the return to driving.', @@ -122,6 +124,7 @@ def diagnostics(report, params): result['current']['reason'] = _reason(current.get('reason', 'learner_report_unavailable')) result['current']['explanation'] = _explanation(result['current']['reason']) result['current']['analysis'] = {key: details[key] for key in ( + 'Parked analysis progress', 'Earlier analysis shown while updating', 'Recorded steering observations', 'Retained control windows', 'Retained tracking windows', 'Recorded drive coverage', 'Drives in steering evidence history', 'Saved route adjustment count', 'Saved route configuration state', 'Recorded coordinate recommendations', 'Recorded suggestion sources', 'Recorded suggestion assessments', diff --git a/openpilot/starpilot/galaxy/setting_descriptions.py b/openpilot/starpilot/galaxy/setting_descriptions.py index f09aabda08..bc9612a585 100644 --- a/openpilot/starpilot/galaxy/setting_descriptions.py +++ b/openpilot/starpilot/galaxy/setting_descriptions.py @@ -86,7 +86,7 @@ DESCRIPTIONS = { 'SpeedLimitController': 'Follows accepted limits plus offsets up to SET speed. Missing data uses the previous accepted limit.', 'SLCOnEngage': ('Starts software cruise SET at the SLC limit plus offset. ' + 'A limit accepted this session remains available during data gaps. Previous-drive history does not initialize SET. ' + - 'RES restores the previous SET.'), + 'RES restores the previous SET. Redneck Cruise lowers the new SET only when a current limit is available.'), 'SLCOverrideMode': ('Cruise uses this target when you lift off the accelerator. ' + 'Holding your speed uses the highest speed you reached, up to SET.'), 'SLCWheelOverride': 'Press + to raise SET past the adjusted limit and use your new SET speed.', @@ -149,6 +149,7 @@ DESCRIPTIONS = { 'KeepScreenOnGpuLoading': 'Keeps the driving screen visible while an eGPU model loads. Manual Screen Off still works.', 'TurnOffCommaScreen': 'Pauses comma UI rendering to reduce CPU and GPU use. Tap once to wake the screen.', 'LoudBlindspotAlert': 'Uses the soft-warning sound when a lane change is blocked by a detected blind-spot vehicle.', + 'LoudBlindspotAlertMuteAtStandstill': 'Mutes Blindspot Alert While Lateral Is Off when stopped or moving below 1 mph.', 'LoudBlindspotAlertWhenDisengaged': ('Warns when signaling toward a detected blind-spot vehicle with steering assistance off or paused. ' + 'Independent of Loud Blindspot Alert. Hazards do not trigger it.'), 'SoundPack': 'Chooses the sounds used for driving alerts and chimes.', diff --git a/openpilot/starpilot/galaxy/settings.py b/openpilot/starpilot/galaxy/settings.py index 166fbe44a0..62d881e330 100644 --- a/openpilot/starpilot/galaxy/settings.py +++ b/openpilot/starpilot/galaxy/settings.py @@ -99,7 +99,7 @@ class ContextSource(Protocol): def sample(self) -> AuthorityContext: ... -def _qualified(ctx: AuthorityContext, group: str) -> bool: +def _qualified(ctx: AuthorityContext, group: str, *, params=None) -> bool: cp = ctx.cp if group == "preferences": return True @@ -126,8 +126,8 @@ def _qualified(ctx: AuthorityContext, group: str) -> bool: if group in ("conditional", "conditional_wheel", "long_output"): return bool((cp.openpilotLongitudinalControl or ctx.configuration_longitudinal) and not cp.notCar and not cp.dashcamOnly and not cp.passive) if group == "slc": - from opendbc.car.hyundai.software_cruise import selected as button_cruise_selected - return bool((cp.openpilotLongitudinalControl or ctx.configuration_longitudinal or button_cruise_selected(cp)) and + from openpilot.starpilot.car.hyundai.software_cruise_settings import slc_configurable + return bool((cp.openpilotLongitudinalControl or ctx.configuration_longitudinal or slc_configurable(cp, params)) and not cp.notCar and not cp.dashcamOnly and not cp.passive) if group == "long": return bool((cp.openpilotLongitudinalControl or ctx.configuration_longitudinal) and @@ -558,7 +558,7 @@ class SettingsGateway: if not session_valid(): return False fresh = self.context.sample() if live else ctx - return fresh.cp_raw == ctx.cp_raw and _qualified(fresh, group) + return fresh.cp_raw == ctx.cp_raw and _qualified(fresh, group, params=self.params) return FeatureSettingsOwner(self.params, authorized, learning_messages=lambda: self.context._messages() if isinstance(self.context, LiveContextSource) else None, vehicle_fingerprint=lambda: getattr(current().cp, "carFingerprint", None), diff --git a/openpilot/starpilot/galaxy/tests/description-key-inventory.json b/openpilot/starpilot/galaxy/tests/description-key-inventory.json index e12136e71b..06a4a18e32 100644 --- a/openpilot/starpilot/galaxy/tests/description-key-inventory.json +++ b/openpilot/starpilot/galaxy/tests/description-key-inventory.json @@ -66,6 +66,7 @@ "LowSpeedCruiseOnSet", "RedneckCruise", "LoudBlindspotAlert", + "LoudBlindspotAlertMuteAtStandstill", "LoudBlindspotAlertWhenDisengaged", "NostalgiaMode", "PIPPreviewEnabled", diff --git a/openpilot/starpilot/galaxy/tests/test_flm_acceptance.py b/openpilot/starpilot/galaxy/tests/test_flm_acceptance.py index 460b732444..a8cd56621c 100644 --- a/openpilot/starpilot/galaxy/tests/test_flm_acceptance.py +++ b/openpilot/starpilot/galaxy/tests/test_flm_acceptance.py @@ -190,6 +190,14 @@ class TestFindingAcceptance(unittest.TestCase): self.assertEqual(self.raw(), before) self.assertEqual(self.fixture.stored(), pending) + def test_pending_review_without_torque_tuning_is_unavailable(self): + from openpilot.starpilot.flm.review_settings import review_settings + from opendbc.car import structs + + cp = structs.CarParams.new_message(**self.cp.to_dict()) + cp.lateralTuning.init('pid') + self.assertIsNone(review_settings(cp, self.params)) + def test_pending_review_identity_ignores_only_coordinate_acceptance(self): from openpilot.starpilot.flm.offroad_worker import OffroadWorker diff --git a/openpilot/starpilot/galaxy/tests/test_flm_tracking_results.mjs b/openpilot/starpilot/galaxy/tests/test_flm_tracking_results.mjs index f4ed2e4b2f..c6a3e115be 100644 --- a/openpilot/starpilot/galaxy/tests/test_flm_tracking_results.mjs +++ b/openpilot/starpilot/galaxy/tests/test_flm_tracking_results.mjs @@ -1,12 +1,9 @@ import assert from 'node:assert/strict' -import { execFileSync } from 'node:child_process' import { compile } from '../web/vendor/vue/vue.esm-browser.js' import { FlmPage } from '../web/js/flm.js' import { GalaxySettingRow } from '../web/js/galaxy-setting-row.js' import { SURFACE_NAMES, FRICTION_NAMES, offroadView, offroadCoordinateEvidence, recommendationText, PID_UNSUPPORTED, validTrainingResults, validTrackingResults, trackingView, surfaceRows, measurementText, validTrackingValues, trackingCoordinates, validTrackingPlot, trackingPlotView, sourceSeconds, tunerStatus } from '../web/js/flm-training-results.js' -if (process.env.CI && process.platform === 'linux') execFileSync('python3', ['tools/ci/check_prebuilt_receipt.py', '--revision', 'HEAD'], { stdio: 'inherit' }) - const coordinates = amount => SURFACE_NAMES.map((name, i) => [name, i === 0 ? amount : 0]) const tracking = () => ({ version: 1, status: 'trial_active', reason: 'scoring_future_tracking', group: 'feedforward', names: ['ff_gain_left'], trialId: 'a'.repeat(64), phase: 'trial', requiredEpisodes: 3, diff --git a/openpilot/starpilot/galaxy/tests/test_flm_training_results.mjs b/openpilot/starpilot/galaxy/tests/test_flm_training_results.mjs index 4c97e801bc..4406beb0ed 100644 --- a/openpilot/starpilot/galaxy/tests/test_flm_training_results.mjs +++ b/openpilot/starpilot/galaxy/tests/test_flm_training_results.mjs @@ -227,12 +227,20 @@ console.log('Saved curve and slider adjustments, unsaved recommendations, absent const scan = report();scan.current.status = 'fitting';scan.current.reason = 'analyzing_last_completed_drive' scan.current.details['Original route segments reviewed'] = [99, 99] assert.equal(parkedAnalysisProgress(scan).percent, null) -for (const [phase, percent] of [['reading', 20], ['verifying', 20], ['checking', null]]) { +for (const [phase, percent, detail] of [ + ['reading', 20, '2 of 10 sections read in this recording'], + ['verifying', null, 'Checking that the recording is unchanged.'], + ['checking', null, 'Checking the suggested changes.'], +]) { scan.current.details['Parked analysis progress'] = [phase, 2, 10] assert(validTrainingResults(scan)) assert.equal(parkedAnalysisProgress(scan).percent, percent) - assert.equal(parkedAnalysisProgress(scan).detail, '2 of 10 sections read in this recording') + assert.equal(parkedAnalysisProgress(scan).detail, detail) } +scan.current.details['Parked analysis progress'] = ['reading', 3, 3] +assert.equal(parkedAnalysisProgress(scan).percent, null) +scan.current.reason = 'verifying_recorded_drive' +assert.equal(tunerStatus(scan, true).key, 'fitting') for (const counts of [[11, 10], [-1, 10], [true, 10], [1, 181], [1.5, 10], [null, null]]) { scan.current.details['Parked analysis progress'] = ['reading', ...counts] assert.equal(parkedAnalysisProgress(scan).percent, null) diff --git a/openpilot/starpilot/galaxy/tests/test_panda_wake_settings.py b/openpilot/starpilot/galaxy/tests/test_panda_wake_settings.py index 802dc30e6b..b3720a0d0b 100644 --- a/openpilot/starpilot/galaxy/tests/test_panda_wake_settings.py +++ b/openpilot/starpilot/galaxy/tests/test_panda_wake_settings.py @@ -225,8 +225,6 @@ def test_supported_hardware_uses_existing_alternate_firmware(setup, monkeypatch, HW_TYPE_TRES = Panda.HW_TYPE_TRES HW_TYPE_RED_PANDA = Panda.HW_TYPE_RED_PANDA HW_TYPE_CUATRO = Panda.HW_TYPE_CUATRO - HEALTH_PACKET_VERSION = 1 - CAN_PACKET_VERSION = 2 bootstub = False def __init__(self, serial): @@ -253,7 +251,7 @@ def test_supported_hardware_uses_existing_alternate_firmware(setup, monkeypatch, return b'image' def get_packets_versions(self): - return (1, 2) if protocol_ok else (0, 0) + return pandad.PACKET_VERSIONS if protocol_ok else (0, 0) def close(self): pass diff --git a/openpilot/starpilot/galaxy/tests/test_saved_torque_page.py b/openpilot/starpilot/galaxy/tests/test_saved_torque_page.py index bc3a7223d0..5c8949908e 100644 --- a/openpilot/starpilot/galaxy/tests/test_saved_torque_page.py +++ b/openpilot/starpilot/galaxy/tests/test_saved_torque_page.py @@ -39,7 +39,9 @@ class TestSavedTorquePage(unittest.TestCase): 'Use StarPilot Auto Learn', 'Highway Smoothing'}) developer = self.page('torque/developer') advanced = {row['label']: row for row in developer['rows']} - self.assertEqual(set(advanced), {'Lat Accel', 'Friction', 'Actuator delay'}) + self.assertEqual(set(advanced), {'Steering Controller', 'Lat Accel', 'Friction', 'Actuator delay'}) + self.assertTrue(advanced['Steering Controller']['available']) + self.assertEqual(advanced['Steering Controller']['value'], rows['Steering Controller']['value']) for label in ('Lat Accel', 'Friction'): self.assertTrue(advanced[label]['resetAvailable'], label) self.assertEqual(advanced[label]['defaultValue'], 'Vehicle/learned') diff --git a/openpilot/starpilot/galaxy/tests/test_settings.py b/openpilot/starpilot/galaxy/tests/test_settings.py index 30bd974708..a10338056c 100644 --- a/openpilot/starpilot/galaxy/tests/test_settings.py +++ b/openpilot/starpilot/galaxy/tests/test_settings.py @@ -155,6 +155,59 @@ class SettingsGatewayTest(unittest.TestCase): self.assertFalse(self.gateway.confirm(intent['intent'], self.session, self.generation)) self.assertTrue(self.params.get_bool('AlwaysOnLateral')) + def test_redneck_cruise_allows_slc_setup_before_next_startup(self): + from opendbc.car.hyundai.interface import CarInterface + from opendbc.car.hyundai.software_cruise import prepare, selected + from opendbc.car.hyundai.values import CAR + + cp = CarInterface.get_non_essential_params(CAR.HYUNDAI_KONA_NON_SCC) + raw = cp.as_reader().as_builder().to_bytes() + self.context.value = AuthorityContext(True, cp, raw) + self.params.put_bool('IsMetric', True, block=True) + + def slc_row(page): + return next(i for i, row in enumerate(page['rows']) if row['label'] == 'Speed Limit Controller') + + page = self.page('slc') + self.assertFalse(page['rows'][slc_row(page)]['available']) + self.params.put_bool('RedneckCruise', True, block=True) + page = self.page('slc') + index = slc_row(page) + self.assertTrue(page['rows'][index]['available']) + intent = self.gateway.preview(page['view'], index, 0, self.session, self.generation, value='On') + + self.params.put_bool('RedneckCruise', False, block=True) + self.assertFalse(self.gateway.confirm(intent['intent'], self.session, self.generation)) + self.assertFalse(self.params.get_bool('SpeedLimitController')) + + self.params.put_bool('RedneckCruise', True, block=True) + page = self.page('slc') + intent = self.gateway.preview(page['view'], slc_row(page), 0, self.session, self.generation, value='On') + self.assertTrue(self.gateway.confirm(intent['intent'], self.session, self.generation)) + self.assertTrue(self.params.get_bool('SpeedLimitController')) + page = self.page('slc') + index = next(i for i, row in enumerate(page['rows']) if row['label'] == 'Match Speed Limit on Engage') + self.assertTrue(page['rows'][index]['available']) + intent = self.gateway.preview(page['view'], index, 0, self.session, self.generation, value='On') + self.assertTrue(self.gateway.confirm(intent['intent'], self.session, self.generation)) + self.assertTrue(self.params.get_bool('SLCOnEngage')) + self.assertFalse(selected(cp)) + self.assertFalse(cp.openpilotLongitudinalControl) + self.assertEqual(cp.as_reader().as_builder().to_bytes(), raw) + + prepare(cp, True) + self.context.value = AuthorityContext(True, cp, cp.as_reader().as_builder().to_bytes()) + page = self.page('slc') + index = next(i for i, row in enumerate(page['rows']) if row['label'].endswith('offset')) + self.assertTrue(page['rows'][index]['available']) + intent = self.gateway.preview(page['view'], index, 0, self.session, self.generation, value=3) + self.assertTrue(self.gateway.confirm(intent['intent'], self.session, self.generation)) + + scc = CarInterface.get_non_essential_params(CAR.HYUNDAI_KONA) + self.context.value = AuthorityContext(True, scc, scc.to_bytes()) + page = self.page('slc') + self.assertFalse(page['rows'][slc_row(page)]['available']) + def test_pcm_cruise_long_owner_can_configure_slc_without_custom_cruise_authority(self): cp = self.context.value.cp cp.carFingerprint = "TOYOTA_HIGHLANDER_TSS2" diff --git a/openpilot/starpilot/galaxy/tests/test_system_monitor_storage.py b/openpilot/starpilot/galaxy/tests/test_system_monitor_storage.py index abb19e65fd..33bc680872 100644 --- a/openpilot/starpilot/galaxy/tests/test_system_monitor_storage.py +++ b/openpilot/starpilot/galaxy/tests/test_system_monitor_storage.py @@ -19,7 +19,7 @@ class SystemMonitorStorageTest(unittest.TestCase): (self.root / 'meminfo').write_text('MemTotal: 4096000 kB\nMemAvailable: 1024000 kB\n') (self.root / 'uptime').write_text('300 0\n') self.recordings = Path('/data/media/0/realdata') - self.devices = {Path('/data'): 1, self.recordings: 2} + self.devices = {Path('/data'): 1, Path('/data/media'): 1, self.recordings: 2} self.sizes = {Path('/data'): (21, 30, 7.6), self.recordings: (598, 916, 273)} self.calls = [] diff --git a/openpilot/starpilot/galaxy/web/js/flm-training-results.js b/openpilot/starpilot/galaxy/web/js/flm-training-results.js index c84e1e2588..21f7736a24 100644 --- a/openpilot/starpilot/galaxy/web/js/flm-training-results.js +++ b/openpilot/starpilot/galaxy/web/js/flm-training-results.js @@ -222,7 +222,8 @@ const REASONS = { trial_measurement_inconclusive: "Your saved steering adjustments are kept for the next drive.", trial_inconclusive_drive_limit: "Three trial drives did not establish an improvement. The prior tune was restored.", next_drive_observed_tracking_worse: "Comparable driving showed a steering regression, so the prior tune was restored.", - analyzing_last_completed_drive: "Analyzing the last completed drive while parked.", + analyzing_last_completed_drive: "Reading the completed drive.", + verifying_recorded_drive: "The sections were read. Auto Learn is verifying the recording.", checking_recorded_steering_recommendations: "Checking the recorded-drive recommendations against the original controller and steering outputs.", recorded_tracking_suggestion_not_yet_qualified_for_automatic_application: "Auto Learn reviewed the drive and left your tune unchanged. Consistent suggestions are listed when available.", original_controller_or_registered_encoder_check_refused: "A tune was suggested, but at least one original controller or encoder check refused it. Your saved tune was kept.", @@ -407,7 +408,7 @@ export function parkedAnalysisProgress(report) { const labels = { preparing: 'Preparing drive analysis', reading: 'Reading a recorded drive', verifying: 'Verifying the recording', checking: 'Checking steering suggestions' } const fallback = { loading_parked_analysis: 'preparing', analyzing_last_completed_drive: 'reading', - checking_recorded_steering_recommendations: 'checking' }[current.reason] + verifying_recorded_drive: 'verifying', checking_recorded_steering_recommendations: 'checking' }[current.reason] const value = current.details?.['Parked analysis progress'] const phase = Array.isArray(value) && value.length === 3 && Object.hasOwn(labels, value[0]) ? value[0] : fallback if (!Object.hasOwn(labels, phase)) return null @@ -416,8 +417,8 @@ export function parkedAnalysisProgress(report) { const steps = { preparing: 'Starting the parked analyzer.', reading: 'Reading the recording sections.', verifying: 'Checking that the recording is unchanged.', checking: 'Checking the suggested changes.' } return { phase, label: labels[phase], completed: counted ? done : null, total: counted ? total : null, - percent: counted && ['reading', 'verifying'].includes(phase) ? done / total * 100 : null, - detail: counted ? `${done} of ${total} sections read in this recording` : steps[phase] } + percent: counted && phase === 'reading' && done < total ? done / total * 100 : null, + detail: counted && phase === 'reading' ? `${done} of ${total} sections read in this recording` : steps[phase] } } export function tunerStatus(report, live = false, choiceLive = false, error = "", reportFresh = live) { @@ -426,7 +427,7 @@ export function tunerStatus(report, live = false, choiceLive = false, error = "" if (error) return { key: "offline", tone: "muted", title: "Connection interrupted", description: "Earlier results are available below. Current steering activity is unknown." } if (preference?.valid && preference.enabled === false || !preference && live && current?.enabled === false) return { key: "off", tone: "muted", title: "Auto Learn is off", description: "No driving samples are being collected by the learner. Turn it on in steering settings to begin." } - if (reportFresh && current?.status === 'fitting' && ['analyzing_last_completed_drive', 'checking_recorded_steering_recommendations'].includes(current.reason)) + if (reportFresh && current?.status === 'fitting' && ['analyzing_last_completed_drive', 'verifying_recorded_drive', 'checking_recorded_steering_recommendations'].includes(current.reason)) return { key: 'fitting', tone: 'active', title: 'Analyzing your drive', description: learningReason(current.reason) + (offroadView(report)?.retained ? ' Earlier drive findings remain below while this analysis runs.' : '') } if (reportFresh && preference?.valid && preference.enabled && preference.parked && current?.reason?.startsWith('waiting_for_')) return { key: 'waiting-parked', tone: 'muted', title: 'Waiting to analyze your drive', description: learningReason(current.reason) } diff --git a/openpilot/starpilot/lateral/controller_selection.py b/openpilot/starpilot/lateral/controller_selection.py index 154407eda0..7d3ed2432a 100644 --- a/openpilot/starpilot/lateral/controller_selection.py +++ b/openpilot/starpilot/lateral/controller_selection.py @@ -93,6 +93,39 @@ class ControllerSelection: mode: ControllerMode policy: str | None source: str + force_torque: bool = False + + +def torque_choice_cp(cp): + """Preview only calibrated torque-actuated cars; never change the caller's CP.""" + if generic_torque_supported(cp): + return cp + try: + platform = PLATFORMS.get(str(cp.carFingerprint)) + unsafe = (structs.CarParams.SafetyModel.noOutput, structs.CarParams.SafetyModel.silent, + structs.CarParams.SafetyModel.allOutput) + if (platform is None or platform.__class__.__module__.split('.')[-2] != str(cp.brand) or + cp.notCar or cp.passive or cp.dashcamOnly or + cp.steerControlType != structs.CarParams.SteerControlType.torque or cp.lateralTuning.which() != 'pid' or + not cp.safetyConfigs or any(config.safetyModel in unsafe for config in cp.safetyConfigs)): + return None + from opendbc.car.interfaces import CarInterfaceBase + prepared = cp.as_reader().as_builder() + CarInterfaceBase.configure_torque_tune(prepared.carFingerprint, prepared.lateralTuning) + return prepared if generic_torque_supported(prepared) else None + except (AttributeError, TypeError, ValueError, OverflowError, KeyError, NotImplementedError, OSError): + return None + + +def prepare_controller(cp, raw): + """Apply an explicit saved type before the interface and published CP exist.""" + selected = selection_from_bytes(cp, raw) + if selected.source != 'invalid' and selected.force_torque and cp.lateralTuning.which() == 'pid': + prepared = torque_choice_cp(cp) + if prepared is not None: + cp.lateralTuning.init('torque') + cp.lateralTuning.torque = prepared.lateralTuning.torque.to_dict() + return cp def policy_for(CP) -> str | None: @@ -198,21 +231,27 @@ def parse_document(raw: bytes) -> dict: if not isinstance(vehicles, dict) or len(vehicles) > len(KNOWN_POLICIES): raise ValueError('Invalid controller selection vehicles') for fingerprint, choice in vehicles.items(): - if (fingerprint not in KNOWN_POLICIES or not isinstance(choice, dict) or set(choice) != {'brand', 'mode'} or + if (fingerprint not in KNOWN_POLICIES or not isinstance(choice, dict) or set(choice) not in ({'brand', 'mode'}, {'brand', 'mode', 'forceTorque'}) or + ('forceTorque' in choice and type(choice['forceTorque']) is not bool) or choice['brand'] != KNOWN_POLICIES[fingerprint] or type(choice['mode']) is not str or choice['mode'] not in (ControllerMode.STANDARD, ControllerMode.STARPILOT)): raise ValueError('Invalid controller selection choice') return document -def replace_mode(raw: bytes | None, CP, mode: ControllerMode) -> bytes: +def replace_mode(raw: bytes | None, CP, mode: ControllerMode, *, force_torque: bool = False) -> bytes: """Change only one exact platform's saved choice, preserving other entries.""" - if policy_for(CP) is None: - raise ValueError('No exact torque policy for CarParams') + choice_cp = torque_choice_cp(CP) + if type(force_torque) is not bool or choice_cp is None or policy_for(choice_cp) is None: + raise ValueError('No calibrated torque controller for CarParams') mode = ControllerMode(mode) + if CP.lateralTuning.which() == 'pid' and mode == ControllerMode.STARPILOT and not force_torque: + raise ValueError('PID cars require an explicit torque controller choice') document = {'version': DOCUMENT_VERSION, 'vehicles': {}} if raw is None else parse_document(raw) vehicles = dict(document['vehicles']) vehicles[str(CP.carFingerprint)] = {'brand': str(CP.brand), 'mode': mode.value} + if force_torque: + vehicles[str(CP.carFingerprint)]['forceTorque'] = True encoded = json.dumps({'version': DOCUMENT_VERSION, 'vehicles': vehicles}, sort_keys=True, separators=(',', ':'), allow_nan=False).encode() if len(encoded) > MAX_DOCUMENT_BYTES: @@ -222,20 +261,25 @@ def replace_mode(raw: bytes | None, CP, mode: ControllerMode) -> bytes: def selection_from_bytes(CP, raw: bytes | None) -> ControllerSelection: default = default_selection(CP) - if raw is None or default.policy is None: + if raw is None: return default try: choice = parse_document(raw)['vehicles'].get(str(CP.carFingerprint)) if choice is None or choice['brand'] != str(CP.brand): return default - return ControllerSelection(ControllerMode(choice['mode']), default.policy, 'saved') + force_torque = choice.get('forceTorque', False) + choice_cp = torque_choice_cp(CP) if force_torque else CP + policy = policy_for(choice_cp) if choice_cp is not None else None + if policy is None and not (not force_torque and choice['mode'] == ControllerMode.STANDARD and torque_choice_cp(CP) is not None): + return ControllerSelection(default.mode, default.policy, 'invalid') + return ControllerSelection(ControllerMode(choice['mode']), policy, 'saved', force_torque) except (UnicodeError, ValueError, TypeError, OverflowError): return ControllerSelection(default.mode, default.policy, 'invalid') def read_selection(params, CP) -> ControllerSelection: """Read once at controls startup; a later settings write cannot change this controller.""" - if policy_for(CP) is None: + if torque_choice_cp(CP) is None: return default_selection(CP) try: with Path(params.get_param_path(DOCUMENT_KEY)).open('rb') as source: diff --git a/openpilot/starpilot/lateral/model_turn_assist.py b/openpilot/starpilot/lateral/model_turn_assist.py index dfb9957628..1dfc4e1362 100644 --- a/openpilot/starpilot/lateral/model_turn_assist.py +++ b/openpilot/starpilot/lateral/model_turn_assist.py @@ -101,7 +101,7 @@ def _plan_positions_are_finite(model_v2) -> bool: return False -def limit_curvature_to_plan(model_v2, curvature: float, v_ego: float) -> float: +def limit_curvature_to_plan(model_v2, curvature: float, v_ego: float, min_reach: float = TWITCH_GUARD_MIN_REACH) -> float: if not (math.isfinite(curvature) and math.isfinite(v_ego)): return curvature if v_ego >= TWITCH_GUARD_MAX_SPEED or curvature == 0.0: @@ -109,9 +109,9 @@ def limit_curvature_to_plan(model_v2, curvature: float, v_ego: float) -> float: if not _plan_positions_are_finite(model_v2): return curvature reach = get_plan_reach(model_v2) - if not math.isfinite(reach) or reach < TWITCH_GUARD_MIN_REACH: + if not math.isfinite(reach) or reach < min_reach: return curvature - plan = abs(_plan_circle_curvature(model_v2.position.x, model_v2.position.y, CURVATURE_HOLD_PLAN_LOOKAHEAD_FAR)) + plan = abs(_plan_circle_curvature(model_v2.position.x, model_v2.position.y, min(CURVATURE_HOLD_PLAN_LOOKAHEAD_FAR, reach))) if not math.isfinite(plan): return curvature straightness = (plan - TWITCH_GUARD_STRAIGHT_LO) / (TWITCH_GUARD_STRAIGHT_HI - TWITCH_GUARD_STRAIGHT_LO) diff --git a/openpilot/starpilot/lateral/tests/test_controller_types.py b/openpilot/starpilot/lateral/tests/test_controller_types.py new file mode 100644 index 0000000000..540915b9b8 --- /dev/null +++ b/openpilot/starpilot/lateral/tests/test_controller_types.py @@ -0,0 +1,152 @@ +"""Explicit controller choices reach startup without changing vehicle authority.""" +import json +from dataclasses import replace +from unittest.mock import patch + +import pytest + +from opendbc.car import DT_CTRL +from opendbc.car.car_helpers import interfaces +from openpilot.common.params import Params +from openpilot.selfdrive.controls.lib.lateral_controller_factory import create_lateral_controller +from openpilot.starpilot.lateral.controller_selection import ( + DOCUMENT_KEY, ControllerMode, parse_document, prepare_controller, replace_mode, + selection_from_bytes, torque_choice_cp, +) +from openpilot.starpilot.ui.feature_settings_owner import FeatureSettingsOwner +from openpilot.starpilot.ui.feature_settings_state import FeatureSettingsRequest +from openpilot.starpilot.vehicle_preferences import VehicleStartupPreferences + +PID_CARS = ('CHRYSLER_PACIFICA_2018_HYBRID', 'CHRYSLER_PACIFICA_2019_HYBRID', + 'HONDA_CIVIC', 'VOLKSWAGEN_GOLF_MK7') + + +def factory(identity): + return interfaces[identity].get_non_essential_params(identity) + + +@pytest.mark.parametrize('identity', PID_CARS) +@pytest.mark.parametrize('mode', list(ControllerMode)) +def test_explicit_choice_selects_real_controller_and_preserves_authority(identity, mode): + cp = factory(identity) + assert cp.lateralTuning.which() == 'pid' + baseline = cp.to_dict() + assert torque_choice_cp(cp) is not None + assert cp.to_dict() == baseline + assert prepare_controller(cp, None).to_dict() == baseline + raw = replace_mode(None, cp, mode, force_torque=True) + prepared = VehicleStartupPreferences(controller_selection=raw).prepare(cp) + actual = prepared.to_dict() + actual.pop('lateralTuning') + expected = baseline.copy() + expected.pop('lateralTuning') + assert actual == expected + assert prepared.lateralTuning.which() == 'torque' + selection = selection_from_bytes(prepared, raw) + ci = interfaces[identity](prepared) + controller = create_lateral_controller(prepared.as_reader(), ci, DT_CTRL, mode=selection.mode) + assert type(controller).__name__ == 'LatControlTorque' + assert (controller.starpilot_extension is not None) == (mode == ControllerMode.STARPILOT) + assert controller.torque_params.to_dict() == prepared.lateralTuning.torque.to_dict() + restored_raw = replace_mode(raw, prepared, ControllerMode.STANDARD) + stock = prepare_controller(factory(identity), restored_raw) + assert stock.to_dict() == baseline + stock_controller = create_lateral_controller(stock.as_reader(), interfaces[identity](stock), DT_CTRL, mode=ControllerMode.STANDARD) + assert type(stock_controller).__name__ == 'LatControlPID' + + +@pytest.mark.parametrize('identity', PID_CARS) +def test_developer_choice_saved_and_startup_snapshot_is_frozen(tmp_path, identity): + cp = factory(identity) + params = Params(str(tmp_path)) + owner = FeatureSettingsOwner(params, lambda _: True, vehicle_fingerprint=lambda: identity, vehicle_params=lambda: cp) + state = owner.snapshot('torque/developer', parked=True, system_long=False, lateral_context=True, metric=False) + current = next(r for r in state.rows if r.key == DOCUMENT_KEY) + assert current.available and current.value == 'Stock Controller' + assert current.choices == ('Stock Controller', 'Torque Controller', 'StarPilot Controller') + frozen = VehicleStartupPreferences.read(params, enabled=True) + request = FeatureSettingsRequest(current.key, current.source, 'Torque Controller', vehicle_fingerprint=identity, + capability=current.capability, dependencies=current.dependencies) + assert owner.apply(request) + assert not owner.apply(request) + assert frozen.prepare(factory(identity)).lateralTuning.which() == 'pid' + saved = VehicleStartupPreferences.read(params, enabled=True) + params.remove(DOCUMENT_KEY) + assert saved.prepare(factory(identity)).lateralTuning.which() == 'torque' + assert VehicleStartupPreferences.read(params, enabled=False).prepare(factory(identity)).lateralTuning.which() == 'pid' + assert cp.lateralTuning.which() == 'pid' + assert not owner.apply(replace(request, value='Invented Controller')) + + +@pytest.mark.parametrize('field,value', [('steerControlType', 'angle'), ('steerControlType', 'curvature'), + ('brand', 'toyota'), ('notCar', True), ('passive', True), ('dashcamOnly', True), ('carFingerprint', 'UNKNOWN')]) +def test_forced_choice_refuses_unsupported_configuration(field, value): + cp = factory(PID_CARS[0]) + raw = replace_mode(None, cp, ControllerMode.STARPILOT, force_torque=True) + setattr(cp, field, value) + before = cp.to_dict() + assert torque_choice_cp(cp) is None + assert prepare_controller(cp, raw).to_dict() == before + with pytest.raises(ValueError): + replace_mode(None, cp, ControllerMode.STANDARD, force_torque=True) + + +def test_missing_calibration_unsafe_profile_and_malformed_choice_do_not_convert(): + cp = factory(PID_CARS[0]) + original = cp.to_dict() + raw = replace_mode(None, cp, ControllerMode.STARPILOT, force_torque=True) + with patch('opendbc.car.interfaces.CarInterfaceBase.configure_torque_tune', side_effect=KeyError('missing')): + assert torque_choice_cp(cp) is None + assert prepare_controller(cp, raw).to_dict() == original + cp.safetyConfigs[0].safetyModel = 'noOutput' + assert torque_choice_cp(cp) is None + cp = factory(PID_CARS[0]) + for bad in (b'{}', b'x' * 4097, raw.replace(b'true', b'1'), raw.replace(b'true', b'"true"')): + assert selection_from_bytes(cp, bad).source == 'invalid' + assert prepare_controller(cp, bad).to_dict() == original + document = json.loads(raw) + del document['vehicles'][PID_CARS[0]]['forceTorque'] + legacy = json.dumps(document).encode() + assert prepare_controller(cp, legacy).to_dict() == original + assert prepare_controller(factory(PID_CARS[1]), raw).lateralTuning.which() == 'pid' + assert parse_document(raw)['vehicles'][PID_CARS[0]]['forceTorque'] is True + + +@pytest.mark.parametrize('identity', PID_CARS[:2]) +@pytest.mark.parametrize('mode', list(ControllerMode)) +def test_pacifica_choice_reaches_actual_controls(identity, mode): + import os + from openpilot.common.prefix import OpenpilotPrefix + from openpilot.selfdrive.controls.controlsd import Controls + with OpenpilotPrefix(), patch.dict(os.environ, {'SIMULATION': '1', 'REPLAY': '1'}): + params = Params() + cp = factory(identity) + raw = replace_mode(None, cp, mode, force_torque=True) + params.put(DOCUMENT_KEY, json.loads(raw), block=True) + preferences = VehicleStartupPreferences.read(params, enabled=True) + preferences.prepare(cp) + ci = interfaces[identity](cp) + preferences.finalize(cp) + preferences.configure_controller(ci) + params.put('CarParams', cp.to_bytes(), block=True) + controls = Controls() + assert type(controls.LaC).__name__ == 'LatControlTorque' + assert (controls.LaC.starpilot_extension is not None) == (mode == ControllerMode.STARPILOT) + assert controls.CP.to_dict()['safetyConfigs'] == cp.to_dict()['safetyConfigs'] + + +def test_every_eligible_factory_pid_can_select_and_restore(): + supported = [] + for identity in interfaces: + cp = factory(identity) + if cp.lateralTuning.which() != 'pid' or torque_choice_cp(cp) is None: + continue + before = cp.to_dict() + raw = replace_mode(None, cp, ControllerMode.STANDARD, force_torque=True) + prepare_controller(cp, raw) + assert cp.lateralTuning.which() == 'torque', identity + original = factory(identity) + prepare_controller(original, replace_mode(raw, cp, ControllerMode.STANDARD)) + assert original.to_dict() == before, identity + supported.append(identity) + assert set(PID_CARS).issubset(supported) diff --git a/openpilot/starpilot/lateral/tests/test_model_turn_assist_stop_hold.py b/openpilot/starpilot/lateral/tests/test_model_turn_assist_stop_hold.py index aceff6d17b..dc0f714e17 100644 --- a/openpilot/starpilot/lateral/tests/test_model_turn_assist_stop_hold.py +++ b/openpilot/starpilot/lateral/tests/test_model_turn_assist_stop_hold.py @@ -2,7 +2,7 @@ import unittest from types import SimpleNamespace from openpilot.starpilot.lateral.model_turn_assist import ( - STOP_HOLD_MAX_SPEED, TWITCH_GUARD_FLOOR, TWITCH_GUARD_MAX_SPEED, ModelTurnAssist, update_twitch_guard, + STOP_HOLD_MAX_SPEED, TWITCH_GUARD_FLOOR, TWITCH_GUARD_MAX_SPEED, ModelTurnAssist, limit_curvature_to_plan, update_twitch_guard, ) STRAIGHT = SimpleNamespace(position=SimpleNamespace(x=[0., 1., 2., 3.], y=[0., 0., 0., 0.]), @@ -124,6 +124,12 @@ class TestTwitchGuardArming(unittest.TestCase): self.assertFalse(assist.twitch_guard_armed) self.assertEqual(step(assist, 2.0, 0., .012, model=LONG_STRAIGHT), .012) + def test_short_straight_plan_down_to_4m_is_guarded(self): + short_straight = SimpleNamespace(position=SimpleNamespace(x=[0., 1., 2., 3., 4., 5.], y=[0.] * 6), + meta=SimpleNamespace(laneChangeState=0)) + self.assertEqual(limit_curvature_to_plan(short_straight, .012, 1.0), .012) + self.assertEqual(limit_curvature_to_plan(short_straight, .012, 1.0, min_reach=4.0), TWITCH_GUARD_FLOOR) + if __name__ == '__main__': unittest.main() diff --git a/openpilot/starpilot/speed_limits/tests/test_engagement.py b/openpilot/starpilot/speed_limits/tests/test_engagement.py index 5390f5a4cc..3f987d0b62 100644 --- a/openpilot/starpilot/speed_limits/tests/test_engagement.py +++ b/openpilot/starpilot/speed_limits/tests/test_engagement.py @@ -83,6 +83,45 @@ def engage(instance, *, now=START + 10_000_000): return cs +@pytest.mark.parametrize('gesture,match,limit,delay,expected', [ + ('decelCruise', True, 50., 80_000_000, 50.), + ('decelCruise', False, 50., 80_000_000, 60.), + ('accelCruise', True, 50., 80_000_000, 60.), + ('decelCruise', True, 70., 80_000_000, 60.), + ('decelCruise', True, 20., 80_000_000, 60.), + ('decelCruise', True, 50., 550_000_000, 60.), +]) +def test_redneck_set_matching_preserves_the_stock_ceiling_and_resume(gesture, match, limit, delay, expected): + from opendbc.car.hyundai.interface import CarInterface + from opendbc.car.hyundai.software_cruise import prepare + from opendbc.car.hyundai.values import CAR + from openpilot.starpilot.car.hyundai.redneck_cruise import RedneckCruise + + _, sm, _ = drive(metric=True, limit=limit, offset=0.) + cp = prepare(CarInterface.get_non_essential_params(CAR.HYUNDAI_KONA_NON_SCC), True) + instance = owner(sm, cp, metric=True, match=match) + instance.redneck_cruise = RedneckCruise(cp, SimpleNamespace(redneckCruiseAvailable=True, pcmCruiseSpeed=False)) + sm.seen, sm.recv_time = dict(sm.valid), {} + + def step(now, *, enabled, stock_speed, buttons=()): + sm.advance(now) + sm.recv_time['carControl'] = now / 1e9 + sm['carControl'].enabled = enabled + cs = car.CarState(canValid=True, vEgo=15., gearShifter='drive', buttonEvents=list(buttons), + cruiseState={'available': True, 'enabled': enabled, 'speed': stock_speed / 3.6, 'speedCluster': stock_speed / 3.6}) + with patch.object(card.time, 'monotonic_ns', return_value=now), patch.object(cruise, 'monotonic_ns', return_value=now): + instance.update_cruise_speed(cs) + instance.CS_prev = cs + instance.CC_prev = car.CarControl(enabled=enabled) + return instance.v_cruise_helper.v_cruise_kph + + step(START, enabled=False, stock_speed=0., buttons=({'type': gesture, 'pressed': True},)) + assert step(START + 20_000_000, enabled=True, stock_speed=0.) == cruise.V_CRUISE_UNSET + assert step(START + delay, enabled=True, stock_speed=60.) == pytest.approx(expected) + assert step(START + delay + 20_000_000, enabled=True, stock_speed=60.) == pytest.approx(expected) + assert not sm['carControl'].longActive and not cp.openpilotLongitudinalControl + + def receipt(instance, *, now=START + 10_000_000, event_id=1): kind, state, previous, selected, observed = instance.slc_receipts[-1] return CruiseEvent(event_id, observed, previous, selected, 'decel', instance.slc_producer_session, now, diff --git a/openpilot/starpilot/system/starport/bluetooth_bridge.py b/openpilot/starpilot/system/starport/bluetooth_bridge.py index 7d09cb748b..0b5814686e 100644 --- a/openpilot/starpilot/system/starport/bluetooth_bridge.py +++ b/openpilot/starpilot/system/starport/bluetooth_bridge.py @@ -27,6 +27,10 @@ from openpilot.starpilot.system.starport.incoming_pairing import IncomingPairing AA_AGENT_PATH = '/org/starpilot/starport/pairing' +class BluetoothAdapterBusy(BluetoothRejected): + pass + + class BluetoothAdmissionError(RuntimeError): pass @@ -187,9 +191,12 @@ class SharedBluetoothOwner(BluetoothOwner): stream = os.fdopen(fd, 'r+') try: fcntl.flock(stream, fcntl.LOCK_EX | fcntl.LOCK_NB) + except BlockingIOError: + stream.close() + raise BluetoothAdapterBusy('Bluetooth adapter is busy in another process') from None except BaseException: stream.close() - raise BluetoothRejected('Bluetooth adapter is busy in another process') from None + raise return stream def _journal(self, path: str, sender: str, pairable: bool, discoverable: bool) -> None: @@ -216,7 +223,13 @@ class SharedBluetoothOwner(BluetoothOwner): def recover_phone_role(self) -> bool: """Restore a crashed holder's visibility only on the same BlueZ instance.""" with self.lock: - with self._process_lock(): + if not self.journal_path.exists(): + return False + try: + process_lock = self._process_lock() + except BluetoothAdapterBusy: + return False + with process_lock: if not self.journal_path.exists(): return False data = self._read_journal() @@ -370,6 +383,7 @@ class SharedBluetoothOwner(BluetoothOwner): def maintain_phone_role(self) -> None: lease = self.phone_lease if lease is None: + self.recover_phone_role() return if lease.session is not None: try: diff --git a/openpilot/starpilot/system/starport/tests/test_bluetooth_bridge.py b/openpilot/starpilot/system/starport/tests/test_bluetooth_bridge.py index f65e913621..e4e81e28f7 100644 --- a/openpilot/starpilot/system/starport/tests/test_bluetooth_bridge.py +++ b/openpilot/starpilot/system/starport/tests/test_bluetooth_bridge.py @@ -524,3 +524,24 @@ def test_default_agent_failure_cleans_registration_before_pairing_visibility(): with pytest.raises(BluetoothRejected, match='permission denied'): client.register_incoming_agent(Mock(wraps=object()), ':1.20') assert calls == ['RegisterAgent', 'RequestDefaultAgent', 'UnregisterAgent', 'filter_closed'] + + +def test_recovery_defers_while_another_process_holds_the_adapter(tmp_path): + state = {'parked': True, 'session': ('galaxy', '42')} + bluez = FakeBlueZ() + first = owner(tmp_path, state, bluez) + lease = first.acquire_phone_role(state['session'], Phone()) + second = owner(tmp_path, state, bluez) + journal = first.journal_path.read_bytes() + before = list(bluez.writes) + + assert second.recover_phone_role() is False + second.maintain_phone_role() + assert first.journal_path.read_bytes() == journal + assert bluez.writes == before + + lease.process_lock.close() + second.maintain_phone_role() + assert bluez.writes[-1] == (False, False) + assert not second.journal_path.exists() + second.close() diff --git a/openpilot/starpilot/tests/test_vehicle_preferences.py b/openpilot/starpilot/tests/test_vehicle_preferences.py index c0a369c2ec..6b7d7000dd 100644 --- a/openpilot/starpilot/tests/test_vehicle_preferences.py +++ b/openpilot/starpilot/tests/test_vehicle_preferences.py @@ -612,7 +612,7 @@ class TestVehicleStartupPreferences(unittest.TestCase): self.assertEqual(cp.alternativeExperience, 0) def test_unrelated_vehicle_flags_are_untouched(self): - cp = SimpleNamespace(brand="other", flags=4096, alternativeExperience=256) + cp = structs.CarParams(brand="other", flags=4096, alternativeExperience=256) preferences = VehicleStartupPreferences(True) self.assertIs(preferences.prepare(cp), cp) preferences.finalize(cp) diff --git a/openpilot/starpilot/tests/test_vehicle_state_context.py b/openpilot/starpilot/tests/test_vehicle_state_context.py index 0cfe900579..4ca26c52bc 100644 --- a/openpilot/starpilot/tests/test_vehicle_state_context.py +++ b/openpilot/starpilot/tests/test_vehicle_state_context.py @@ -105,7 +105,7 @@ class TestVehicleStateContext(unittest.TestCase): self.assertEqual(ast.unparse(update.args[0]), 'CS') self.assertEqual(ast.unparse(initialize.args[0]), 'self.CS_prev') self.assertEqual(ast.unparse(initialize.keywords[0].value), 'self.vehicle_startup.consume_cruise_resume()') - enable_edge = next(node for node in ast.walk(helper) if isinstance(node, ast.If)) + enable_edge = next(node for node in helper.body[0].body if isinstance(node, ast.If) and initialize in ast.walk(node)) self.assertEqual(ast.unparse(enable_edge.test), "self.sm['carControl'].enabled and (not self.CC_prev.enabled)") self.assertIn(initialize, list(ast.walk(enable_edge))) step = inspect.getsource(card.Car.step) diff --git a/openpilot/starpilot/ui/controller_feature.py b/openpilot/starpilot/ui/controller_feature.py index 0c24177123..e5caa8ed45 100644 --- a/openpilot/starpilot/ui/controller_feature.py +++ b/openpilot/starpilot/ui/controller_feature.py @@ -7,7 +7,7 @@ import math import json from openpilot.starpilot.lateral.controller_selection import ( - DOCUMENT_KEY, LEARNING_OFF_KEY, MAX_DOCUMENT_BYTES, ControllerMode, policy_for, replace_mode, selection_from_bytes, + DOCUMENT_KEY, LEARNING_OFF_KEY, MAX_DOCUMENT_BYTES, ControllerMode, policy_for, replace_mode, selection_from_bytes, torque_choice_cp, ) from openpilot.starpilot.lateral.learning_preferences import ( KEY as LEARNING_PREFERENCES_KEY, MAX_BYTES as LEARNING_PREFERENCES_LIMIT, read_preference, replace_preference, @@ -21,7 +21,9 @@ from openpilot.starpilot.ui.feature_settings_state import FeatureRow, FeatureSet CHOICES = ('Stock Controller', 'StarPilot Controller') +TORQUE_CHOICE = 'Torque Controller' MODES = dict(zip(CHOICES, (ControllerMode.STANDARD, ControllerMode.STARPILOT), strict=True)) +MODES[TORQUE_CHOICE] = ControllerMode.STANDARD TUNING_GUIDANCE = ("StarPilot's torque controller can provide higher low-speed steering accuracy, but may require additional tuning. " + "Join the StarPilot Discord and open a tuning request: https://firestar.link/discord") SETUP_ACTION = 'torque_prepare_firestar' @@ -61,16 +63,18 @@ class ControllerFeature: if CP is None or CP.notCar: return None try: - policy = policy_for(CP) + prepared = torque_choice_cp(CP) + policy = policy_for(prepared) if prepared is not None else None if policy is None: return None - tune = CP.lateralTuning.torque + tune = prepared.lateralTuning.torque firmware = tuple((str(fw.ecu), bytes(fw.fwVersion)) for fw in CP.carFw) return (str(CP.brand), str(CP.carFingerprint), policy, str(CP.steerControlType), str(CP.lateralTuning.which()), bool(CP.passive), bool(CP.dashcamOnly), bool(CP.notCar), int(CP.flags), int(CP.alternativeExperience), float(tune.latAccelFactor), float(tune.latAccelOffset), float(tune.friction), float(tune.steeringAngleDeadzoneDeg), - float(CP.steerActuatorDelay), float(CP.steerLimitTimer), str(CP.carVin), firmware) + float(CP.steerActuatorDelay), float(CP.steerLimitTimer), str(CP.carVin), firmware, + json.dumps(CP.lateralTuning.to_dict(), sort_keys=True, separators=(',', ':'))) except (AttributeError, TypeError, ValueError, OverflowError): return None @@ -117,7 +121,9 @@ class ControllerFeature: learning = ({LEARNING_PREFERENCES_KEY: replace_preference(sources[LEARNING_PREFERENCES_KEY], CP, False)} if LEARNING_PREFERENCES_KEY in sources else {}) return {**SETUP_DEFAULTS, **learning, LANE_CHANGE_KEY: json.dumps(to_value(lane), sort_keys=True, separators=(',', ':')).encode(), - DOCUMENT_KEY: replace_mode(sources[DOCUMENT_KEY], CP, ControllerMode.STARPILOT)} + DOCUMENT_KEY: replace_mode(sources[DOCUMENT_KEY], CP, ControllerMode.STARPILOT, + force_torque=steering_controller(CP) == 'pid' or + selection_from_bytes(CP, sources[DOCUMENT_KEY]).force_torque)} def setup_row(self) -> FeatureRow | None: CP = self.vehicle_params() @@ -176,15 +182,16 @@ class ControllerFeature: raw, readable = read_saved(self.params, DOCUMENT_KEY, MAX_DOCUMENT_BYTES) selected = selection_from_bytes(CP, raw) if readable else None valid = readable and selected is not None and selected.source != 'invalid' - value = CHOICES[0] if valid and selected.mode == ControllerMode.STANDARD else \ - CHOICES[1] if valid else 'Invalid saved controller choice' + value = (TORQUE_CHOICE if selected.force_torque and selected.mode == ControllerMode.STANDARD else + CHOICES[0] if selected.mode == ControllerMode.STANDARD else CHOICES[1]) if valid else 'Invalid saved controller choice' + choices = (CHOICES[0], TORQUE_CHOICE, CHOICES[1]) if steering_controller(CP) == 'pid' or valid and selected.force_torque else CHOICES learning, learning_readable = read_saved(self.params, LEARNING_OFF_KEY, 1) preference = read_preference(self.params, CP, legacy_snapshot=(learning, learning_readable)) learning_valid = learning_readable and preference.valid allowed = valid and learning_valid and self.authority('preferences') reason = ('Choose the steering controller for your next drive. ' + TUNING_GUIDANCE if valid and learning_valid else 'Saved steering preferences are unreadable or invalid; no change was made.') - return FeatureRow(DOCUMENT_KEY, 'Steering Controller', value, raw, CHOICES if valid else (), + return FeatureRow(DOCUMENT_KEY, 'Steering Controller', value, raw, choices if valid else (), available=allowed, reason=reason, capability=capability, dependencies=((LEARNING_OFF_KEY, learning), (LEARNING_PREFERENCES_KEY, preference.raw)), default_value=CHOICES[0] if selection_from_bytes(CP, None).mode == ControllerMode.STANDARD else CHOICES[1]) @@ -238,7 +245,8 @@ class ControllerFeature: not request.vehicle_fingerprint or request.vehicle_fingerprint != self.vehicle_fingerprint()): return False CP = self.vehicle_params() - if CP is None or request.capability != self.capability(CP): + row = self.row() + if CP is None or row is None or request.value not in row.choices or request.capability != self.capability(CP): return False raw, readable = read_saved(self.params, DOCUMENT_KEY, MAX_DOCUMENT_BYTES) learning, learning_readable = read_saved(self.params, LEARNING_OFF_KEY, 1) @@ -251,7 +259,9 @@ class ControllerFeature: selected = selection_from_bytes(CP, raw) if selected.source == 'invalid': return False - encoded = replace_mode(raw, CP, MODES[request.value]) + force_torque = request.value == TORQUE_CHOICE or request.value == CHOICES[1] and ( + steering_controller(CP) == 'pid' or selected.force_torque) + encoded = replace_mode(raw, CP, MODES[request.value], force_torque=force_torque) except (UnicodeError, ValueError, TypeError, OverflowError): return False diff --git a/openpilot/starpilot/ui/feature_settings_owner.py b/openpilot/starpilot/ui/feature_settings_owner.py index 8409a6155a..7bbefa7267 100644 --- a/openpilot/starpilot/ui/feature_settings_owner.py +++ b/openpilot/starpilot/ui/feature_settings_owner.py @@ -620,8 +620,7 @@ class FeatureSettingsOwner: return value, value is not None and 0.0 <= value <= 100.0, canonical, legacy def _read_saved(self, key: str, limit: int) -> tuple[bytes | None, bool]: - # One assembly observes one complete source per key. Actions and the next - # assembly always read the filesystem again, including unreadable sources. + # Cache source reads only within each snapshot. reads = self._snapshot_reads.get() def read(): try: @@ -1128,6 +1127,9 @@ class FeatureSettingsOwner: rows.extend(longitudinal_developer_rows(self)) elif page == FeaturePage.DEVELOPER_LATERAL: title = 'Developer Parameters' + controller_row = self.controller.row() + if controller_row is not None: + rows.append(controller_row) capability = self._capability("torque") or self._capability("gain") allowed = configurable and self.authority("torque") and capability is not None _, numeric_rows = self.torque.rows(capability, allowed, repair_allowed=parked and allowed) @@ -1183,9 +1185,9 @@ class FeatureSettingsOwner: rows.extend(self._cruise_rows(configurable)) rows.extend(self.wheel.rows()) elif page == FeaturePage.SLC: - from opendbc.car.hyundai.software_cruise import selected as button_cruise_selected cp = self.vehicle_params() - slc_available = system_long if cp is None else self.longitudinal_available() or button_cruise_selected(cp) + button_cruise = hyundai_software_cruise.slc_configurable(cp, self.params) + slc_available = system_long if cp is None else self.longitudinal_available() or button_cruise system_long = slc_available and self.authority("slc") allowed = configurable and system_long offsets_ready, offset_rows = self.slc_offsets.rows(allowed, repair_allowed=parked and allowed) @@ -1205,10 +1207,10 @@ class FeatureSettingsOwner: control_row = self._bool_row("SpeedLimitController", "Speed Limit Controller", allowed and (offsets_ready or control == "1"), reason=control_reason) rows.append(replace(control_row, reason=control_reason) if control_row.choices else control_row) - cp = self.vehicle_params() - if cp is not None and not cp.pcmCruise: + if cp is not None and (not cp.pcmCruise or button_cruise): rows.append(self._bool_row("SLCOnEngage", "Match Speed Limit on Engage", allowed and control == "1", - reason="Start SET at the SLC limit plus offset. RES restores your previous SET")) + reason="Lower your new SET to the speed limit plus offset when using Redneck Cruise" + if button_cruise else "Start SET at the SLC limit plus offset. RES restores your previous SET")) rows.append(self._bool_row("ShowSpeedLimits", "Show speed limit signs", self.authority("preferences"), reason="Display signs independently of Speed Limit Controller; does not change cruise speed")) rows.extend(policy_rows(self._value, self._readable, allowed=allowed)) @@ -1433,8 +1435,7 @@ class FeatureSettingsOwner: def apply(self, request: FeatureSettingsRequest, *, reset_default: bool = False) -> bool: if reset_default and not self.authority("parked_preferences"): return False - # A request may arrive through a callback during assembly. Its compare and - # authorization checks must still observe current sources independently. + # Recheck live sources even from snapshot callbacks. token = self._snapshot_reads.set(None) vehicle_token = self._snapshot_vehicle.set(None) try: @@ -1753,7 +1754,8 @@ class FeatureSettingsOwner: return False if key in ("SLCOnEngage", WHEEL_OVERRIDE_KEY): cp = self.vehicle_params() - if cp is None or cp.pcmCruise or not self.longitudinal_available() or ( + button_match = key == "SLCOnEngage" and hyundai_software_cruise.slc_configurable(cp, self.params) + if (not (button_match or cp is not None and not cp.pcmCruise and self.longitudinal_available()) or request.value == "On" and self._raw("SpeedLimitController") != b"1"): return False encoded = "1" if request.value == "On" else "0" diff --git a/openpilot/starpilot/ui/runtime_app.py b/openpilot/starpilot/ui/runtime_app.py index 2772714b2e..6d46b60a20 100644 --- a/openpilot/starpilot/ui/runtime_app.py +++ b/openpilot/starpilot/ui/runtime_app.py @@ -720,8 +720,8 @@ class StarShellSession: from openpilot.starpilot.feature_capabilities import lateral_supported return lateral_supported(cp) if group == "slc": - from opendbc.car.hyundai.software_cruise import selected as button_cruise_selected - if button_cruise_selected(cp): + from openpilot.starpilot.car.hyundai.software_cruise_settings import slc_configurable + if slc_configurable(cp, ui_state.params): return True if group in ("conditional", "conditional_wheel", "long_output", "slc"): return bool(cp.openpilotLongitudinalControl and not cp.notCar and not cp.passive and not cp.dashcamOnly) diff --git a/openpilot/starpilot/ui/runtime_snapshot.py b/openpilot/starpilot/ui/runtime_snapshot.py index a7770ec1be..84388b41b5 100644 --- a/openpilot/starpilot/ui/runtime_snapshot.py +++ b/openpilot/starpilot/ui/runtime_snapshot.py @@ -687,7 +687,11 @@ class RuntimeSnapshotAdapter: display_message(sm, "carOutput", now_ns, after_frame=after) if started else None, display_message(sm, "vehicleParameters", now_ns, after_frame=after) if started else None, cp, ) - display_lat_active = bool(display_control.latActive) if display_control is not None else False + legacy_2025_lateral_off = bool( + cp is not None and getattr(cp, 'carFingerprint', '') == 'SUBARU_LEGACY_2025' and + display_control is not None and not getattr(getattr(display_control, 'hudControl', None), 'lanesVisible', True) + ) + display_lat_active = bool(display_control.latActive) if (display_control is not None and not legacy_2025_lateral_off) else False display_long_active = bool(display_control.longActive) if display_control is not None else False long_engaged = bool(display_selfdrive is not None and getattr(display_selfdrive, 'enabled', False)) if getattr(ui, 'aol_runtime', False): @@ -742,10 +746,25 @@ class RuntimeSnapshotAdapter: weather_location = (fix[1].latitude, fix[1].longitude) break aol_latched = (display_aol_latch(sm, now_ns, after_frame=after) - if started and getattr(ui, "aol_runtime", False) else None) - armed_at_stop = bool(aol_latched and cp is not None and getattr(cp, 'brand', '') == 'subaru' and display_car_valid and - display_car.standstill and str(display_car.gearShifter) == 'drive' and - not display_car.steerFaultTemporary and not display_car.steerFaultPermanent and not display_car.accFaulted) + if started and getattr(ui, "aol_runtime", False) and not legacy_2025_lateral_off else None) + if cp is not None and getattr(cp, 'carFingerprint', '') == 'SUBARU_LEGACY_2025': + armed_at_stop = False + if (aol_latched and display_car_valid and + str(getattr(display_car, 'gearShifter', '')) in ('drive', 'manumatic') and + not getattr(display_car, 'steerFaultTemporary', False) and + not getattr(display_car, 'steerFaultPermanent', False) and + not getattr(display_car, 'accFaulted', False)): + min_steer_speed = max(float(getattr(cp, 'minSteerSpeed', 0.0) or 0.0), 0.3) + raw_v = getattr(display_car, 'vEgo', None) + car_speed = _finite(abs(float(raw_v))) if raw_v is not None else None + armed_at_stop = bool( + getattr(display_car, 'standstill', False) or + (car_speed is not None and car_speed <= min_steer_speed) + ) + else: + armed_at_stop = bool(aol_latched and cp is not None and getattr(cp, 'brand', '') == 'subaru' and display_car_valid and + display_car.standstill and str(display_car.gearShifter) == 'drive' and + not display_car.steerFaultTemporary and not display_car.steerFaultPermanent and not display_car.accFaulted) drive_mode_source = display_message(sm, 'starpilotCarState', now_ns, after_frame=after) if started else None alert = self._drive_mode_notice.update( drive_mode_source, display_car, cp=cp, drive_frame=after, diff --git a/openpilot/starpilot/ui/slc_offset_feature.py b/openpilot/starpilot/ui/slc_offset_feature.py index 3db24f34cc..a89739aa39 100644 --- a/openpilot/starpilot/ui/slc_offset_feature.py +++ b/openpilot/starpilot/ui/slc_offset_feature.py @@ -7,6 +7,7 @@ from dataclasses import dataclass import math import threading +from openpilot.starpilot.car.hyundai.software_cruise_settings import slc_configurable from openpilot.starpilot.speed_limits import offset_document as od from openpilot.starpilot.ui.feature_settings_state import FeatureRow, FeatureSettingsRequest, SLC_OFFSET_KEYS from openpilot.starpilot.saved_source import read_saved @@ -64,12 +65,14 @@ def _whole_limit_cutoff(bound_mps: float, factor: float) -> int: return nearest + (c_float(nearest * factor).value < bound_mps) -def _capability(cp, configuration_longitudinal=False) -> tuple | None: +def _capability(cp, configuration_longitudinal=False, *, params=None) -> tuple | None: try: - if cp is None or not cp.carFingerprint or not (cp.openpilotLongitudinalControl or configuration_longitudinal) or \ - cp.notCar or cp.dashcamOnly or cp.passive: + if cp is None or not cp.carFingerprint or cp.notCar or cp.dashcamOnly or cp.passive: return None - return (str(cp.carFingerprint), bool(cp.openpilotLongitudinalControl or configuration_longitudinal), bool(cp.pcmCruise and not configuration_longitudinal), + longitudinal = bool(cp.openpilotLongitudinalControl or configuration_longitudinal) + if not longitudinal and not slc_configurable(cp, params): + return None + return (str(cp.carFingerprint), longitudinal, bool(cp.pcmCruise and not configuration_longitudinal), bool(cp.notCar), bool(cp.dashcamOnly), bool(cp.passive)) except (AttributeError, TypeError, ValueError): return None @@ -84,7 +87,7 @@ class SlcOffsetOwner: self.configuration_longitudinal = configuration_longitudinal def capability(self) -> tuple | None: - return _capability(self.vehicle_params(), self.configuration_longitudinal()) + return _capability(self.vehicle_params(), self.configuration_longitudinal(), params=self.params) def _raw(self, key: str) -> bytes | None: return read_saved(self.params, key, od.MAX_DOCUMENT_BYTES)[0] diff --git a/openpilot/starpilot/ui/sounds_owner.py b/openpilot/starpilot/ui/sounds_owner.py index ceb5987b8b..8a48915ad5 100644 --- a/openpilot/starpilot/ui/sounds_owner.py +++ b/openpilot/starpilot/ui/sounds_owner.py @@ -61,16 +61,21 @@ class SoundsOwner: rows.append(FeatureRow(AUTO_PREFIX + key, "Use Auto " + label, "Follow ambient sound", source=saved.raw, available=parked and saved.readable, repair_value="Auto")) rows.append(pack_row) + without_lateral_raw, without_lateral_readable = read_saved(self.params, BLINDSPOT_KEYS[1], 8) + without_lateral_on = without_lateral_readable and without_lateral_raw == b"1" for key, label, reason in (*DEPARTURE_TOGGLES, (BLINDSPOT_KEYS[0], "Loud Blindspot Alert", "Uses the soft-warning sound when a lane change is blocked by a detected blind-spot vehicle."), (BLINDSPOT_KEYS[1], "Blindspot Alert While Lateral Is Off", "Warns when signaling toward a detected blind-spot vehicle with steering assistance off or paused. " + "Independent of Loud Blindspot Alert. Hazards do not trigger it."), + (BLINDSPOT_KEYS[2], "Mute Blindspot Alert at Standstill", + "Mutes Blindspot Alert While Lateral Is Off when stopped or moving below 1 mph."), ): raw, readable = read_saved(self.params, key, 8) valid = readable and raw in (None, b"0", b"1") + row_available = parked and valid and (without_lateral_on if key == BLINDSPOT_KEYS[2] else True) rows.append(FeatureRow(key, label, ("On" if raw == b"1" else "Off") if valid else "Invalid saved value", - raw, ("Off", "On") if valid else (), available=parked and valid, + raw, ("Off", "On") if valid else (), available=row_available, reason=reason, default_value="Off")) defaults = dict.fromkeys(SPECS, 'Auto') defaults['SoundPack'] = PACK_LABELS.get(DEFAULT_PACK, DEFAULT_PACK) @@ -83,6 +88,10 @@ class SoundsOwner: if request.key in (*BLINDSPOT_KEYS, *DEPARTURE_KEYS): if request.value not in ("Off", "On") or request.expected not in (None, b"0", b"1"): return False + if request.key == BLINDSPOT_KEYS[2] and request.value == "On": + without_raw, without_readable = read_saved(self.params, BLINDSPOT_KEYS[1], 8) + if not (without_readable and without_raw == b"1"): + return False result = commit_exact(self.params, key=request.key, max_bytes=8, raw=b"1" if request.value == "On" else b"0", expected=request.expected, authorized=self.parked, temp_prefix=".optional-alert-") diff --git a/openpilot/starpilot/ui/tests/test_camera_client_cache.py b/openpilot/starpilot/ui/tests/test_camera_client_cache.py index 1f53c8f1e2..295fcb9358 100644 --- a/openpilot/starpilot/ui/tests/test_camera_client_cache.py +++ b/openpilot/starpilot/ui/tests/test_camera_client_cache.py @@ -1,4 +1,9 @@ +from types import SimpleNamespace from unittest.mock import Mock, patch + +import pytest + +from openpilot.selfdrive.ui.mici.onroad import cameraview as compact from openpilot.selfdrive.ui.onroad import cameraview as camera @@ -41,3 +46,66 @@ def test_new_drive_drains_cached_clients_and_cancels_pending_switch(): assert view._target_stream_type is None and not view._switching for client in view._clients.values(): client.recv.assert_called_once_with(timeout_ms=0) + + +@pytest.mark.parametrize('camera_type', [camera.CameraView, compact.CameraView]) +def test_failed_egl_camera_startup_uses_padded_nv12_texture_uploads(camera_type): + class View(camera_type): + def close(self): + pass + + with patch.object(camera, 'COMMA_HARDWARE', True), \ + patch.object(camera, 'init_egl', return_value=False), \ + patch.object(camera, 'VisionIpcClient', side_effect=lambda *a, **k: Mock(width=4, stride=8, height=2)), \ + patch.object(compact, 'VisionIpcClient', side_effect=lambda *a, **k: Mock(width=4, stride=8, height=2)), \ + patch.object(camera.rl, 'load_shader_from_memory', return_value=Mock(id=1)) as shader, \ + patch.object(camera.rl, 'get_shader_location', return_value=1), \ + patch.object(camera.ui_state, 'add_offroad_transition_callback'): + view = View('camera-fallback-test', camera.VisionStreamType.VISION_STREAM_NARROW_ROAD) + assert not view._use_egl + assert 'sampler2D texture1' in shader.call_args.args[1] + + y = SimpleNamespace(width=8, height=2, id=1) + uv = SimpleNamespace(width=4, height=1, id=2) + data = memoryview(bytes(range(40))) + with patch.object(camera.rl, 'load_texture_from_image', side_effect=[y, uv]): + view._initialize_textures() + view.frame = SimpleNamespace(uv_offset=24, data=data) + with patch.object(camera.rl, 'update_texture') as upload, \ + patch.object(camera.rl, 'begin_shader_mode'), patch.object(camera.rl, 'end_shader_mode'), \ + patch.object(camera.rl, 'set_shader_value_texture'), patch.object(camera.rl, 'draw_texture_pro') as draw, \ + patch.object(view, '_update_texture_color_filtering'): + view._render_textures(Mock(), Mock()) + assert upload.call_args_list[0].args == (y, data[:16]) + assert upload.call_args_list[1].args == (uv, data[24:32]) + draw.assert_called_once() + + upload.reset_mock() + draw.reset_mock() + view._texture_needs_update = True + view.frame = SimpleNamespace(uv_offset=24, data=data[:31]) + view._render_textures(Mock(), Mock()) + upload.assert_not_called() + draw.assert_not_called() + + +@pytest.mark.parametrize('camera_type', [camera.CameraView, compact.CameraView]) +def test_successful_egl_keeps_external_texture_shader(camera_type): + class View(camera_type): + def close(self): + pass + + placeholder = Mock(id=2) + with patch.object(camera, 'COMMA_HARDWARE', True), \ + patch.object(camera, 'init_egl', return_value=True), \ + patch.object(camera, 'VisionIpcClient', return_value=Mock()), \ + patch.object(compact, 'VisionIpcClient', return_value=Mock()), \ + patch.object(camera.rl, 'load_shader_from_memory', return_value=Mock(id=1)) as shader, \ + patch.object(camera.rl, 'get_shader_location', return_value=1), \ + patch.object(camera.rl, 'gen_image_color'), \ + patch.object(camera.rl, 'unload_image'), \ + patch.object(camera.rl, 'load_texture_from_image', return_value=placeholder), \ + patch.object(camera.ui_state, 'add_offroad_transition_callback'): + view = View('camera-egl-test', camera.VisionStreamType.VISION_STREAM_NARROW_ROAD) + assert view._use_egl and view.egl_texture is placeholder + assert 'samplerExternalOES texture0' in shader.call_args.args[1] diff --git a/openpilot/starpilot/ui/tests/test_controller_feature.py b/openpilot/starpilot/ui/tests/test_controller_feature.py index 251185a8d1..178c8c0140 100644 --- a/openpilot/starpilot/ui/tests/test_controller_feature.py +++ b/openpilot/starpilot/ui/tests/test_controller_feature.py @@ -85,11 +85,12 @@ class TestControllerFeature(unittest.TestCase): self.assertIsNone(self.params.get('ForceAutoTuneOff')) self.assertIsNone(self.params.get(DOCUMENT_KEY)) - def test_stock_pid_keeps_learning_preference_without_exposing_a_toggle(self): + def test_stock_pid_exposes_controller_choice_without_mutating_cp(self): self.cp = interfaces[HONDA.HONDA_CIVIC].get_non_essential_params(HONDA.HONDA_CIVIC) self.assertEqual(self.cp.lateralTuning.which(), 'pid') original = self.cp.as_reader().as_builder().to_bytes() - self.assertIsNone(self.row()) # No torque-only controller/manual editor. + self.assertEqual(self.require_row().choices, ('Stock Controller', 'Torque Controller', 'StarPilot Controller')) + self.assertEqual(self.require_row().value, 'Stock Controller') self.assertIsNone(self.row('ForceAutoTuneOff')) self.assertTrue(read_preference(self.params, self.cp).enabled) self.assertIsNone(self.params.get('ForceAutoTuneOff')) diff --git a/openpilot/starpilot/ui/tests/test_onroad_axes.py b/openpilot/starpilot/ui/tests/test_onroad_axes.py index 8bf82ba0a4..720fa63dd8 100644 --- a/openpilot/starpilot/ui/tests/test_onroad_axes.py +++ b/openpilot/starpilot/ui/tests/test_onroad_axes.py @@ -99,6 +99,37 @@ class TestOnroadAxes(unittest.TestCase): self.publish_latch(False) self.assertFalse(self.state(False, False).aol_armed_at_stop) + def test_legacy_2025_armed_stop_covers_creep_threshold_and_manumatic(self): + self.ui.aol_runtime = True + self.ui.CP.brand = 'subaru' + self.ui.CP.carFingerprint = 'SUBARU_LEGACY_2025' + self.ui.CP.minSteerSpeed = 0.0 + car = self.ui.sm['carState'] + car.steerFaultTemporary = car.steerFaultPermanent = car.accFaulted = False + self.publish_latch() + for gear in ('drive', 'manumatic'): + car.gearShifter = gear + car.standstill = False + for speed, expected_stop in ((0.0, True), (0.2, True), (0.3, True), (0.35, False)): + car.vEgo = speed + with self.subTest(gear=gear, speed=speed): + st = self.state(False, False) + self.assertEqual(st.aol_armed_at_stop, expected_stop) + expected_color = (10, 100, 98, 255) if expected_stop else (18, 40, 57, 255) + self.assertEqual(rgba(axis_status_color(st)), expected_color) + + self.ui.CP.carFingerprint = 'SUBARU_OUTBACK_2023' + for gear, standstill, speed, expected_stop in ( + ('drive', False, 0.2, False), + ('manumatic', True, 0.0, False), + ('drive', True, 0.0, True), + ): + car.gearShifter = gear + car.standstill = standstill + car.vEgo = speed + with self.subTest(car='SUBARU_OUTBACK_2023', gear=gear, standstill=standstill, speed=speed): + self.assertEqual(self.state(False, False).aol_armed_at_stop, expected_stop) + def test_missing_model_cannot_show_armed_aol_as_active_steering(self): self.ui.aol_runtime = True self.publish_latch() diff --git a/openpilot/starpilot/ui/tests/test_sounds_settings.py b/openpilot/starpilot/ui/tests/test_sounds_settings.py index 53a14640b8..5d71628295 100644 --- a/openpilot/starpilot/ui/tests/test_sounds_settings.py +++ b/openpilot/starpilot/ui/tests/test_sounds_settings.py @@ -49,7 +49,7 @@ class SoundsSettingsTests(unittest.TestCase): def test_absence_auto_no_writes_and_native_registry(self): state = self.owner.snapshot() - self.assertEqual(len(state.rows), 12) + self.assertEqual(len(state.rows), 13) for key, _, _ in VOLUMES: self.assertEqual(self.row(key).value, "Auto") self.assertEqual((self.row(key).step, self.row(key).maximum, self.row(key).unit), (5.0, 100.0, "%")) @@ -264,7 +264,7 @@ class SoundsSettingsTests(unittest.TestCase): session.sounds_scroll = 5 state = replace(session.sounds_snapshot(), scroll=5) self.assertEqual(state.page, "sounds:overview") - self.assertEqual(len(state.rows), 12) + self.assertEqual(len(state.rows), 13) self.assertTrue(all(value_buttons(state, row) == () for row in state.rows)) self.assertEqual(next(row for row in state.rows if row.key == "EngageVolume").value, "40") received = [] diff --git a/openpilot/starpilot/vehicle_preferences.py b/openpilot/starpilot/vehicle_preferences.py index 0c9cf32a51..63b84d5ceb 100644 --- a/openpilot/starpilot/vehicle_preferences.py +++ b/openpilot/starpilot/vehicle_preferences.py @@ -19,6 +19,7 @@ def bolt_disable_supported(cp) -> bool: @dataclass(frozen=True) class VehicleStartupPreferences: + controller_selection: bytes | None = field(default=None, kw_only=True) toyota_auto_hold: bool = False toyota_sng: bool = field(default=False, kw_only=True) jeep_brake_hold: bool = field(default=False, kw_only=True) @@ -58,6 +59,10 @@ class VehicleStartupPreferences: from openpilot.starpilot.car.tesla.radar_settings import read_radar_settings from openpilot.starpilot.car.tesla.pedal_preferences import read_pedal_settings from openpilot.starpilot.car.ford.bluepilot import startup_params as ford_bluepilot + from openpilot.starpilot.lateral.controller_selection import DOCUMENT_KEY, MAX_DOCUMENT_BYTES + controller_selection, readable_selection = read_saved(params, DOCUMENT_KEY, MAX_DOCUMENT_BYTES) + if not enabled or not readable_selection: + controller_selection = None smoothing = read_snapshot(params, enabled=enabled) radar = read_radar_settings(params) pedal = read_pedal_settings(params) @@ -87,7 +92,7 @@ class VehicleStartupPreferences: volt_one_pedal = bool(enabled and not disable_bolt and read_saved(params, "VoltOnePedalMode", 8) == (b"1", True) and readable and safe in (None, b"0")) except (OSError, TypeError, ValueError): - return cls(vw_stock_long=vw_stock_long, + return cls(controller_selection=controller_selection, vw_stock_long=vw_stock_long, subaru_smoothing=smoothing, disable_bolt_long=disable_bolt, honda_bosch_a_radar=honda_radar, tesla_preap_stock=preap_stock, tesla_preap_radar=radar, tesla_preap_pedal=pedal, gm_camera_pedal=False, toyota_filter=False) @@ -107,7 +112,7 @@ class VehicleStartupPreferences: cooperative = bool(enabled and readable and safe in (None, b"0") and read_saved(params, "TeslaCoopSteering", 8) == (b"1", True)) screen_brake = read_saved(params, 'TeslaAOLDisengageOnBrake', 8) == (b'1', True) - return cls(vw_stock_long=vw_stock_long, + return cls(controller_selection=controller_selection, vw_stock_long=vw_stock_long, subaru_smoothing=smoothing, subaru_avh_startup=bool(enabled and readable and safe in (None, b"0") and read_saved(params, "IsReleaseBranch", 8) in ((None, True), (b"0", True)) and read_saved(params, "SubaruAvhStartup", 8) == (b"1", True)), @@ -233,7 +238,8 @@ class VehicleStartupPreferences: configure_radar(cp) from opendbc.bluepilot_lateral.hosts.starpilot.safety_param import init_ford_safety_param_starpilot init_ford_safety_param_starpilot(cp, dict(self.ford_bluepilot)) - return cp + from openpilot.starpilot.lateral.controller_selection import prepare_controller + return prepare_controller(cp, self.controller_selection) def finalize(self, cp) -> None: from opendbc.car.volkswagen.meb_modes import prepare_stock as prepare_meb_stock diff --git a/openpilot/system/updated/tests/test_retained_agnos.py b/openpilot/system/updated/tests/test_retained_agnos.py index 1043442e62..aa24a10531 100644 --- a/openpilot/system/updated/tests/test_retained_agnos.py +++ b/openpilot/system/updated/tests/test_retained_agnos.py @@ -195,7 +195,10 @@ class TestRetainedAgnos(unittest.TestCase): def test_legacy_staging_defers_to_the_new_hardware_aware_launcher(self): source = (ROOT / 'launch_env.sh').read_text() - for version in ('19.8.1', '19.8.2', '20.2.1', '20.5.2', '20.5.3'): + match = re.search(r'^ export AGNOS_VERSION="([^"]+)"$', source, re.MULTILINE) + assert match is not None + target = match[1] + for version in dict.fromkeys(('19.8.1', '19.8.2', '20.2.1', '20.5.2', '20.5.3', target)): with self.subTest(version=version): installed = self.root / 'VERSION' installed.write_text(version + '\n') @@ -205,8 +208,8 @@ class TestRetainedAgnos(unittest.TestCase): f'source {shlex.quote(str(environment))}\n' + \ 'printf "%s\\n%s\\n%s\\n" "$AGNOS_VERSION" "$AGNOS_ACCEPTED_VERSIONS" "$AGNOS_UPDATE_POLICY"' required, accepted, policy = subprocess.check_output(['bash', '-c', script], text=True).splitlines() - self.assertIn(version, accepted.split()) - self.assertEqual(required, '20.5.3') + self.assertEqual(accepted.split(), [target, version]) + self.assertEqual(required, target) self.assertEqual(policy, 'auto') def test_runtime_still_requires_upgrade_when_legacy_staging_accepts_old_os(self): diff --git a/panda/board/obj/body_h7.bin.signed b/panda/board/obj/body_h7.bin.signed index b8f4484e8b..1011b9709f 100644 Binary files a/panda/board/obj/body_h7.bin.signed and b/panda/board/obj/body_h7.bin.signed differ diff --git a/panda/board/obj/bootstub.body_h7.bin b/panda/board/obj/bootstub.body_h7.bin index b9afe7f633..184a014989 100644 Binary files a/panda/board/obj/bootstub.body_h7.bin and b/panda/board/obj/bootstub.body_h7.bin differ diff --git a/panda/board/obj/bootstub.panda.bin b/panda/board/obj/bootstub.panda.bin index 72995e5c0f..f2164c54aa 100644 Binary files a/panda/board/obj/bootstub.panda.bin and b/panda/board/obj/bootstub.panda.bin differ diff --git a/panda/board/obj/bootstub.panda_can_ignition_only.bin b/panda/board/obj/bootstub.panda_can_ignition_only.bin index 72995e5c0f..f2164c54aa 100644 Binary files a/panda/board/obj/bootstub.panda_can_ignition_only.bin and b/panda/board/obj/bootstub.panda_can_ignition_only.bin differ diff --git a/panda/board/obj/bootstub.panda_h7.bin b/panda/board/obj/bootstub.panda_h7.bin index 228fcaf4ee..ce5e51a65c 100644 Binary files a/panda/board/obj/bootstub.panda_h7.bin and b/panda/board/obj/bootstub.panda_h7.bin differ diff --git a/panda/board/obj/bootstub.panda_h7_can_ignition_only.bin b/panda/board/obj/bootstub.panda_h7_can_ignition_only.bin index 228fcaf4ee..ce5e51a65c 100644 Binary files a/panda/board/obj/bootstub.panda_h7_can_ignition_only.bin and b/panda/board/obj/bootstub.panda_h7_can_ignition_only.bin differ diff --git a/panda/board/obj/bootstub.panda_h7_hkg_remote.bin b/panda/board/obj/bootstub.panda_h7_hkg_remote.bin index 228fcaf4ee..ce5e51a65c 100644 Binary files a/panda/board/obj/bootstub.panda_h7_hkg_remote.bin and b/panda/board/obj/bootstub.panda_h7_hkg_remote.bin differ diff --git a/panda/board/obj/bootstub.panda_h7_hkg_remote_can_ignition_only.bin b/panda/board/obj/bootstub.panda_h7_hkg_remote_can_ignition_only.bin index 228fcaf4ee..ce5e51a65c 100644 Binary files a/panda/board/obj/bootstub.panda_h7_hkg_remote_can_ignition_only.bin and b/panda/board/obj/bootstub.panda_h7_hkg_remote_can_ignition_only.bin differ diff --git a/panda/board/obj/bootstub.panda_h7_remote.bin b/panda/board/obj/bootstub.panda_h7_remote.bin index 228fcaf4ee..ce5e51a65c 100644 Binary files a/panda/board/obj/bootstub.panda_h7_remote.bin and b/panda/board/obj/bootstub.panda_h7_remote.bin differ diff --git a/panda/board/obj/bootstub.panda_h7_remote_can_ignition_only.bin b/panda/board/obj/bootstub.panda_h7_remote_can_ignition_only.bin index 228fcaf4ee..ce5e51a65c 100644 Binary files a/panda/board/obj/bootstub.panda_h7_remote_can_ignition_only.bin and b/panda/board/obj/bootstub.panda_h7_remote_can_ignition_only.bin differ diff --git a/panda/board/obj/bootstub.panda_h7_tesla_wake.bin b/panda/board/obj/bootstub.panda_h7_tesla_wake.bin index 228fcaf4ee..ce5e51a65c 100644 Binary files a/panda/board/obj/bootstub.panda_h7_tesla_wake.bin and b/panda/board/obj/bootstub.panda_h7_tesla_wake.bin differ diff --git a/panda/board/obj/bootstub.panda_h7_tesla_wake_can_ignition_only.bin b/panda/board/obj/bootstub.panda_h7_tesla_wake_can_ignition_only.bin index 228fcaf4ee..ce5e51a65c 100644 Binary files a/panda/board/obj/bootstub.panda_h7_tesla_wake_can_ignition_only.bin and b/panda/board/obj/bootstub.panda_h7_tesla_wake_can_ignition_only.bin differ diff --git a/panda/board/obj/bootstub.panda_hkg_remote.bin b/panda/board/obj/bootstub.panda_hkg_remote.bin index 72995e5c0f..f2164c54aa 100644 Binary files a/panda/board/obj/bootstub.panda_hkg_remote.bin and b/panda/board/obj/bootstub.panda_hkg_remote.bin differ diff --git a/panda/board/obj/bootstub.panda_hkg_remote_can_ignition_only.bin b/panda/board/obj/bootstub.panda_hkg_remote_can_ignition_only.bin index 72995e5c0f..f2164c54aa 100644 Binary files a/panda/board/obj/bootstub.panda_hkg_remote_can_ignition_only.bin and b/panda/board/obj/bootstub.panda_hkg_remote_can_ignition_only.bin differ diff --git a/panda/board/obj/bootstub.panda_remote.bin b/panda/board/obj/bootstub.panda_remote.bin index 72995e5c0f..f2164c54aa 100644 Binary files a/panda/board/obj/bootstub.panda_remote.bin and b/panda/board/obj/bootstub.panda_remote.bin differ diff --git a/panda/board/obj/bootstub.panda_remote_can_ignition_only.bin b/panda/board/obj/bootstub.panda_remote_can_ignition_only.bin index 72995e5c0f..f2164c54aa 100644 Binary files a/panda/board/obj/bootstub.panda_remote_can_ignition_only.bin and b/panda/board/obj/bootstub.panda_remote_can_ignition_only.bin differ diff --git a/panda/board/obj/bootstub.panda_tesla_wake.bin b/panda/board/obj/bootstub.panda_tesla_wake.bin index 72995e5c0f..f2164c54aa 100644 Binary files a/panda/board/obj/bootstub.panda_tesla_wake.bin and b/panda/board/obj/bootstub.panda_tesla_wake.bin differ diff --git a/panda/board/obj/bootstub.panda_tesla_wake_can_ignition_only.bin b/panda/board/obj/bootstub.panda_tesla_wake_can_ignition_only.bin index 72995e5c0f..f2164c54aa 100644 Binary files a/panda/board/obj/bootstub.panda_tesla_wake_can_ignition_only.bin and b/panda/board/obj/bootstub.panda_tesla_wake_can_ignition_only.bin differ diff --git a/panda/board/obj/gitversion.h b/panda/board/obj/gitversion.h index 22c5b32799..ebfd8812bf 100644 --- a/panda/board/obj/gitversion.h +++ b/panda/board/obj/gitversion.h @@ -1,4 +1,4 @@ #pragma once extern const uint8_t gitversion[29]; -const uint8_t gitversion[29] = "DEV-d9e877d0-Pf38f504f-DEBUG"; +const uint8_t gitversion[29] = "DEV-d4fac919-Pf38f504f-DEBUG"; diff --git a/panda/board/obj/panda.bin.signed b/panda/board/obj/panda.bin.signed index ae67ef0f42..4865942360 100644 Binary files a/panda/board/obj/panda.bin.signed and b/panda/board/obj/panda.bin.signed differ diff --git a/panda/board/obj/panda_can_ignition_only.bin.signed b/panda/board/obj/panda_can_ignition_only.bin.signed index a2aff1154d..100120cb7b 100644 Binary files a/panda/board/obj/panda_can_ignition_only.bin.signed and b/panda/board/obj/panda_can_ignition_only.bin.signed differ diff --git a/panda/board/obj/panda_h7.bin.signed b/panda/board/obj/panda_h7.bin.signed index 59bde55671..b2fa209828 100644 Binary files a/panda/board/obj/panda_h7.bin.signed and b/panda/board/obj/panda_h7.bin.signed differ diff --git a/panda/board/obj/panda_h7_can_ignition_only.bin.signed b/panda/board/obj/panda_h7_can_ignition_only.bin.signed index ad5b652453..c30676af69 100644 Binary files a/panda/board/obj/panda_h7_can_ignition_only.bin.signed and b/panda/board/obj/panda_h7_can_ignition_only.bin.signed differ diff --git a/panda/board/obj/panda_h7_hkg_remote.bin.signed b/panda/board/obj/panda_h7_hkg_remote.bin.signed index 1fd43807b6..b38172eee0 100644 Binary files a/panda/board/obj/panda_h7_hkg_remote.bin.signed and b/panda/board/obj/panda_h7_hkg_remote.bin.signed differ diff --git a/panda/board/obj/panda_h7_hkg_remote_can_ignition_only.bin.signed b/panda/board/obj/panda_h7_hkg_remote_can_ignition_only.bin.signed index 410976293f..35c4379db3 100644 Binary files a/panda/board/obj/panda_h7_hkg_remote_can_ignition_only.bin.signed and b/panda/board/obj/panda_h7_hkg_remote_can_ignition_only.bin.signed differ diff --git a/panda/board/obj/panda_h7_remote.bin.signed b/panda/board/obj/panda_h7_remote.bin.signed index 904fa2f857..4e8c44a933 100644 Binary files a/panda/board/obj/panda_h7_remote.bin.signed and b/panda/board/obj/panda_h7_remote.bin.signed differ diff --git a/panda/board/obj/panda_h7_remote_can_ignition_only.bin.signed b/panda/board/obj/panda_h7_remote_can_ignition_only.bin.signed index cd72521f5c..707172ebf6 100644 Binary files a/panda/board/obj/panda_h7_remote_can_ignition_only.bin.signed and b/panda/board/obj/panda_h7_remote_can_ignition_only.bin.signed differ diff --git a/panda/board/obj/panda_h7_tesla_wake.bin.signed b/panda/board/obj/panda_h7_tesla_wake.bin.signed index c8a0f6f8f9..7a4652f4a2 100644 Binary files a/panda/board/obj/panda_h7_tesla_wake.bin.signed and b/panda/board/obj/panda_h7_tesla_wake.bin.signed differ diff --git a/panda/board/obj/panda_h7_tesla_wake_can_ignition_only.bin.signed b/panda/board/obj/panda_h7_tesla_wake_can_ignition_only.bin.signed index 5792af0565..4ee60909e7 100644 Binary files a/panda/board/obj/panda_h7_tesla_wake_can_ignition_only.bin.signed and b/panda/board/obj/panda_h7_tesla_wake_can_ignition_only.bin.signed differ diff --git a/panda/board/obj/panda_hkg_remote.bin.signed b/panda/board/obj/panda_hkg_remote.bin.signed index 9e3182bdce..e1ebb1dcce 100644 Binary files a/panda/board/obj/panda_hkg_remote.bin.signed and b/panda/board/obj/panda_hkg_remote.bin.signed differ diff --git a/panda/board/obj/panda_hkg_remote_can_ignition_only.bin.signed b/panda/board/obj/panda_hkg_remote_can_ignition_only.bin.signed index fa6bf46e80..632dee65ae 100644 Binary files a/panda/board/obj/panda_hkg_remote_can_ignition_only.bin.signed and b/panda/board/obj/panda_hkg_remote_can_ignition_only.bin.signed differ diff --git a/panda/board/obj/panda_remote.bin.signed b/panda/board/obj/panda_remote.bin.signed index d7ed53e887..a96b9d619c 100644 Binary files a/panda/board/obj/panda_remote.bin.signed and b/panda/board/obj/panda_remote.bin.signed differ diff --git a/panda/board/obj/panda_remote_can_ignition_only.bin.signed b/panda/board/obj/panda_remote_can_ignition_only.bin.signed index d0ecd37d23..c098a178e1 100644 Binary files a/panda/board/obj/panda_remote_can_ignition_only.bin.signed and b/panda/board/obj/panda_remote_can_ignition_only.bin.signed differ diff --git a/panda/board/obj/panda_tesla_wake.bin.signed b/panda/board/obj/panda_tesla_wake.bin.signed index 1cc1bc863b..a14b15a830 100644 Binary files a/panda/board/obj/panda_tesla_wake.bin.signed and b/panda/board/obj/panda_tesla_wake.bin.signed differ diff --git a/panda/board/obj/panda_tesla_wake_can_ignition_only.bin.signed b/panda/board/obj/panda_tesla_wake_can_ignition_only.bin.signed index 72f8c9ed7f..8744b906fa 100644 Binary files a/panda/board/obj/panda_tesla_wake_can_ignition_only.bin.signed and b/panda/board/obj/panda_tesla_wake_can_ignition_only.bin.signed differ diff --git a/panda/board/obj/version b/panda/board/obj/version index de421c1b76..6b509e10f8 100644 --- a/panda/board/obj/version +++ b/panda/board/obj/version @@ -1 +1 @@ -DEV-d9e877d0-Pf38f504f-DEBUG \ No newline at end of file +DEV-d4fac919-Pf38f504f-DEBUG \ No newline at end of file diff --git a/panda/tests/libpanda/libpanda.so b/panda/tests/libpanda/libpanda.so index e1629b44ce..53f41e44c2 100755 Binary files a/panda/tests/libpanda/libpanda.so and b/panda/tests/libpanda/libpanda.so differ diff --git a/prebuilt.json b/prebuilt.json index 2bf0dc536a..a750169d8e 100644 --- a/prebuilt.json +++ b/prebuilt.json @@ -1 +1 @@ -{"protected_inventory_sha256": "9dcc7363e6266ae6f2ecee245ef0e7898a5882d43288e8d1b9659633beb512ee", "schema_version": 1} +{"protected_inventory_sha256": "419f51cf6ff8059afd08687934fab81df5eec165f7550aa56ffd5359dc194b2e", "schema_version": 1} diff --git a/tools/ci/run_vehicle_tests.py b/tools/ci/run_vehicle_tests.py index d9baaa8ff0..db476bddff 100644 --- a/tools/ci/run_vehicle_tests.py +++ b/tools/ci/run_vehicle_tests.py @@ -581,6 +581,7 @@ RELEASE_TARGETS = ( "opendbc_repo/opendbc/safety/tests/test_subaru_avh_startup.py", "opendbc_repo/opendbc/safety/tests/test_subaru_forester_angle.py", "opendbc_repo/opendbc/safety/tests/test_subaru_receive_guards.py", + "opendbc_repo/opendbc/safety/tests/test_subaru_preglobal_stock_acc.py", "opendbc_repo/opendbc/safety/tests/test_subaru_outback_angle.py", 'openpilot/starpilot/car/toyota/tests/test_matrix_stock_caller_native.py', 'opendbc_repo/opendbc/safety/tests/test_toyota_matrix_stock_aol.py',