mirror of
https://github.com/firestar5683/StarPilot.git
synced 2026-11-30 00:33:41 +08:00
Merge remote-tracking branch 'upstream/testing' into volvo-v60-eucd
This commit is contained in:
@@ -11,6 +11,7 @@ on:
|
||||
- testing
|
||||
- dev
|
||||
pull_request:
|
||||
types: [opened, synchronize, reopened, edited]
|
||||
workflow_dispatch:
|
||||
workflow_call:
|
||||
inputs:
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -4,6 +4,7 @@ on:
|
||||
push:
|
||||
branches: [master, Domathon, Dom, StarPilot, stable, testing, dev]
|
||||
pull_request:
|
||||
types: [opened, synchronize, reopened, edited]
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
|
||||
@@ -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
|
||||
|
||||
+1
-1
@@ -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.
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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):
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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()
|
||||
@@ -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
|
||||
|
||||
@@ -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):
|
||||
|
||||
@@ -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))
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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):
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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"])
|
||||
|
||||
|
||||
@@ -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}")
|
||||
|
||||
|
||||
@@ -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))
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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)
|
||||
|
||||
|
||||
@@ -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"))
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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()
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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: {}},
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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";
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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,
|
||||
};
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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)):
|
||||
|
||||
@@ -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)))
|
||||
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -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)
|
||||
@@ -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):
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -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"
|
||||
]
|
||||
}
|
||||
]
|
||||
|
||||
@@ -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"
|
||||
]
|
||||
}
|
||||
]
|
||||
|
||||
@@ -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")
|
||||
|
||||
|
||||
@@ -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']
|
||||
|
||||
@@ -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)
|
||||
|
||||
Binary file not shown.
Binary file not shown.
@@ -161,6 +161,7 @@ inline static std::unordered_map<std::string, ParamKeyAttributes> 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}"}},
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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')
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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())
|
||||
|
||||
@@ -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__":
|
||||
|
||||
@@ -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__":
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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
|
||||
@@ -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
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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))
|
||||
|
||||
@@ -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)
|
||||
@@ -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
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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())
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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')
|
||||
|
||||
@@ -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))
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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"))
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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):
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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)
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user