Compare commits

...

155 Commits

Author SHA1 Message Date
firestar5683 404ef33a96 Rebalance lifecycle CI using current hosted timings 2026-11-23 01:51:06 -06:00
firestar5683 e366cb0170 Make the Park-to-Drive audio test use a deterministic clock 2026-11-22 19:20:21 -06:00
firestar5683 81c66ef1ac Align camera, Ford and Mazda CI fixtures 2026-11-22 18:20:59 -06:00
firestar5683 645cca2086 Use real car state in the radar alert fixture 2026-11-22 17:24:29 -06:00
firestar5683 5ab912b3d4 Cover current Mazda admission in Switchback tests 2026-11-22 17:13:26 -06:00
firestar5683 1ffb6314f2 Pin the Bolt regen gear wire field in schema compatibility tests 2026-11-22 16:49:46 -06:00
firestar5683 791e9ee4ad Carry Bolt regen gear on the StarPilot car-state message 2026-11-22 16:40:27 -06:00
firestar5683 7da988976c Label Bolt L2 and L3 as regen gears in alerts 2026-11-22 16:26:18 -06:00
firestar5683 b94119ec3e Keep Honda Fit AOL independent of cruise minimum speed 2026-11-22 16:21:26 -06:00
firestar5683 cce15c82dc Restore executable mode on the process replay script 2026-11-22 16:10:52 -06:00
firestar5683 ede0735ffd Make replay startup alerts independent of the checkout channel 2026-11-22 16:08:09 -06:00
firestar5683 d98dfb489d Align unit fixtures with current alert and settings contracts 2026-11-22 15:47:31 -06:00
firestar5683 29b703d207 Restore executable mode and trim speed-limit help text 2026-11-22 15:20:16 -06:00
firestar5683 fce3f7d436 Keep HKG wheel AOL available with Alpha Long 2026-11-22 14:53:52 -06:00
firestar5683 a24192a582 Recover FLM reads after late status and unreadable endings 2026-11-22 14:51:16 -06:00
firestar5683 1f06ce685c Restore Niro EV AOL with camera-SCC Alpha Long 2026-11-22 14:49:21 -06:00
firestar5683 dda32b141c Maintain factory ACC Bolt brake demand until standstill 2026-11-22 14:27:25 -06:00
firestar5683 75757ab021 Set up Python for TrueNAS documentation checks 2026-11-22 14:15:32 -06:00
firestar5683 6da9182f6c Run testing documentation checks on TrueNAS 2026-11-22 14:14:29 -06:00
firestar5683 870bd63ff4 Refresh the prebuilt receipt after StarPort and speed limit updates 2026-11-22 14:10:32 -06:00
firestarsdog 2535ee3901 Make SLC follow the newest speed limit instead of switching sources on dropouts 2026-11-22 15:06:17 -05:00
dirwin31 6d4b357e1f Merge pull request #334 from dirwin31/FixHeadunitFix
StarPort: Add experimental phone services fix for 2018 Honda Fit
2026-11-22 11:48:55 -08:00
firestar5683 68ef096322 Damp highway curve steering on Ioniq 5 HDA II 2026-11-22 13:42:05 -06:00
firestar5683 d8439a094b Use standard startup reminder on official StarPilot channels 2026-11-22 13:39:18 -06:00
firestar5683 2a2594b697 Keep full-range GM ACC active below its entry speed 2026-11-22 13:34:47 -06:00
firestar5683 2223a9d371 Keep factory ACC Bolt braking below the cruise entry speed 2026-11-22 13:33:34 -06:00
firestar5683 b25bbb8c78 Allow low-speed steering on verified Mazda CX-5 EPS swap 2026-11-22 13:32:39 -06:00
leomonde 16806d8a93 Integrate Volvo V60 (EUCD) support 2026-11-22 13:28:17 -06:00
firestar5683 ae4df1725c Show the Low gear requirement on early Bolt pedal profiles 2026-11-22 13:23:41 -06:00
firestar5683 f2c632ef11 Update Mazda, GM and Auto Learn regression fixtures 2026-11-22 13:13:18 -06:00
Danny ea17311f8c StarPort: Add experimental phone services fix for 2018 Honda Fit 2026-11-22 11:13:08 -08:00
firestar5683 a3c73c70e5 Keep legacy Mazda discovery on normal CAN wiring 2026-11-22 12:54:46 -06:00
leomonde 5fbcdffece Merge remote-tracking branch 'upstream/testing' into volvo-v60-eucd 2026-11-22 15:45:18 -03:00
firestar5683 972dd457c5 Restore stock cruise engagement and AOL on legacy Mazda CX-5 2026-11-22 12:15:53 -06:00
firestar5683 19122ea4e2 Report FLM verification and parked interruptions clearly 2026-11-22 11:55:14 -06:00
firestar5683 46c17cc1aa Keep exact Honda Nidec discovery on bus zero 2026-11-22 11:54:12 -06:00
firestar5683 d3f179e766 Update testing to verified AGNOS 20.5.5 2026-11-22 11:53:18 -06:00
firestar5683 cd65e68b60 Discover Honda Fit firmware on normal CAN bus 2026-11-22 11:48:58 -06:00
firestar5683 31f8918db7 Roll Testing back to AGNOS 20.5.3 2026-11-22 11:08:18 -06:00
firestar5683 e4f363003b Fix disabled Alpha Long startup and busy Bluetooth recovery 2026-11-22 10:57:08 -06:00
firestar5683 f36af88b54 Skip torque-only parked review for non-torque steering 2026-11-22 10:52:19 -06:00
firestar5683 ec59d25227 Keep the UI running when camera EGL import is unavailable 2026-11-22 10:49:07 -06:00
firestar5683 8687966c6d Extract Card native AOL handler selection 2026-11-22 10:42:10 -06:00
firestar5683 91683efbf6 Restore the two Firestar AGNOS mirrors 2026-11-22 01:06:38 -06:00
firestar5683 73e593514d Verify AGNOS mirror fallback and cruise initialization order 2026-11-22 00:19:10 -06:00
firestar5683 549a28fa9f Fix AGNOS staging expectations and restore source size limits 2026-11-21 23:54:09 -06:00
firestar5683 ea704cb66d Match fresh speed limits on Redneck Cruise SET 2026-11-21 23:45:33 -06:00
Frogger900 fd9cd41a68 Package Frogger900’s 2025 Subaru Legacy port 2026-11-21 23:44:15 -06:00
Frogger900 d4fac91919 Integrate Frogger900’s 2025 Subaru Legacy port 2026-11-21 23:39:18 -06:00
firestar5683 80c21b10dc Read current radar lead state in Redneck Cruise 2026-11-21 23:12:13 -06:00
firestar5683 50e0e7241a Update testing to verified AGNOS 20.5.4 2026-11-21 23:10:13 -06:00
firestar5683 d7f509b98a Enable speed limit settings for Redneck Cruise 2026-11-21 22:10:05 -06:00
firestar5683 5561759a77 Verify the Highlander sDSU engagement floor in factory tests 2026-11-22 03:35:21 +00:00
firestar5683 3e34e48f91 Separate FLM tracking tests from release receipt validation 2026-11-21 21:07:10 -06:00
firestar5683 cf1ecc9aff Verify Highlander lateral permission through braking 2026-11-21 21:03:55 -06:00
firestar5683 9f954d2909 Exercise Highlander low-speed lateral checks with stock ACC 2026-11-21 20:47:35 -06:00
firestar5683 c8abbd740b Allow low-speed engagement on Highlander with supported sDSU 2026-11-21 20:36:20 -06:00
firestar5683 1f0455554b Cover Outback release safety configuration rejection 2026-11-21 20:31:54 -06:00
firestar5683 730713bb89 Enable stock cruise steering on the 2015–17 Subaru Outback 2026-11-21 20:23:31 -06:00
firestar5683 85a2f5b786 Enable stock cruise steering on the 2015–17 Subaru Outback 2026-11-21 20:18:49 -06:00
firestar5683 b739b32844 Allow reported CAN2 diagnostics on stock CAN-FD Hondas 2026-11-21 20:15:20 -06:00
firestar5683 403c79eaff Align steering controller regression fixtures 2026-11-21 19:49:04 -06:00
firestar5683 87a57e5359 Expose calibrated steering controller choices in developer parameters 2026-11-21 19:26:35 -06:00
firestar5683 4603d87068 Align Panda and AGNOS tests with current firmware checks 2026-11-21 18:14:06 -06:00
firestar5683 0db704125d Prefer Dropbox for AGNOS downloads 2026-11-21 17:14:02 -06:00
firestar5683 0c57d72897 Update AGNOS test fixtures for mirror downloads 2026-11-21 17:07:58 -06:00
firestar5683 2cf77aa2de Use AGNOS mirrors for download failover 2026-11-21 17:04:58 -06:00
firestar5683 19a135ff10 Keep Trax braking below the cruise engagement speed 2026-11-21 16:50:07 -06:00
firestar5683 08c2199599 Build Panda firmware for MQB HUD ownership 2026-11-21 16:31:45 -06:00
firestar5683 122a248050 Give the MQB cluster one lane assist HUD source 2026-11-21 16:28:47 -06:00
firestar5683 c67b1c074a Recover incompatible internal Panda bootstubs 2026-11-21 16:22:30 -06:00
Frogger900 d91e913953 subaru: fix subaru_avh_count MISRA width and Legacy 2025 startup dash test assertions 2026-11-21 17:11:53 -05:00
firestar5683 d907949650 Preserve internal Panda identity across recovery reset 2026-11-21 16:06:07 -06:00
leomonde 6738edad1a Keep the V60 out of the shared CMA/V40 test fixtures 2026-11-21 18:50:22 -03:00
firestar5683 c1f7468fff Use normal diagnostic wiring for mixed CAN Palisade startup 2026-11-21 15:39:59 -06:00
leomonde ba10c64889 Fix fleet coverage count and wrap long line for the V60 2026-11-21 17:10:04 -03:00
firestar5683 6bf5e14704 Run full CI for Stable pull requests 2026-11-21 13:53:08 -06:00
firestar5683 b2e84e4a11 Model the C3 mount root in storage tests 2026-11-21 13:49:21 -06:00
leomonde ede83a74d1 Volvo V60 (EUCD): add platform 2026-11-21 16:37:28 -03:00
firestar5683 80aae010ee Allow legacy C3X Panda flash erase to complete 2026-11-21 13:14:17 -06:00
firestar5683 91a070023d Migrate legacy C3X Panda firmware during startup 2026-11-21 12:55:51 -06:00
firestar5683 28a6cf1133 Show mounted tici NVMe storage in Galaxy 2026-11-21 12:49:14 -06:00
firestar5683 ee7b5d66be Refresh prebuilt receipt after Polaris copy update 2026-11-21 12:27:50 -06:00
zikeji 058f28ed2f Merge pull request #331 from StarPilotHQ/polaris-about-text
Update the Polaris model info: not tied to RDFv4, link polaris.firestar.link
2026-11-21 13:25:36 -05:00
firestar5683 faef0b43ee Use real vehicle params in SLC settings tests 2026-11-21 12:24:34 -06:00
firestar5683 193835d88d Use real vehicle params in optional feature tests 2026-11-21 12:09:16 -06:00
firestar5683 4218e46640 Fix Hyundai safety and regression checks 2026-11-21 12:08:19 -06:00
Zikeji c0a70d3d87 Update the Polaris model info: not tied to RDFv4, link polaris.firestar.link 2026-11-21 12:59:28 -05:00
firestar5683 64e4411939 Restore Redneck Cruise for conventional cruise Hyundai profiles 2026-11-21 11:27:31 -06:00
firestar5683 f06dfafff0 Build matching Panda firmware for Gen2 Bolt pedal state 2026-11-21 11:20:41 -06:00
firestar5683 5bf72b4a2c Accept the Bolt Gen2 CC interceptor state 8 2026-11-21 11:18:20 -06:00
firestar5683 e9d7d1610f Add longitudinal developer tuning controls 2026-11-21 11:15:12 -06:00
firestar5683 e44319a142 Allow FLM analysis during Force Offroad 2026-11-21 11:07:14 -06:00
firestar5683 94473780e8 Fix Kona dash handover and wheel assignment display 2026-11-21 11:06:14 -06:00
Frogger900 cb3ebdd09e subaru: add 2025 Legacy AOL, angle control, HUD/DBC, AVH, twitch guard, and standstill BSM mute 2026-11-21 10:18:43 -05:00
firestarsdog 81dc63dac6 Torque Bar: Stop Fill Crossing Center 2026-11-21 03:53:16 -05:00
firestarsdog 448a673630 Modem: Disable SIM Detection on comma 3 to Fix Missing SIM 2026-11-21 03:19:21 -05:00
firestar5683 9d88359d20 Lead the testing README with StarPilot 7.0 features 2026-11-21 01:35:27 -06:00
firestar5683 8c0826a61f Wait for Volvo readiness publication in lifecycle tests 2026-11-21 01:16:48 -06:00
firestar5683 008b0cbcf1 Wait for Volvo readiness publication in lifecycle tests 2026-11-21 01:16:44 -06:00
firestar5683 8d487d0dc5 Preserve Mach-E stock ACC steering through bounded source waits 2026-11-21 00:38:31 -06:00
firestar5683 4241d07dc8 Set StarPilot testing version to 7.0.1 2026-11-21 00:38:06 -06:00
firestar5683 1faca4bed4 Invite PR authors to open a StarPilot Discord ticket 2026-11-20 23:42:08 -06:00
firestar5683 1aa4f9ce50 Verify manual Volkswagen reverse startup against its steering deadline 2026-11-20 21:31:10 -06:00
firestar5683 bd2dba096c Verify low-speed cruise refresh after a Card settings read failure 2026-11-20 21:31:10 -06:00
firestar5683 6d9b146eea Describe low-speed cruise start in Galaxy 2026-11-20 20:07:02 -06:00
firestar5683 ec9cd685b9 Add an optional vehicle-minimum cruise start 2026-11-20 19:55:08 -06:00
firestar5683 3508aba53d Wait for healthy manual MQB startup before arming lateral 2026-11-20 19:49:02 -06:00
firestar5683 ef3b03444c Keep Galaxy widget previews visible while editing 2026-11-20 19:15:36 -06:00
Danny e29879ca79 Bluetooth: Fix Home indicator showing off when a paired iPhone is cached 2026-11-20 19:07:50 -06:00
Danny 14fe0d040d Speed Limit: Keep the Confirmation Steady Through Map Dropouts 2026-11-20 19:07:49 -06:00
Danny 602b54181c Widgets: Load Faster, Keep Scenes in Sync, Tighter Speed Outline, Fix Clicking on Desktop 2026-11-20 19:07:48 -06:00
Danny c82db4bc03 StarPort: Default AA Fallback, Fallback IP, and Skip Step 1 for Unofficial Dongles 2026-11-20 19:07:47 -06:00
Danny d7b3560862 StarPort Logs: Require a Note, Warn on Custom Forks, Log the Repo 2026-11-20 19:07:46 -06:00
firestar5683 256924b83c Keep FLM learning with inactive legacy GM tunes 2026-11-20 17:49:26 -06:00
firestar5683 028cbb9df4 Explain saved GM settings that pause FLM 2026-11-20 17:31:16 -06:00
firestar5683 92f4cbe228 Pass explicit source paths in FLM identity tests 2026-11-20 15:55:56 -06:00
firestar5683 829c5ce6c8 Preserve historical FLM identity guard regression coverage 2026-11-20 15:53:55 -06:00
firestar5683 ee3aa066f8 Keep FLM active with a fixed manual proportional gain 2026-11-20 15:41:49 -06:00
firestar5683 ee82c843ca Expose controller-bound proportional gain in steering settings 2026-11-20 15:15:52 -06:00
firestar5683 9e869ef085 Extract lateral pause conditions under the source size limit 2026-11-20 15:12:51 -06:00
firestar5683 212b1d7eef Initialize Turn Assist in the shared Controls test fixture 2026-11-20 15:01:34 -06:00
firestar5683 57135a1f28 Preserve MQB lateral intent through brake withdrawal 2026-11-20 15:00:43 -06:00
firestar5683 f8e110a1ac Opt in before signaling in automatic turn tests 2026-11-20 14:18:09 -06:00
firestar5683 64a28c5877 Update replay expectations for signaled Turn Assist 2026-11-20 14:05:38 -06:00
firestar5683 f84e678554 Keep FLM findings and manual choices for the same vehicle fingerprint 2026-11-20 13:53:26 -06:00
firestar5683 b00d753a24 Recover Polestar stock relay after a receive backlog 2026-11-20 13:50:54 -06:00
firestar5683 4e0e99039a Explain why FLM findings cannot be accepted 2026-11-20 13:42:44 -06:00
firestar5683 5da0140842 Repair turn fixtures and StarPort layout validation 2026-11-20 13:23:21 -06:00
firestar5683 43b1ea1b34 Bound Tesla radar callback regression tests 2026-11-20 13:17:57 -06:00
firestar5683 508409e6ba Update FLM clock provenance for reviewed model turn guidance 2026-11-20 13:17:56 -06:00
firestar5683 aef357ce92 Select ION buffers for device camera builds 2026-11-20 13:03:36 -06:00
firestar5683 be463c0905 Show torque and delay learning percentages 2026-11-20 12:58:48 -06:00
firestar5683 013d9753e0 Calm RAV4 TSS2 low-speed center corrections 2026-11-20 12:58:47 -06:00
firestar5683 b5b3b8b80f Keep FLM vehicle status stable and explain parked analysis waits 2026-11-20 12:27:05 -06:00
firestar5683 5a88d1c7c1 Separate automatic turn initiation from low-speed turn assistance 2026-11-20 11:52:45 -06:00
firestar5683 08d23a48e9 Add optional steering wheel rotation to Big UI 2026-11-20 11:42:01 -06:00
firestar5683 7181662d12 Model explicit tuning locks in FLM browser fixtures 2026-11-20 11:18:52 -06:00
firestar5683 eac912d9ad Bound Volvo and Tesla HW1 native callback regressions 2026-11-20 11:18:52 -06:00
firestar5683 06f2da46ad Distinguish confirmed FLM changes from manual overrides 2026-11-20 11:04:54 -06:00
firestar5683 38e7b89f66 Exercise Tesla initialization in isolated native regressions 2026-11-20 09:03:28 -06:00
firestar5683 03d6f7b445 Bound Tesla native checksum callback regressions 2026-11-20 08:58:37 -06:00
firestar5683 84592f6012 Cover Toyota AOL hold experience combinations 2026-11-20 08:53:43 -06:00
firestar5683 3bbd0280a6 Check individual Toyota wheel-speed quality faults 2026-11-20 08:42:06 -06:00
firestar5683 fbc192941d Keep stopped Ford leads out of independent light holds 2026-11-20 08:40:48 -06:00
firestar5683 2568d806e4 Keep FLM findings available across drive analyses 2026-11-20 08:26:51 -06:00
firestar5683 8a301fa02f Restore wheel personality callbacks and repair Developer tests 2026-11-20 08:09:54 -06:00
firestar5683 6232db5ce0 Cover Honda transmit bounds and Toyota filter profiles 2026-11-20 08:09:54 -06:00
firestar5683 555dac7d12 Restore Ford steering-wheel speed-limit confirmation 2026-11-20 07:55:17 -06:00
firestar5683 cb3bfc720b Preserve stopped Subaru AOL intent after brake release 2026-11-20 07:49:06 -06:00
firestar5683 6709d6743d Renew SPI reply timeout after valid CAN backpressure 2026-11-19 22:48:05 -06:00
Prabhaav Pillai 4e86f60665 Cleanly restore Reset Driver Monitoring and Reset Calibration into Developer 2026-11-19 23:03:21 -05:00
firestar5683 8af946ac09 Retry speed-limit wheel actions within their original lifetime 2026-11-19 21:54:35 -06:00
firestar5683 1cd4feed89 Cover Honda callback bounds and RDX gas limits 2026-11-19 21:50:55 -06:00
firestar5683 e5ea759719 Separate usable steering samples from complete native history checks 2026-11-19 21:33:27 -06:00
508 changed files with 13608 additions and 1976 deletions
+12 -2
View File
@@ -11,6 +11,7 @@ on:
- testing
- dev
pull_request:
types: [opened, synchronize, reopened, edited]
workflow_dispatch:
workflow_call:
inputs:
@@ -25,11 +26,15 @@ concurrency:
jobs:
docs:
name: build docs
permissions:
contents: read
runs-on: ${{
(github.repository == 'commaai/openpilot') &&
(github.repository == 'StarPilotHQ/StarPilot' && github.event_name == 'push' && github.ref == 'refs/heads/testing')
&& fromJSON('["self-hosted","Linux","X64","truenas","starpilot-build"]')
|| ((github.repository == 'commaai/openpilot') &&
((github.event_name != 'pull_request') ||
(github.event.pull_request.head.repo.full_name == 'commaai/openpilot'))
&& fromJSON('["namespace-profile-amd64-8x16"]')
&& fromJSON('["namespace-profile-amd64-8x16"]'))
|| fromJSON('["ubuntu-24.04"]') }}
steps:
- uses: commaai/timeout@v1
@@ -40,6 +45,11 @@ jobs:
/openpilot/selfdrive/assets/icons_mici/settings/comma_icon.png
sparse-checkout-cone-mode: false
- uses: actions/setup-python@v6
if: github.repository == 'StarPilotHQ/StarPilot' && github.event_name == 'push' && github.ref == 'refs/heads/testing'
with:
python-version: '3.12.13'
# Build
- name: Build docs
run: python3 docs/serve.py --build
+5
View File
@@ -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:
@@ -88,6 +91,8 @@ jobs:
--json-output ci-results/flm-offroad.json
.venv/bin/python -m pytest -q --import-mode=importlib \
openpilot/starpilot/flm/tests/test_steering_compatibility.py \
openpilot/starpilot/flm/tests/test_offroad_nonemitted_controls.py \
openpilot/starpilot/flm/tests/test_pending_review.py \
openpilot/starpilot/flm/tests/test_observed_maneuvers.py \
openpilot/starpilot/flm/tests/test_upstream_producer_transport.py \
openpilot/starpilot/flm/tests/test_clock_resolution_budget.py \
@@ -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
+3 -2
View File
@@ -35,8 +35,9 @@ jobs:
REPO = "StarPilotHQ/StarPilot"
MARKER = "<!-- starpilot-pr-discord-reminder-v1 -->"
BODY = ("In order to review this PR, please open a ticket in the "
"StarPilot Discord at https://firestar.link/discord.\n\n" + MARKER)
BODY = ("Thank you for your PR! To increase communication and responsiveness, "
"please open a ticket describing your PR in the StarPilot discord at "
"[https://firestar.link/discord](https://firestar.link/discord)\n\n" + MARKER)
def remind(event, request):
if event.get("action") != "opened" or "pull_request" not in event:
+1
View File
@@ -4,6 +4,7 @@ on:
push:
branches: [master, Domathon, Dom, StarPilot, stable, testing, dev]
pull_request:
types: [opened, synchronize, reopened, edited]
workflow_dispatch:
permissions:
+12 -4
View File
@@ -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
@@ -45,6 +52,7 @@ jobs:
run: |
python3 -m unittest tools.laptop_device_build.tests.test_runtime_dependencies -v
python3 -c 'from pathlib import Path; assert b"starting pandad (comma hardware)" in Path("openpilot/selfdrive/pandad/pandad").read_bytes(), "Shipped pandad must use the comma hardware build profile"'
python3 -c 'from pathlib import Path; paths = ("openpilot/system/camerad/camerad", "msgq_repo/msgq/visionipc/_visionipc.so", "openpilot/system/loggerd/encoderd", "openpilot/tools/replay/replay"); assert all(b"/dev/ion\0" in Path(p).read_bytes() for p in paths), "Shipped camera buffers must use ION"'
- name: Test one-shot branch migration
run: python3 -m unittest discover -s scripts/tests -v
- name: Validate tracked dependencies
@@ -93,7 +101,7 @@ jobs:
env:
GOTOOLCHAIN: local
run: |
sudo apt-get -o Acquire::Retries=2 -o Acquire::http::Timeout=30 -o Acquire::https::Timeout=30 update && sudo apt-get -o Acquire::Retries=2 -o Acquire::http::Timeout=30 -o Acquire::https::Timeout=30 install -y --no-install-recommends pkg-config zlib1g-dev
sudo apt-get update && sudo apt-get install -y --no-install-recommends pkg-config zlib1g-dev
(cd mapd_repo && go mod download)
PYTHONPATH="$GITHUB_WORKSPACE" python3 -m openpilot.starpilot.maps.package_shadow
- name: Build devel
@@ -218,7 +226,7 @@ jobs:
env:
RAYLIB_BACKEND: headless
STARPILOT_TEST_DIAGNOSTICS: ci-results/host-test-diagnostics/unittest
run: tools/op.sh test --jobs 2 --json-output unit-test-results.json
run: tools/op.sh test --json-output unit-test-results.json
- name: Test GM vehicle configurations and CAN behavior
if: ${{ !cancelled() && steps.build.outcome == 'success' }}
timeout-minutes: 5
@@ -303,7 +311,7 @@ jobs:
.venv/bin/python -c "import av; assert 'libx264' in av.codecs_available"
- name: Provide Mesa software graphics for pixel-level tests
if: ${{ !cancelled() && steps.build.outcome == 'success' }}
run: sudo apt-get -o Acquire::Retries=2 -o Acquire::http::Timeout=30 -o Acquire::https::Timeout=30 update && sudo apt-get -o Acquire::Retries=2 -o Acquire::http::Timeout=30 -o Acquire::https::Timeout=30 install -y libegl1 libgles-dev libgl1-mesa-dri
run: sudo apt-get update && sudo apt-get install -y libegl1 libgles-dev libgl1-mesa-dri
- name: Test every assigned custom pytest node serially
if: ${{ !cancelled() && steps.build.outcome == 'success' }}
timeout-minutes: 20
@@ -410,7 +418,7 @@ jobs:
go-version: '1.25.1'
cache-dependency-path: mapd_repo/go.sum
- name: Install native build dependencies
run: sudo apt-get -o Acquire::Retries=2 -o Acquire::http::Timeout=30 -o Acquire::https::Timeout=30 update && sudo apt-get -o Acquire::Retries=2 -o Acquire::http::Timeout=30 -o Acquire::https::Timeout=30 install -y --no-install-recommends pkg-config zlib1g-dev
run: sudo apt-get update && sudo apt-get install -y --no-install-recommends pkg-config zlib1g-dev
- name: Test and build pinned map provider
run: python3 tools/ci/run_map_tests.py --output ci-results/map-provider
- name: Save test and build evidence
+40 -58
View File
@@ -8,73 +8,33 @@
[![App Store](https://img.shields.io/badge/App_Store-black?logo=apple&logoColor=white)](https://firestar.link/ios)
[![Google Play](https://img.shields.io/badge/Google_Play-green?logo=googleplay&logoColor=white)](https://firestar.link/android)
**StarPilot** is a custom fork of [comma.ai's openpilot](https://comma.ai/openpilot),
an open source driver assistance system.
StarPilot is an open source driver assistance system for comma 3, 3X, and 4. This branch is where you can try StarPilot 7.0.
Openpilot provides
* Automated Lane Centering
* Adaptive Cruise Control
* Lane Change Assist
* Driver Monitoring *without wheel nags*
## What's on testing
Ford-specific lateral-control and vehicle-support work includes substantial adaptations from
[BluePilot](https://github.com/BluePilotDev/bluepilot/tree/bp-7.0), principally developed by
[Alan Polk](https://github.com/alan-polk) with additional BluePilot contributors. StarPilot's
implementation has since diverged, but that does not erase its lineage. See [CREDITS.md](CREDITS.md)
for the code-level provenance and [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md) for applicable
upstream notices and terms. BluePilot and its contributors do not maintain or endorse StarPilot;
please direct support requests for this adaptation to the StarPilot project.
* **Lane Centering 2.0** can keep the car centered when only one lane line is visible in certain scenarios. When lane markings are unreliable, it falls back to the driving model's path.
* **Enhanced Stops** improves stops at stop signs and traffic lights. Vision Stop Sign Detection uses the road camera to recognize stop signs.
* **Custom Controllers** improve turning behavior on supported vehicles. The Firestar Lateral Method adapts steering to your car, and StarPilot's longitudinal planner manages acceleration and braking on supported radar and vision-only configurations.
* **Custom Models** let you choose from community fine tunes in Galaxy's Model Manager.
* **On-Device UI Replay** lets you review a recorded drive with the driving interface overlaid on the footage.
Hyundai, Kia, and Genesis angle steering and related vehicle support include substantial adaptations
from [sunnypilot](https://github.com/sunnypilot/sunnypilot/tree/hkg-angle-steering-2025) and its
[opendbc angle-steering branch](https://github.com/sunnypilot/opendbc/tree/hkg-angle-steering-2025).
StarPilot's implementation has diverged significantly; the upstream contributors do not maintain
this adaptation. Detailed code lineage is recorded in [CREDITS.md](CREDITS.md).
## StarPort and companion apps
StarPilot has a vibrant, welcoming community [discord](https://firestar.link/discord).
Stop by to chat or ask questions!
If your car isn't driving as well as you'd like, [open a ticket so we can help](https://firestar.link/logs)!
**StarPort** puts the driving display on a compatible Android Auto head unit, with navigation, music controls, and model connection status. Use Mapbox or Google Maps for route guidance, and play audio through compatible car speakers with Spotify Connect or phone audio.
## Documentation
**Galaxy** lets you change settings, download models, update StarPilot, run diagnostics, and manage dashcam footage from your phone. The native apps connect over Wi-Fi, Firestar Link (HTTPS), or Bluetooth. [Download for iOS](https://firestar.link/ios) · [Download for Android](https://firestar.link/android)
Please see [https://wiki.firestar.link](https://wiki.firestar.link) for hardware lists,
installation guides, and software configuration.
## Getting started
## Features
Find supported hardware, installation steps, and settings in the [StarPilot wiki](https://wiki.firestar.link). Ask questions in the [community Discord](https://firestar.link/discord) or [open a driving support ticket](https://firestar.link/logs).
* **Full support for Comma C3, C3X, and C4**
* Full support for chestnut/eGPU on C3, C3X, and C4. C3/C3X may require special gps handling.
* Model switcher with all of comma's tinygrad driving models
* StarPilot custom torque controller
* StarPilot custom longitudinal planner for both radar and VoACC (visual only, radar-less) vehicles
* **Custom tuning for an expanding list of vehicles**
* Firestar Lateral Method -
Auto tuning system to adapt openpilot to *your* car's unique lateral characteristics.
* Galaxy: StarPilot's portal to configure your comma device using your phone from anywhere.
Download models, change settings, update software, diagnostics, manage dashcam video, and more.
* Android and iOS companion apps - Access Galaxy over Wi-Fi, Firestar Link (HTTPS), or Bluetooth.
* StarPort - Project StarPilot onto compatible Android Auto head units for a larger driving display.
* Customizable driving display - Driving map and navigation widgets, plus music controls and Jetlink status in StarPort.
* Spotify Connect and phone audio - Play through compatible car speakers over StarPort or Bluetooth.
* Navigation - Mapbox or Google maps and routing, with route guidance for exits and turns.
* Always On Lateral (full time steering assist)
* Lane Centering - Enable to center between detected lane lines,
with graceful fallback to model E2E lateral outputs and safety breakout
* Force Stop 2.0 - Better stops at stop signs and traffic lights.
* Speed Limit Controller - Use dashboard, map data, and/or vision detection for speed limit signs
* Curve Speed Controller - Learns from how you take curves
* Conditional Experimental Mode (CEM)
* Conditional Chill Mode (CCM)
* Driving Profiles and Traffic Mode
* Custom themes
* Alert volume customization
* Comma Pedal Interceptor support
* Bluetooth support - Connect keyboards, controllers, steering wheel remotes, and more.
* Sentry mode - Record when motion is detected while parked.
* V-ASM - Detect vehicles in the adjacent/blind spots using the driver-facing camera.
* Additional car support - Toyota SDSU, ZSS, CAN filter; pre-AP tesla; ford; Polestar 2; and more.
* And more!
## More driving and device features
* Always On Lateral keeps steering assistance available independently of adaptive cruise on supported vehicles.
* Speed Limit Controller uses dashboard, map, or vision data. Curve Speed Controller learns from how you take curves.
* Driving Profiles and Traffic Mode, adjustable alert volume, and vehicle-specific tuning.
* Bluetooth keyboards, controllers, and steering wheel remotes.
* Sentry Mode records motion while parked. V-ASM uses the driver-facing camera to detect vehicles alongside the car.
## GM-only Features
@@ -111,6 +71,28 @@ StarPilot retains upstream vehicle and Panda safety interfaces and adds regressi
Support depends on the vehicle configuration and enabled feature. An existing vehicle identifier or settings page does not by itself establish driving support. Model Laboratory currently exposes management controls, but paired driving inference remains unavailable pending integration and Chestnut validation.
## Integrations and credits
StarPilot builds on [comma.ai's openpilot](https://comma.ai/openpilot), which provides automated lane centering, adaptive cruise control, lane change assist, and driver monitoring.
* **JetLink** is an experimental integration with Zeph Leggett / ZoomPilot's host software. Run a larger driving model on a compatible USB-connected laptop, phone, tablet, or Jetson. See the [JetLink setup and hardware guide](openpilot/starpilot/models/JETLINK.md).
* **Chestnut eGPU** is supported on comma 3, 3X, and 4. The 3 and 3X may need additional GPS setup. The model switcher also supports comma's tinygrad driving models.
* Additional vehicle and hardware integrations include the comma pedal interceptor, Toyota SDSU, ZSS and CAN filter configurations, pre-AP Tesla, Ford, and Polestar 2.
Ford-specific lateral-control and vehicle-support work includes substantial adaptations from
[BluePilot](https://github.com/BluePilotDev/bluepilot/tree/bp-7.0), principally developed by
[Alan Polk](https://github.com/alan-polk) with additional BluePilot contributors. StarPilot's
implementation has since diverged, but that does not erase its lineage. See [CREDITS.md](CREDITS.md)
for the code-level provenance and [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md) for applicable
upstream notices and terms. BluePilot and its contributors do not maintain or endorse StarPilot;
please direct support requests for this adaptation to the StarPilot project.
Hyundai, Kia, and Genesis angle steering and related vehicle support include substantial adaptations
from [sunnypilot](https://github.com/sunnypilot/sunnypilot/tree/hkg-angle-steering-2025) and its
[opendbc angle-steering branch](https://github.com/sunnypilot/opendbc/tree/hkg-angle-steering-2025).
StarPilot's implementation has diverged significantly; the upstream contributors do not maintain
this adaptation. Detailed code lineage is recorded in [CREDITS.md](CREDITS.md).
## Third-Party Notices
* Portions of this software include modified versions of the Material Design Icons provided by Google under the Apache License 2.0. A copy of the license is included in the `LICENSE-MDI` file.
+1 -1
View File
@@ -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.
+1 -1
View File
@@ -39,7 +39,7 @@ msgq_python = envNanobind.Program(f'msgq/_ipc{python_suffix}', ['msgq/ipc_py.cc'
# Build Vision IPC
vipc_files = ['visionipc.cc', 'visionipc_server.cc', 'visionipc_client.cc']
if File('/dev/ion').exists():
if arch == "comma_arm64" or File('/dev/ion').exists():
vipc_files += ['visionbuf_ion.cc']
else:
vipc_files += ['visionbuf.cc']
Binary file not shown.
Binary file not shown.
Binary file not shown.
+30 -7
View File
@@ -13,9 +13,11 @@ from opendbc.car.gm.pedal_capability import automatic_bolt_candidate
from opendbc.car.gm.discovery import automatic_trax_candidate, automatic_volt_candidate, normal_bus0_topology as gm_normal_bus0_topology
from opendbc.car.ford.discovery import (normal_bus0_selection as ford_normal_bus0_selection,
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
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.mazda.discovery import normal_bus0_topology as mazda_normal_bus0_topology
from opendbc.car.chrysler.discovery import normal_bus_topology as chrysler_normal_bus_topology
from opendbc.car.tesla.discovery import normal_bus0_topology as tesla_normal_bus0_topology
from opendbc.car.values import BRANDS
@@ -143,6 +145,14 @@ def fingerprint(can_recv: CanRecvCallable, can_send: CanSendCallable, set_obd_mu
cached = True
else:
carlog.warning("Getting VIN & FW versions")
volvo_v60 = False
def volvo_probe(fp):
nonlocal volvo_v60
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
@@ -179,21 +189,34 @@ def fingerprint(can_recv: CanRecvCallable, can_send: CanSendCallable, set_obd_mu
elif (normal_brand := normal_bus_query_brand(
observe_normal_bus, normal_bus_topology,
gm_probe=gm_normal_bus0_topology if _gm_fw_uses_normal_bus0() else None,
volvo_probe=volvo_normal_bus_topology if not fw_versions.FW_QUERY_CONFIGS['volvo'].requests else None,
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
('chrysler' if chrysler_normal_bus_topology(normal_bus_packets) else None)) is not None:
('honda_nidec' if nidec_bus0_topology(normal_bus_packets) else None) or
('chrysler' if chrysler_normal_bus_topology(normal_bus_packets) else None) or
('mazda' if mazda_normal_bus0_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', 'mazda') else (0, 1)
vin_rx_addr, vin_rx_bus, vin = get_vin(can_recv, can_send, vin_buses)
car_fw = 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)
@@ -79,6 +79,10 @@ def ford_sign(speed: int, unit: int) -> tuple[Status, float]:
return (Status.ABSENT, 0.0) if speed in (251, 255) else (Status.UNKNOWN, 0.0)
def volvo_sign(speed_kph: float) -> tuple[Status, float]:
return (Status.VALID, speed_kph / 3.6) if speed_kph > 0 else (Status.ABSENT, 0.0)
def hyundai_canfd_sign(speed: int, system_status: int, is_metric: bool) -> tuple[Status, float]:
# FR_CMR_02_100ms defines 0 as no recognition, 253 as unlimited, and
# 254/255 as reserved/invalid. A failed ISLW system is not evidence of absence.
@@ -93,6 +93,7 @@ class Request:
logging: bool = False
# pandad toggles OBD multiplexing on/off as needed
obd_multiplexing: bool = True
brand_query_only: bool = False
@dataclass
+12 -5
View File
@@ -40,6 +40,11 @@ def is_brand(brand: str, filter_brand: str | None) -> bool:
return filter_brand is None or brand == filter_brand
def firmware_requests(query_brand: str | None = None):
return [(brand, config, request) for brand, config, request in REQUESTS
if is_brand(brand, query_brand) and (query_brand is not None or not request.brand_query_only)]
def build_fw_dict(fw_versions: list[CarParams.CarFw], filter_brand: str | None = None) -> dict[AddrType, set[bytes]]:
fw_versions_dict: defaultdict[AddrType, set[bytes]] = defaultdict(set)
for fw in fw_versions:
@@ -200,7 +205,7 @@ def get_present_ecus(can_recv: CanRecvCallable, can_send: CanSendCallable, set_o
parallel_queries: dict[bool, list[EcuAddrBusType]] = {True: [], False: []}
responses: set[EcuAddrBusType] = set()
for brand, config, r in REQUESTS:
for brand, config, r in firmware_requests():
for ecu_type, addr, sub_addr in config.get_all_ecus(VERSIONS[brand]):
# Only query ecus in whitelist if whitelist is not empty
if len(r.whitelist_ecus) == 0 or ecu_type in r.whitelist_ecus:
@@ -232,10 +237,11 @@ def get_brand_ecu_matches(ecu_rx_addrs: set[EcuAddrBusType]) -> dict[str, list[b
"""Returns dictionary of brands and matches with ECUs in their FW versions"""
brand_rx_addrs = {brand: set() for brand in FW_QUERY_CONFIGS}
brand_matches = {brand: [] for brand, _, _ in REQUESTS}
requests = firmware_requests()
brand_matches = {brand: [] for brand, _, _ in requests}
# Since we can't know what request an ecu responded to, add matches for all possible rx offsets
for brand, config, r in REQUESTS:
for brand, config, r in requests:
for ecu in config.get_all_ecus(VERSIONS[brand]):
if len(r.whitelist_ecus) == 0 or ecu[0] in r.whitelist_ecus:
brand_rx_addrs[brand].add((uds.get_rx_addr_for_tx_addr(ecu[1], r.rx_offset), ecu[2]))
@@ -275,7 +281,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:
@@ -308,7 +314,8 @@ 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
requests = [(brand, config, r) for brand, config, r in firmware_requests(query_brand) if
(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):
+5 -1
View File
@@ -1008,7 +1008,8 @@ class CarController(CarControllerBase):
else:
stop_brake = fixed_stopping_brake(CC.longActive, near_stop, stopping, CC.cruiseControl.resume,
self.CP.stopAccel, self.params.MAX_BRAKE)
if stop_brake is not None:
bolt_rolling_stop = self.bolt_euv_long and stop_brake is not None and not CS.out.standstill
if stop_brake is not None and not bolt_rolling_stop:
self.apply_gas = self.params.INACTIVE_REGEN
self.apply_brake = stop_brake
if self.truck_tuning is not None:
@@ -1035,6 +1036,9 @@ class CarController(CarControllerBase):
self.apply_gas, self.apply_brake = bolt_euv_demands(
actuators.accel, CS.out.vEgo, CC.orientationNED if long_pitch else None,
self.CP.mass, self.CP.wheelbase, self.params.MAX_BRAKE, acc_tune=self.gm_acc_tune)
if bolt_rolling_stop:
# Keep the requested braking until the wheels stop rolling.
self.apply_brake = max(self.apply_brake, stop_brake)
elif self.volt_gateway_long or self.volt_ascm_long or self.volt_camera_long or self.volt_sdgm_long:
self.apply_gas, self.apply_brake = volt_demands(
actuators.accel, CS.out.vEgo, CC.orientationNED if long_pitch else None,
+8 -3
View File
@@ -419,10 +419,12 @@ class CarState(CarStateBase):
ret.standstill = abs(pt_cp.vl["EBCMWheelSpdRear"]["RLWheelSpd"]) <= STANDSTILL_THRESHOLD and \
abs(pt_cp.vl["EBCMWheelSpdRear"]["RRWheelSpd"]) <= STANDSTILL_THRESHOLD
if pt_cp.vl["ECMPRDNL2"]["ManualMode"] == 1:
gear = pt_cp.vl["ECMPRDNL2"]
self.gm_regen_gear = self.bolt_cc_profile and self.CP.carFingerprint in NO_ACC_BOLT_CAR and gear["PRNDL2"] in (5, 7)
if gear["ManualMode"] == 1:
ret.gearShifter = self.parse_gear_shifter("T")
else:
ret.gearShifter = self.parse_gear_shifter(self.shifter_values.get(pt_cp.vl["ECMPRDNL2"]["PRNDL2"], None))
ret.gearShifter = self.parse_gear_shifter(self.shifter_values.get(gear["PRNDL2"], None))
source_be_brake = (gm_control_word(self.CP) &
(GMSafetyFlags.ASCM_INTERCEPT | GMSafetyFlags.SDGM).value and
@@ -493,7 +495,10 @@ class CarState(CarStateBase):
if new_sample:
self.pedal_sensor_ts_nanos = sensor_ts
self.pedal_sensor_counter = counter
self.pedal_sensor_healthy = bool(counter_changed and sensor["STATE"] == 0 and tracks_valid and checksum_valid)
state = sensor["STATE"]
state_ok = state == 0 or (state == 8 and bolt_pedal_profile and not removed_pedal and
self.CP.carFingerprint == CAR.CHEVROLET_BOLT_CC_2022_2023)
self.pedal_sensor_healthy = bool(counter_changed and state_ok and tracks_valid and checksum_valid)
elif sensor_ts < self.pedal_sensor_ts_nanos:
self.pedal_sensor_healthy = False
self.pedal_sensor_ts_nanos = 0
@@ -10,11 +10,12 @@ from opendbc.car.gm.tests.test_ascm_intercept import params
from opendbc.car.gm.values import CAR, DBC, is_bolt_euv_longitudinal
def original_demand(cp, active, speed, accel, state, resume, pitch):
# Original 6cae0ce, ordinary non-Volt camera path; default LongPitch on.
def original_demand(cp, active, speed, accel, state, resume, pitch, *, standstill=False):
# Original 6cae0ce camera path, with the hold demand as a floor while rolling.
if not active:
return 5650, 0
if speed < 0.25 and state == 'stopping' and not resume:
hold = speed < 0.25 and state == 'stopping' and not resume
if hold and standstill:
return 5650, 25
grade = math.sin(pitch) * 9.81 if speed > 0.25 else 0.0
if grade > 0 and accel > 0:
@@ -27,6 +28,8 @@ def original_demand(cp, active, speed, accel, state, resume, pitch):
switch = int(round(np.interp(speed, [0.5, 10.0], [6150, 5610])))
brake_accel = min((torque - switch) / (radius * cp.mass), 0.0)
brake = int(round(np.interp(brake_accel, [-4.0, 0.0], [400, 0])))
if hold:
brake = max(25, brake)
return (5650 if brake > 0 or state == 'stopping' else raw), brake
@@ -58,7 +61,8 @@ PHASES = [(False, False, 12., 1., 'off', False, False, 0.),
(True, True, 12., 1., 'pid', False, False, 0.),
(True, True, 7., -1.5, 'pid', False, False, -0.04)]
PHASES += [(True, True, speed, -2., 'stopping', False, False, 0.) for speed in (0.6, 0.49, 0.3, 0.25, 0.24, 0.1)]
PHASES += [(True, True, 0., -4., 'stopping', False, True, 0.),
PHASES += [(True, True, .213, -.665, 'stopping', False, False, 0.),
(True, True, 0., -.665, 'stopping', False, True, 0.),
(True, True, 0., 1., 'stopping', True, True, 0.),
(True, True, 0., 0.5, 'starting', True, True, 0.),
(True, True, 0.3, 0.5, 'starting', True, False, 0.),
@@ -136,7 +140,7 @@ class TestBoltEuvControl(unittest.TestCase):
if not alpha or frame % 4:
self.assertFalse(actual)
continue
raw, brake = original_demand(cp, active, speed, accel, state, resume, pitch)
raw, brake = original_demand(cp, active, speed, accel, state, resume, pitch, standstill=still)
expected = original_frames(raw, brake, (frame // 4) % 4, enabled, active and still and state == 'stopping')
self.assertEqual(actual, expected, (alpha, alignment, phase, frame))
self.assertEqual((controller.apply_gas, controller.apply_brake), (raw - 6150, brake))
@@ -50,9 +50,10 @@ class TestBoltFactoryAcc(unittest.TestCase):
ci = CarInterface(cp)
packer = CANPacker(DBC[cp.carFingerprint][Bus.pt])
setup(cp)
cases = [(speed, accel, pitch) for speed in (5., 20., 35.)
cases = [(speed, accel, pitch, 'pid') for speed in (5., 20., 35.)
for accel in (-4., -2., -.5, 0., 1., 2.) for pitch in (-.04, 0., .04)]
for tick, (speed, accel, pitch) in enumerate(cases):
cases += [(.213, -.665, 0., 'stopping'), (0., -.665, 0., 'stopping')]
for tick, (speed, accel, pitch, state) in enumerate(cases):
now = 1_000_000_000 + tick * 40_000_000
out, sources = feed(ci, packer, now, counter=tick % 4, speed=speed)
sources.append(packer.make_can_msg('ASCMActiveCruiseControlStatus', 2, {'ACCCruiseState': 3}))
@@ -68,14 +69,15 @@ class TestBoltFactoryAcc(unittest.TestCase):
control = structs.CarControl(enabled=True, longActive=cp.openpilotLongitudinalControl,
orientationNED=[0., pitch, 0.])
control.actuators.accel = accel
control.actuators.longControlState = structs.CarControl.Actuators.LongControlState.pid
control.actuators.longControlState = state
ci.CC.frame = tick * 4
_, messages = ci.apply(control.as_reader(), now)
long_messages = [m for m in messages if m[0] in (0x2CB, 0x315, 0x2CD)]
self.assertFalse(any(m[0] in (0x200, 0x1F5, 0xBD) for m in messages))
if cp.openpilotLongitudinalControl:
raw, brake = original_demand(cp, True, out.vEgo, accel, 'pid', False, pitch)
self.assertEqual(long_messages, original_frames(raw, brake, tick % 4, True, False))
raw, brake = original_demand(cp, True, out.vEgo, accel, state, False, pitch, standstill=out.standstill)
full_stop = out.standstill and state == 'stopping'
self.assertEqual(long_messages, original_frames(raw, brake, tick % 4, True, full_stop))
for message in long_messages:
self.assertTrue(native('tx', message, now // 1000), hex(message[0]))
else:
@@ -337,6 +337,13 @@ class TestBoltPedalMessages(unittest.TestCase):
self.assertTrue(state.pedal_sensor_healthy, gas)
self.assertEqual(out.gasPressed, gas > 23., gas)
parsers[Bus.pt].update([(1_170_000_000, [self.sensor(packer, 30., 0, state=8)])])
out = state.update(parsers)
expected = candidate == CAR.CHEVROLET_BOLT_CC_2022_2023
self.assertEqual(state.pedal_sensor_healthy, expected)
if expected:
self.assertTrue(out.gasPressed)
for counter, kwargs in ((9, {"state": 1}), (10, {"other_track": 1000.}), (11, {"bad_crc": True})):
parsers[Bus.pt].update([(1_000_000_000 + counter * 20_000_000,
[self.sensor(packer, 30., counter, **kwargs)])])
+5
View File
@@ -951,6 +951,11 @@ def is_bolt_pedal_profile(cp, *, stock_only=False):
return _bolt_pedal_profile(cp, stock_only=stock_only)
def bolt_pedal_in_drive_requires_low(cp, gear):
return (gear == 'drive' and getattr(cp, 'carFingerprint', None) in (CAR.CHEVROLET_BOLT_CC_2017, CAR.CHEVROLET_BOLT_CC_2018_2021) and
is_bolt_pedal_profile(cp))
@cached_config
def _bolt_pedal_profile(cp, *, stock_only=False):
"""Exact selected interceptor profile, including its startup authority reduction."""
+16 -4
View File
@@ -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)
@@ -186,7 +186,7 @@ class CANFDLfaStatus:
return True
return 0 < self.popup_last_applied_ns <= now_ns <= self.popup_last_applied_ns + DISPLAY_RELEASE_NS
def owns_ccnc_fault_status(self, now_ns, *, healthy=False, qualified_warning=False):
def owns_ccnc_fault_status(self, now_ns, *, display_sample_ns, healthy=False, qualified_warning=False):
body = self.current(now_ns)
eps_fresh = 0 < self.eps_observed_ns <= now_ns and now_ns - self.eps_observed_ns <= MAX_AGE_NS
indication = ((body[4] >> 6) | ((body[5] & 1) << 2)) if body is not None else 7
@@ -198,7 +198,13 @@ class CANFDLfaStatus:
if qualified_warning:
self.ccnc_last_owned_ns = now_ns
return True
return 0 < self.ccnc_last_owned_ns <= now_ns <= self.ccnc_last_owned_ns + MAX_AGE_NS
last_owned_ns = self.ccnc_last_owned_ns
if not 0 < last_owned_ns <= now_ns:
return False
if now_ns - last_owned_ns <= MAX_AGE_NS:
return True
return (last_owned_ns <= display_sample_ns <= last_owned_ns + MAX_AGE_NS and
display_sample_ns <= now_ns <= display_sample_ns + MAX_AGE_NS)
def last_fault(self):
body = self.body
@@ -115,12 +115,36 @@ def qualified(cp, *, marked_only=False):
SPORTAGE_LONG_AOL_WORDS = frozenset(0x0804 | fuel | topology for fuel in (0, 2) for topology in (0, 8, 16, 144, 32, 40))
CARNIVAL_LONG_AOL_WORD = 0x28B4
LONG_AOL_WORDS = frozenset((CARNIVAL_LONG_AOL_WORD, 0x080D, 0x0815, 0x0895, 0x2815, 0x2895)) | SPORTAGE_LONG_AOL_WORDS
CCNC_LONG_CARS = frozenset((CAR.HYUNDAI_KONA_2ND_GEN, CAR.HYUNDAI_KONA_HEV_2ND_GEN))
CCNC_LONG_AOL_WORDS = frozenset((0x0C0C, 0x0C0E, 0x0C2C, 0x0C2E))
LONG_EV_CARS = frozenset((CAR.HYUNDAI_IONIQ_5, CAR.HYUNDAI_KONA_EV_2ND_GEN))
LONG_AOL_WORDS |= CCNC_LONG_AOL_WORDS
INDEPENDENT_LONG_BUTTON_CARS = LONG_EV_CARS | CCNC_LONG_CARS | {
CAR.KIA_EV6, CAR.HYUNDAI_IONIQ_6, CAR.GENESIS_GV70_ELECTRIFIED_1ST_GEN,
GENERIC_HDA2_CARS = frozenset((
CAR.GENESIS_G80_2ND_GEN_FL,
CAR.HYUNDAI_IONIQ_5_N,
CAR.HYUNDAI_KONA_2ND_GEN,
CAR.HYUNDAI_KONA_HEV_2ND_GEN,
CAR.HYUNDAI_SANTA_CRUZ_1ST_GEN,
CAR.HYUNDAI_SANTA_CRUZ_2025,
CAR.HYUNDAI_SONATA_2024,
CAR.HYUNDAI_SONATA_HEV_2024,
CAR.HYUNDAI_STARIA_4TH_GEN,
CAR.HYUNDAI_TUCSON_2025,
CAR.HYUNDAI_TUCSON_4TH_GEN,
CAR.HYUNDAI_TUCSON_HEV_2025,
CAR.HYUNDAI_TUCSON_PHEV_2025,
CAR.KIA_CARNIVAL_2025,
CAR.KIA_CARNIVAL_HEV_4TH_GEN,
CAR.KIA_K4_2025,
CAR.KIA_K5_2025,
CAR.KIA_K8_HEV_1ST_GEN,
CAR.KIA_NIRO_EV_2ND_GEN,
CAR.KIA_NIRO_HEV_2ND_GEN,
CAR.KIA_SORENTO_2024,
CAR.KIA_SPORTAGE_5TH_GEN,
))
INDEPENDENT_LONG_BUTTON_CARS = LONG_EV_CARS | GENERIC_HDA2_CARS | {
CAR.KIA_EV6, CAR.KIA_NIRO_EV_2ND_GEN, CAR.HYUNDAI_IONIQ_6, CAR.GENESIS_GV70_ELECTRIFIED_1ST_GEN,
CAR.GENESIS_GV60_EV_1ST_GEN, CAR.KIA_SPORTAGE_5TH_GEN, CAR.KIA_CARNIVAL_2025,
}
@@ -139,15 +163,25 @@ def qualified_long(cp, *, marked_only=False):
if cp.carFingerprint in (CAR.KIA_EV6, CAR.GENESIS_GV60_EV_1ST_GEN, CAR.HYUNDAI_IONIQ_6):
if word != 0x09:
return False
elif cp.carFingerprint in CCNC_LONG_CARS:
if word is None or word | 0x804 not in CCNC_LONG_AOL_WORDS:
return False
elif cp.carFingerprint == CAR.KIA_SPORTAGE_5TH_GEN:
if word is None or word | 0x804 not in SPORTAGE_LONG_AOL_WORDS:
return False
elif cp.carFingerprint == CAR.KIA_CARNIVAL_2025:
if word != 0x20B0:
return False
elif cp.carFingerprint == CAR.KIA_CARNIVAL_HEV_4TH_GEN:
return False
elif cp.carFingerprint in GENERIC_HDA2_CARS:
if word is None or not cp.alphaLongitudinalAvailable:
return False
if word & 0x10:
if len(cp.safetyConfigs) != 1 or word not in (0x10, 0x11, 0x12, 0x90, 0x91, 0x92):
return False
elif cp.carFingerprint == CAR.KIA_NIRO_EV_2ND_GEN:
if word != 0x09:
return False
elif word not in (0x08, 0x0A, 0x28, 0x2A, 0x408, 0x40A, 0x428, 0x42A):
return False
elif word not in (0x11, 0x91) and not (cp.carFingerprint == CAR.HYUNDAI_IONIQ_5 and word == 0x09):
return False
raw = int(cp.safetyConfigs[config_index(cp)].safetyParam)
@@ -132,6 +132,10 @@ class CarController(CarControllerBase):
self.apply_torque_last = 0
self.car_fingerprint = CP.carFingerprint
self.last_button_frame = 0
from opendbc.car.hyundai.software_cruise import selected as software_cruise_selected
self.software_cruise_enabled = software_cruise_selected(self.CP)
self.software_cruise_command = 0
self.software_cruise_command_ns = 0
self.cancel_counter = 0
self.blended_longitudinal = None
self.blended_previous_lateral = False
@@ -294,6 +298,16 @@ class CarController(CarControllerBase):
can_sends.extend(self.create_can_msgs(apply_steer_req, apply_torque, torque_fault, set_speed_in_units, accel,
stopping, hud_control, actuators, CS, CC, lead_data=lead_data))
if (self.software_cruise_enabled and self.cancel_counter <= CANCEL_BUTTON_DELAY_FRAMES and
not CC.cruiseControl.resume and not CC.cruiseControl.cancel and not CC.cruiseControl.override):
command = self.software_cruise_command
if (command in (1, 2) and self.software_cruise_command_ns == now_nanos and
(self.frame - self.last_button_frame) * DT_CTRL > 0.10):
button = Buttons.RES_ACCEL if command == 1 else Buttons.SET_DECEL
can_sends.append(hyundaican.create_clu11(self.packer, self.frame, CS.clu11, button, self.CP))
if (self.frame - self.last_button_frame) * DT_CTRL >= 0.15:
self.last_button_frame = self.frame
new_actuators = actuators.as_builder()
new_actuators.torque = apply_torque / self.params.STEER_MAX
new_actuators.torqueOutputCan = apply_torque
@@ -552,8 +566,8 @@ class CarController(CarControllerBase):
stock_popup_owned = stock_source.owns_disengage_popup(apply_steer_req, clock_boot_ns(), healthy=display_healthy,
qualified_warning=stock_owned_status)
if ccnc_non_lka:
stock_ccnc_owned = stock_source.owns_ccnc_fault_status(clock_boot_ns(), healthy=display_healthy,
qualified_warning=stock_owned_status)
stock_ccnc_owned = stock_source.owns_ccnc_fault_status(clock_boot_ns(), display_sample_ns=CS.ccnc_162_ts_ns,
healthy=display_healthy, qualified_warning=stock_owned_status)
damping_source = getattr(CS, "stock_lkas_damping", None)
can_sends.extend(hyundaicanfd.create_steering_messages(self.packer, self.CP, self.CAN,
steering_status_active, apply_steer_req, apply_torque,
+10 -4
View File
@@ -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
@@ -1,6 +1,7 @@
"""Exact Forte non-SCC AOL identity and physical-button observations."""
from opendbc.car.structs import CarParams
from opendbc.car.hyundai.values import CAR, HyundaiFlags
from opendbc.car.hyundai.non_scc_aol import SOFTWARE_CRUISE
FORTE_IDS = (CAR.KIA_FORTE_2019_NON_SCC, CAR.KIA_FORTE_2021_NON_SCC)
FORTE_AOL_MARKER = 0x0400
@@ -19,8 +20,10 @@ def qualified(cp):
not cp.notCar and not cp.openpilotLongitudinalControl and cp.pcmCruise and
bool(cp.flags & HyundaiFlags.NON_SCC) and not int(cp.flags) & ~int(allowed_flags) and
len(cp.safetyConfigs) == 1 and cp.safetyConfigs[0].safetyModel == CarParams.SafetyModel.hyundai and
cp.safetyConfigs[0].safetyParam in words)
(cp.safetyConfigs[0].safetyParam & ~SOFTWARE_CRUISE) in words)
# Keep the public Forte fixture/provider API while sharing the same state machine.
from opendbc.car.hyundai.non_scc_aol import NonSccLkasSources as ForteLkasSources
from opendbc.car.hyundai.non_scc_aol import NonSccLkasSources
ForteLkasSources = NonSccLkasSources
@@ -2,37 +2,12 @@ from copy import deepcopy
from typing import Any
import time
from opendbc.car.hyundai.canfd_stock_aol import qualified as stock_qualified, qualified_long
from opendbc.car.hyundai.canfd_stock_aol import GENERIC_HDA2_CARS as CARS, qualified as stock_qualified, qualified_long
from opendbc.car.hyundai.ecu_continuity import ContinuousECUStartup, StartupKeeper
from opendbc.car.hyundai.ecu_startup import Outcome, stock_copy
from opendbc.car.hyundai.radar_hda2_startup import RadarHDA2Startup
from opendbc.car.hyundai.values import CAR, HyundaiFlags, is_blended
CARS = frozenset((
CAR.GENESIS_G80_2ND_GEN_FL,
CAR.HYUNDAI_IONIQ_5_N,
CAR.HYUNDAI_KONA_2ND_GEN,
CAR.HYUNDAI_KONA_HEV_2ND_GEN,
CAR.HYUNDAI_SANTA_CRUZ_1ST_GEN,
CAR.HYUNDAI_SANTA_CRUZ_2025,
CAR.HYUNDAI_SONATA_2024,
CAR.HYUNDAI_SONATA_HEV_2024,
CAR.HYUNDAI_STARIA_4TH_GEN,
CAR.HYUNDAI_TUCSON_2025,
CAR.HYUNDAI_TUCSON_4TH_GEN,
CAR.HYUNDAI_TUCSON_HEV_2025,
CAR.HYUNDAI_TUCSON_PHEV_2025,
CAR.KIA_CARNIVAL_2025,
CAR.KIA_CARNIVAL_HEV_4TH_GEN,
CAR.KIA_K4_2025,
CAR.KIA_K5_2025,
CAR.KIA_K8_HEV_1ST_GEN,
CAR.KIA_NIRO_EV_2ND_GEN,
CAR.KIA_NIRO_HEV_2ND_GEN,
CAR.KIA_SORENTO_2024,
CAR.KIA_SPORTAGE_5TH_GEN,
))
EXISTING_OWNERS_OR_DISTINCT_RECEIVERS = frozenset((
CAR.HYUNDAI_KONA_EV_2ND_GEN,
CAR.HYUNDAI_IONIQ_5,
@@ -12,6 +12,7 @@ NON_SCC_IDS = frozenset((CAR.HYUNDAI_BAYON_1ST_GEN_NON_SCC, CAR.HYUNDAI_ELANTRA_
CAR.HYUNDAI_ELANTRA_HEV_2022_NON_SCC, CAR.HYUNDAI_KONA_NON_SCC, CAR.HYUNDAI_KONA_EV_NON_SCC,
CAR.KIA_CEED_PHEV_2022_NON_SCC, CAR.KIA_FORTE_2019_NON_SCC, CAR.KIA_FORTE_2021_NON_SCC,
CAR.KIA_SELTOS_2023_NON_SCC, CAR.GENESIS_G70_2021_NON_SCC))
SOFTWARE_CRUISE = 0x0020
AOL_MARKER = 0x0400
AOL_EXPERIENCE = 32
AOL_WORDS = frozenset((0x1400, 0x1c00, 0x1440, 0x1c40, 0x1441, 0x1c41, 0x1402, 0x1c02))
@@ -47,11 +48,11 @@ def qualified(cp):
# ordinary safety may still use its original MAIN-only profile.
ordinary = word & ~int(HyundaiSafetyFlags.HAS_LDA_BUTTON)
return (safety.safetyModel == structs.CarParams.SafetyModel.hyundai and
safety.safetyParam in (word, ordinary, word | AOL_MARKER))
(safety.safetyParam & ~SOFTWARE_CRUISE) in (word, ordinary, word | AOL_MARKER))
def aol_word(cp):
return stock_word(cp) | AOL_MARKER
return stock_word(cp) | AOL_MARKER | (cp.safetyConfigs[0].safetyParam & SOFTWARE_CRUISE)
SOURCE_MAX_AGE_NS = 300_000_000
@@ -0,0 +1,18 @@
"""Conventional cruise button control for exact classic Hyundai profiles."""
from opendbc.car.hyundai.non_scc_aol import SOFTWARE_CRUISE, qualified
def eligible(cp):
return cp is not None and qualified(cp)
def selected(cp):
return (cp is not None and cp.brand == 'hyundai' and len(cp.safetyConfigs) == 1 and
bool(cp.safetyConfigs[0].safetyParam & SOFTWARE_CRUISE) and eligible(cp))
def prepare(cp, enabled):
if enabled and eligible(cp):
cp.safetyConfigs[0].safetyParam |= SOFTWARE_CRUISE
return cp
@@ -0,0 +1,50 @@
from types import SimpleNamespace
import pytest
from opendbc.car import gen_empty_fingerprint
from opendbc.car.hyundai.canfd_stock_aol import qualified_long
from opendbc.car.hyundai.interface import CarInterface
from opendbc.car.hyundai.values import CAR
from openpilot.starpilot.car.hyundai.aol import native_accepts_cp, policy_for
from openpilot.starpilot.ui.wheel_feature import WheelFeature
@pytest.mark.parametrize('identity, hybrid, base', [
(CAR.HYUNDAI_TUCSON_4TH_GEN, False, 0x08),
(CAR.KIA_NIRO_HEV_2ND_GEN, True, 0x0A),
(CAR.HYUNDAI_SONATA_2024, False, 0x408),
(CAR.HYUNDAI_SONATA_HEV_2024, True, 0x40A),
(CAR.KIA_K4_2025, False, 0x408),
])
@pytest.mark.parametrize('alternate', [False, True])
@pytest.mark.parametrize('offset', [0, 4])
def test_camera_scc_wheel_choice_survives_alpha_long(identity, hybrid, base, alternate, offset):
fp = gen_empty_fingerprint()
fp[offset].update({0x35: 32, 0xA0: 24, 0xEA: 24, 0x175: 24, 0x130: 16})
fp[offset + 2].update({0x12A: 16, 0x1A0: 32})
fp[offset][0x1AA if alternate else 0x1CF] = 16 if alternate else 8
if hybrid:
fp[offset][0xFA] = 8
for alpha in (False, True):
cp = CarInterface.get_params(identity, fp, [], alpha, False, False)
assert cp.alphaLongitudinalAvailable and cp.openpilotLongitudinalControl == alpha
assert not CarInterface.startup_required(cp)
wheel = WheelFeature(SimpleNamespace(params=SimpleNamespace(get_bool=lambda key: key == 'AlwaysOnLateral'),
vehicle_params=lambda cp=cp: cp, configuration_vehicle=lambda: False,
configuration_longitudinal=lambda: False, longitudinal_available=lambda alpha=alpha: alpha,
authority=lambda _: True))
assert 'Toggle AOL' in wheel.choices('LKASButtonControl')
assert 'Toggle AOL' in wheel.choices('MainCruiseButtonControl')
if alpha:
config = cp.safetyConfigs[offset // 4]
assert config.safetyParam == base | (0x20 if alternate else 0) | 4
assert qualified_long(cp)
policy = policy_for(cp)
config.safetyParam |= policy.safety_param_addition
cp.alternativeExperience |= policy.alternative_experience_addition
assert config.safetyParam == base | (0x20 if alternate else 0) | 0x804
assert native_accepts_cp(cp, config.safetyModel.raw, config.safetyParam)
cp.alternativeExperience = 0
assert not qualified_long(cp, marked_only=True)
@@ -931,7 +931,7 @@ def test_ccnc_normal_camera_handover_requires_current_health_and_expires(failure
eps = packer.make_can_msg('MDPS', 0, {'COUNTER': tick, 'MDPS_LkaToiActvSta': int(tick >= 4)})
source.update([(clock[0], [eps, camera])])
owned = source.owns_display_status(tick >= 2, clock[0], healthy=True)
assert source.owns_ccnc_fault_status(clock[0], healthy=True, qualified_warning=owned) == owned
assert source.owns_ccnc_fault_status(clock[0], display_sample_ns=clock[0], healthy=True, qualified_warning=owned) == owned
assert owned
final_owned_ns = clock[0]
for tick in range(16, 23):
@@ -952,7 +952,7 @@ def test_ccnc_normal_camera_handover_requires_current_health_and_expires(failure
frames.append(camera)
source.update([(clock[0], frames)])
now = final_owned_ns - 1 if failure == 'backward' else -1 if failure == 'negative' else clock[0]
held = source.owns_ccnc_fault_status(now, healthy=failure != 'host_fault',
held = source.owns_ccnc_fault_status(now, display_sample_ns=clock[0], healthy=failure != 'host_fault',
qualified_warning=failure == 'stale_camera_qualified')
if failure == 'expired':
assert held == (clock[0] - final_owned_ns <= 50_000_000)
@@ -965,7 +965,29 @@ def test_ccnc_normal_camera_handover_requires_current_health_and_expires(failure
camera = template(packer, 2, tick)
eps = packer.make_can_msg('MDPS', 0, {'COUNTER': tick})
source.update([(clock[0], [eps, camera])])
assert not source.owns_ccnc_fault_status(clock[0], healthy=True, qualified_warning=False)
assert not source.owns_ccnc_fault_status(clock[0], display_sample_ns=clock[0], healthy=True, qualified_warning=False)
def test_ccnc_handover_uses_fresh_display_sample_time(clock):
packer = CANPacker(DBC[CAR.HYUNDAI_KONA_2ND_GEN][Bus.pt])
source = CANFDLfaStatus(2)
for tick in range(21):
clock[0] = 51_000_000_000 + tick * 10_000_000
camera = template(packer, 2, tick, warning=15 if 14 <= tick < 16 else 0)
eps = packer.make_can_msg('MDPS', 0, {'COUNTER': tick, 'MDPS_LkaToiActvSta': int(tick >= 4)})
source.update([(clock[0], [eps, camera])])
owned = source.owns_display_status(tick >= 2, clock[0], healthy=True)
if owned:
assert source.owns_ccnc_fault_status(clock[0], display_sample_ns=clock[0], healthy=True, qualified_warning=True)
assert not owned
now = clock[0] + 1_000_000
assert source.owns_ccnc_fault_status(now, display_sample_ns=clock[0] - 40_000_000, healthy=True)
assert not source.owns_ccnc_fault_status(now, display_sample_ns=clock[0] - 50_000_000, healthy=True)
assert not source.owns_ccnc_fault_status(now, display_sample_ns=source.ccnc_last_owned_ns - 1, healthy=True)
assert not source.owns_ccnc_fault_status(now, display_sample_ns=now, healthy=True)
assert not source.owns_ccnc_fault_status(now, display_sample_ns=now + 1, healthy=True)
assert not source.owns_ccnc_fault_status(now, display_sample_ns=clock[0] - 40_000_000, healthy=False)
@pytest.mark.parametrize('fault', range(1, 8))
@@ -12,6 +12,7 @@ from opendbc.car.hyundai.ecu_startup import Outcome, stock_copy
from opendbc.car.hyundai.interface import CarInterface
from opendbc.car.hyundai.ioniq6_handoff import TimestampedCanPacket
from opendbc.car.hyundai.generic_hda2_startup import GenericHDA2Startup, qualified
from openpilot.starpilot.ui.feature_settings_owner import FeatureSettingsOwner
from opendbc.car.hyundai.tests.test_generic_hda2_startup import FUEL_CASES
from opendbc.car.hyundai.values import CAR
from opendbc.safety.tests.libsafety import libsafety_py
@@ -183,7 +184,7 @@ def actual_card_lifecycle(identity, hybrid, alternate, gear, mode, aol):
assert {key: saved.get(key) for key in keys} == settings and not saved.get_bool("ControlsReady")
if mode == "rejected" and aol:
expected.safetyConfigs[0].safetyParam |= 0x800
elif mode == "sent" and aol and identity == CAR.KIA_SPORTAGE_5TH_GEN:
elif mode == "sent" and aol and identity not in (CAR.KIA_CARNIVAL_2025, CAR.KIA_CARNIVAL_HEV_4TH_GEN):
expected.safetyConfigs[0].safetyParam |= 0x800
expected.alternativeExperience = 32
assert card.CP.to_dict() == expected.to_dict()
@@ -195,6 +196,11 @@ def actual_card_lifecycle(identity, hybrid, alternate, gear, mode, aol):
assert commands == [b"\x10\x03", b"\x28\x83\x01"] and owner.keeper.running
assert owner.outcome is Outcome.SENT_UNCONFIRMED and not owner.restored
cp = card.CP
if aol and (mode == "rejected" or cp.alternativeExperience == 32):
features = FeatureSettingsOwner(saved, lambda _: True, vehicle_fingerprint=lambda: str(cp.carFingerprint), vehicle_params=lambda: cp)
page = features.snapshot('wheel', parked=True, system_long=True, lateral_context=True, metric=False)
row = next(row for row in page.rows if row.key == 'wheel:LKASButtonControl')
assert 'Toggle AOL' in row.choices
config = cp.safetyConfigs[0]
native.set_alternative_experience(cp.alternativeExperience)
assert native.set_safety_hooks(int(config.safetyModel.raw), int(config.safetyParam)) == 0
@@ -8,12 +8,15 @@ from opendbc.car.hyundai.values import CAR, HyundaiFlags
from openpilot.starpilot.car.hyundai.aol import independent_cruise_buttons_supported, native_accepts_cp, policy_for
def camera_long(offset, alpha=True):
CAMERA_LONG_CARS = (CAR.HYUNDAI_IONIQ_5, CAR.KIA_NIRO_EV_2ND_GEN)
def camera_long(offset, alpha=True, *, identity=CAR.HYUNDAI_IONIQ_5):
fp = gen_empty_fingerprint()
fp[offset].update({0x1CF: 8, 0x35: 32, 0x175: 24, 0xA0: 24, 0xEA: 24, 0x1BA: 24, 0x1E5: 16})
fp[offset + 2].update({0x12A: 16, 0x1A0: 32})
fp[offset + 1].update({0x110: 32, 0x100: 24})
cp = CarInterface.get_params(CAR.HYUNDAI_IONIQ_5, fp, [], alpha, False, False)
cp = CarInterface.get_params(identity, fp, [], alpha, False, False)
assert cp.openpilotLongitudinalControl and not cp.pcmCruise
assert cp.flags & HyundaiFlags.CANFD_CAMERA_SCC
assert not cp.flags & HyundaiFlags.CANFD_LKA_STEER_MSG
@@ -23,8 +26,9 @@ def camera_long(offset, alpha=True):
@pytest.mark.parametrize('offset', [0, 4])
def test_factory_ioniq5_camera_long_uses_existing_paired_axis_profile(offset):
cp = camera_long(offset)
@pytest.mark.parametrize('identity', CAMERA_LONG_CARS)
def test_factory_camera_long_uses_existing_paired_axis_profile(identity, offset):
cp = camera_long(offset, identity=identity)
before = cp.to_dict()
assert qualified_long(cp)
assert independent_cruise_buttons_supported(cp)
@@ -44,9 +48,10 @@ def test_factory_ioniq5_camera_long_uses_existing_paired_axis_profile(offset):
@pytest.mark.parametrize('offset', [0, 4])
@pytest.mark.parametrize('mutation', ['alternate_buttons', 'unknown_word', 'wrong_experience', 'passive', 'angle'])
def test_camera_long_extension_keeps_unrecognized_contracts_closed(offset, mutation):
cp = camera_long(offset)
@pytest.mark.parametrize('mutation', ['alternate_buttons', 'unknown_word', 'wrong_experience', 'passive', 'angle', 'hda2'])
@pytest.mark.parametrize('identity', CAMERA_LONG_CARS)
def test_camera_long_extension_keeps_unrecognized_contracts_closed(identity, offset, mutation):
cp = camera_long(offset, identity=identity)
owner = config_index(cp)
cp.safetyConfigs[owner].safetyParam = 0x80D
cp.alternativeExperience = 32
@@ -59,18 +64,23 @@ def test_camera_long_extension_keeps_unrecognized_contracts_closed(offset, mutat
cp.alternativeExperience = 0
elif mutation == 'passive':
cp.passive = True
else:
elif mutation == 'angle':
cp.flags |= int(HyundaiFlags.CANFD_ANGLE_STEERING)
assert not qualified_long(cp, marked_only=True)
elif mutation == 'hda2':
cp.flags = (cp.flags & ~int(HyundaiFlags.CANFD_CAMERA_SCC)) | int(HyundaiFlags.CANFD_LKA_STEER_MSG)
cp.safetyConfigs[owner].safetyParam = 0x815
cp.alphaLongitudinalAvailable = False
assert qualified_long(cp, marked_only=True) == (mutation == 'hda2' and identity == CAR.HYUNDAI_IONIQ_5)
@pytest.mark.parametrize('offset', [0, 4])
@pytest.mark.parametrize('button', ['lkas', 'mainCruise'])
def test_default_physical_button_arms_and_brake_cancel_keep_intent(offset, button):
@pytest.mark.parametrize('identity', CAMERA_LONG_CARS)
def test_default_physical_button_arms_and_brake_cancel_keep_intent(identity, offset, button):
from openpilot.starpilot.aol.intent import AolSettings
from openpilot.starpilot.car.hyundai.aol import create_intent
cp = camera_long(offset)
cp = camera_long(offset, identity=identity)
cp.safetyConfigs[config_index(cp)].safetyParam = 0x80D
cp.alternativeExperience = 32
settings = AolSettings(enabled=True, pause_brake_mps=0.0, lkas_action=0, main_action=0,
@@ -96,7 +106,7 @@ def test_default_physical_button_arms_and_brake_cancel_keep_intent(offset, butto
assert not intent.output(cs)[0]
@pytest.mark.parametrize('identity', [CAR.HYUNDAI_KONA_EV_2ND_GEN, CAR.HYUNDAI_IONIQ_5_N, CAR.KIA_NIRO_EV_2ND_GEN])
@pytest.mark.parametrize('identity', [CAR.HYUNDAI_KONA_EV_2ND_GEN, CAR.HYUNDAI_IONIQ_5_N, CAR.KIA_NIRO_HEV_2ND_GEN])
def test_camera_extension_does_not_admit_unqualified_identities(identity):
cp = camera_long(0)
cp.carFingerprint = identity
@@ -108,15 +118,17 @@ def test_camera_extension_does_not_admit_unqualified_identities(identity):
@pytest.mark.parametrize('offset', [0, 4])
@pytest.mark.parametrize('enabled', [False, True])
def test_actual_card_marks_camera_owner_with_recorded_default_buttons(offset, enabled):
@pytest.mark.parametrize('identity', CAMERA_LONG_CARS)
def test_actual_card_marks_camera_owner_with_recorded_default_buttons(identity, offset, enabled):
import os
from unittest.mock import patch
from opendbc.car.hyundai.radar_interface import RadarInterface
from openpilot.common.params import Params
from openpilot.common.prefix import OpenpilotPrefix
from openpilot.selfdrive.car.card import Car
from openpilot.starpilot.ui.feature_settings_owner import FeatureSettingsOwner
cp = camera_long(offset)
cp = camera_long(offset, identity=identity)
with OpenpilotPrefix(), patch.dict(os.environ, {'SIMULATION': '1'}):
saved = Params()
saved.put_bool('OpenpilotEnabledToggle', True, block=True)
@@ -135,6 +147,11 @@ def test_actual_card_marks_camera_owner_with_recorded_default_buttons(offset, en
assert qualified_long(published, marked_only=enabled)
assert config_index(published) == offset // 4
assert not CarInterface.startup_required(published)
features = FeatureSettingsOwner(saved, lambda _: True, vehicle_fingerprint=lambda: str(published.carFingerprint),
vehicle_params=lambda: published)
page = features.snapshot('wheel', parked=True, system_long=True, lateral_context=True, metric=False)
row = next(row for row in page.rows if row.key == 'wheel:LKASButtonControl')
assert 'Toggle AOL' in row.choices
assert card.aol_qualified == enabled
if enabled:
assert card.aol_card_intent.explicit_latch and card.aol_card_intent.independent_cruise_buttons
@@ -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()
@@ -0,0 +1,16 @@
# Legacy Mazda powertrain and camera traffic selects diagnostic wiring only.
# Identification still requires the normal live firmware/CAN match.
NORMAL_BUS0_LAYOUT = {(0, 0x09D), (0, 0x165), (0, 0x202),
(0, 0x21C), (0, 0x240), (2, 0x243)}
def normal_bus0_topology(packets):
seen = set()
for packet in packets:
for frame in packet:
key = (frame.src, frame.address)
if key in NORMAL_BUS0_LAYOUT:
if len(frame.dat) != 8:
return False
seen.add(key)
return seen == NORMAL_BUS0_LAYOUT
@@ -78,6 +78,7 @@ FW_VERSIONS = {
b'PX2G-188K2-D\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00',
b'PX2H-188K2-B\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00',
b'PX2H-188K2-D\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00',
b'PX2H-188K2-E\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00',
b'PX2H-188K2-G\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00',
b'PX2K-188K2-B\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00',
b'PX38-188K2-B\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00',
+18 -2
View File
@@ -7,6 +7,20 @@ from opendbc.car.mazda.carstate import CarState
from opendbc.car.mazda.values import CAR, LKAS_LIMITS
_CX5_EPS_SWAP_FW = {
('engine', 0x7E0): b'PX2H-188K2-E'.ljust(24, b'\x00'),
('transmission', 0x7E1): b'PYB2-21PS1-G'.ljust(24, b'\x00'),
('eps', 0x730): b'KSD5-3210X-C-00'.ljust(24, b'\x00'),
}
def _has_cx5_eps_swap(car_fw):
observed = {(str(fw.ecu), fw.address, bytes(fw.fwVersion)) for fw in car_fw
if fw.brand == 'mazda' and fw.bus == 0 and fw.subAddress == 0 and not fw.logging and
(str(fw.ecu), fw.address) in _CX5_EPS_SWAP_FW}
return observed == {(ecu, address, version) for (ecu, address), version in _CX5_EPS_SWAP_FW.items()}
class CarInterface(CarInterfaceBase):
CarState = CarState
CarController = CarController
@@ -18,14 +32,16 @@ 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
CarInterfaceBase.configure_torque_tune(candidate, ret.lateralTuning)
if candidate not in (CAR.MAZDA_CX5_2022,):
eps_swap = candidate == CAR.MAZDA_CX5 and _has_cx5_eps_swap(car_fw)
# Both low-speed profiles still use the EPS LKAS_BLOCK signal in CarState.
if candidate != CAR.MAZDA_CX5_2022 and not eps_swap:
ret.minSteerSpeed = LKAS_LIMITS.DISABLE_SPEED * CV.KPH_TO_MS
ret.centerToFront = ret.wheelbase * 0.41
+1 -1
View File
@@ -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):
@@ -0,0 +1,62 @@
import pytest
from opendbc.can import CANPacker
from opendbc.car import gen_empty_fingerprint, structs
from opendbc.car.mazda.interface import CarInterface
from opendbc.car.mazda.stock_aol import temporary_restriction
from opendbc.car.mazda.tests.test_stock_startup import complete_frames
from opendbc.car.mazda.values import CAR
def recorded_firmware():
return [structs.CarParams.CarFw(ecu=ecu, address=address, brand='mazda', fwVersion=part.ljust(24, b'\x00'))
for ecu, address, part in (
('engine', 0x7E0, b'PX2H-188K2-E'),
('transmission', 0x7E1, b'PYB2-21PS1-G'),
('eps', 0x730, b'KSD5-3210X-C-00'),
)]
@pytest.mark.parametrize('profile,defect,expected', [
(CAR.MAZDA_CX5, None, 0.),
(CAR.MAZDA_CX5, 'missing_eps', 12.5),
(CAR.MAZDA_CX5, 'missing_engine', 12.5),
(CAR.MAZDA_CX5, 'wrong_transmission', 12.5),
(CAR.MAZDA_CX5, 'wrong_eps_bus', 12.5),
(CAR.MAZDA_CX5, 'conflicting_eps', 12.5),
(CAR.MAZDA_CX5_2022, 'no_fw', 0.),
(CAR.MAZDA_CX9_2021, None, 12.5),
])
def test_low_speed_eligibility_is_limited_to_verified_cx5(profile, defect, expected):
fw = recorded_firmware()
if defect == 'missing_eps':
del fw[2]
elif defect == 'missing_engine':
del fw[0]
elif defect == 'wrong_transmission':
fw[1].fwVersion = b'unknown'
elif defect == 'wrong_eps_bus':
fw[2].bus = 1
elif defect == 'conflicting_eps':
fw.append(structs.CarParams.CarFw(ecu='eps', address=0x730, brand='mazda', fwVersion=b'unknown'))
elif defect == 'no_fw':
fw.clear()
cp = CarInterface.get_params(profile, gen_empty_fingerprint(), fw, False, False, False)
assert cp.minSteerSpeed == expected
assert cp.pcmCruise and not cp.openpilotLongitudinalControl and not cp.dashcamOnly
assert [(str(s.safetyModel), s.safetyParam) for s in cp.safetyConfigs] == [('mazda', 0)]
def test_eps_readiness_still_blocks_lateral_at_low_speed():
cp = CarInterface.get_params(CAR.MAZDA_CX5, gen_empty_fingerprint(), recorded_firmware(), False, False, False)
cp.alternativeExperience = 32
ci = CarInterface(cp)
packer = CANPacker('mazda_2017')
ci.update([(10_000_000, complete_frames(packer, cp, 1, main=True, speed_kph=16., temporary=True))])
for tick, (speed, blocked, restricted) in enumerate(((16., True, True), (16., False, False),
(16., True, True), (0., False, True)), 2):
frames = complete_frames(packer, cp, tick, main=True, speed_kph=speed, temporary=blocked)
state = ci.update([(tick * 10_000_000, frames)])
assert state.canValid and not state.canTimeout
assert state.steerFaultTemporary == blocked
assert temporary_restriction(cp, state) == restricted
@@ -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)
@@ -0,0 +1,51 @@
from unittest.mock import patch
import pytest
from opendbc.car.can_definitions import CanData
from opendbc.car.car_helpers import fingerprint
from opendbc.car.mazda.values import CAR
from opendbc.car.structs import CarParams
from opendbc.car.vin import VIN_UNKNOWN
def legacy_frames():
return [CanData(address, bytes(8), bus) for bus, address in (
(0, 0x09D), (0, 0x165), (0, 0x202), (0, 0x21C), (0, 0x240), (2, 0x243),
)]
@pytest.mark.parametrize('layout', ['normal', 'missing_camera', 'camera_echo', 'wrong_dlc'])
@pytest.mark.parametrize('observed_engine', [True, False])
def test_legacy_mazda_discovery_selects_normal_wiring_and_requires_firmware(layout, observed_engine):
frames = legacy_frames()
if layout != 'normal':
frame = frames.pop()
if layout == 'camera_echo':
frames.append(CanData(frame.address, frame.dat, frame.src + 128))
if layout == 'wrong_dlc':
frames.extend((frame, CanData(frame.address, frame.dat[:-1], frame.src)))
firmware = [CarParams.CarFw(address=address, brand='mazda', fwVersion=version.ljust(24, b'\0')) for address, version in (
(0x7E1, b'PYB2-21PS1-G'), (0x730, b'KSD5-3210X-C-00'),
)]
if observed_engine:
firmware.append(CarParams.CarFw(address=0x7E0, brand='mazda', fwVersion=b'PX2H-188K2-E'.ljust(24, b'\0')))
mux = []
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=firmware) as fw, \
patch('opendbc.car.car_helpers.get_present_ecus', return_value=set()), \
patch('opendbc.car.car_helpers.get_fw_versions_ordered', return_value=[]), \
patch('opendbc.car.car_helpers.can_fingerprint', return_value=(None, {})), \
patch('opendbc.car.car_helpers.time.sleep'):
result = fingerprint(lambda **kwargs: [frames], lambda _: None, mux.append, None)
if layout == 'normal':
assert mux and not any(mux)
assert vin.call_args.args[2] == (0,)
assert fw.call_args.kwargs == {'query_brand': 'mazda', 'normal_bus_only': True}
assert result[0] == (CAR.MAZDA_CX5 if observed_engine else None)
else:
fw.assert_not_called()
assert result[0] is None
@@ -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
+20 -7
View File
@@ -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):
+157 -25
View File
@@ -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
+81 -6
View File
@@ -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"])
+4 -2
View File
@@ -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}")
+7 -2
View File
@@ -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))
+113 -29
View File
@@ -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
+1
View File
@@ -29,6 +29,7 @@ unrecorded_route_gaps = {
VOLVO.VOLVO_XC40_RECHARGE: "volvo/tests/test_cma.py",
VOLVO.VOLVO_S60_RECHARGE: "volvo/tests/test_cma.py",
VOLVO.POLESTAR_2: "volvo/tests/test_cma.py",
VOLVO.VOLVO_V60: "volvo/tests/test_eucd.py",
}
# FIXME: add routes for these cars
@@ -9,6 +9,8 @@ from opendbc.car.interfaces import CarInterfaceBase, get_interface_attr
from opendbc.car.values import PLATFORMS
from opendbc.car.volvo.cma_carcontroller import CarControllerCMA
from opendbc.car.volvo.cma_carstate import CarStateCMA
from opendbc.car.volvo.eucd_carcontroller import CarControllerEUCD
from opendbc.car.volvo.eucd_carstate import CarStateEUCD
from opendbc.car.volvo.values import CAR as VOLVO
from opendbc.testing import Fuzzy, fuzzy_test
@@ -118,6 +120,9 @@ def _make_optional_hardware_test(car_name):
if car_name in (VOLVO.VOLVO_XC40_RECHARGE, VOLVO.VOLVO_S60_RECHARGE, VOLVO.POLESTAR_2):
self.assertIsInstance(interface.CS, CarStateCMA)
self.assertIsInstance(interface.CC, CarControllerCMA)
elif car_name == VOLVO.VOLVO_V60:
self.assertIsInstance(interface.CS, CarStateEUCD)
self.assertIsInstance(interface.CC, CarControllerEUCD)
else:
self.assertIsInstance(interface.CS, interface_type.CarState)
self.assertIsInstance(interface.CC, interface_type.CarController)
@@ -337,7 +337,7 @@ class TestFwFingerprintTiming(unittest.TestCase):
assert first.whitelist_ecus == second.whitelist_ecus
def test_fw_query_timing(self):
total_ref_time = 8.4
total_ref_time = 8.5
brand_ref_times = {
'gm': 1.0,
'body': 0.1,
@@ -355,7 +355,7 @@ class TestFwFingerprintTiming(unittest.TestCase):
'rivian': 0.3,
'psa': 0.1,
'mg': 0.1,
'volvo': 0.0, # Current Volvo FwQueryConfig has no requests.
'volvo': 0.1,
}
total_times = 0.0
@@ -20,7 +20,7 @@ class TestRoutes(unittest.TestCase):
def test_explicit_unrecorded_configuration_gaps(self):
self.assertEqual(set(unrecorded_route_gaps), {
GM.CHEVROLET_VOLT_CC, GM.CHEVROLET_MALIBU_HYBRID_CC, TOYOTA.TOYOTA_PRIUS_RETROFIT, TESLA.TESLA_MODEL_S_HW1,
VOLVO.VOLVO_XC40_RECHARGE, VOLVO.VOLVO_S60_RECHARGE, VOLVO.POLESTAR_2,
VOLVO.VOLVO_XC40_RECHARGE, VOLVO.VOLVO_S60_RECHARGE, VOLVO.POLESTAR_2, VOLVO.VOLVO_V60,
})
self.assertFalse(set(unrecorded_route_gaps) & {route.car_model for route in routes})
self.assertTrue(set(unrecorded_route_gaps) <= set(non_tested_cars))
@@ -169,6 +169,7 @@ legend = ["LAT_ACCEL_FACTOR", "MAX_LAT_ACCEL_MEASURED", "FRICTION"]
"TESLA_MODEL_S_HW1" = [nan, 2.5, nan]
"VOLVO_V40" = [1.5, 1.5, 0.1]
"VOLVO_V60" = [1.5, 1.5, 0.1]
"CHEVROLET_SUBURBAN" = [1.2, 2.5, 0.26]
"CHEVROLET_MALIBU_CC" = [1.85, 1.85, 0.075]
+2 -1
View File
@@ -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
@@ -10,3 +10,14 @@ NORMAL_BUS_LAYOUT.update({(1, address): 8 for address in (0x23, 0x35, 0x70, 0x11
def normal_bus_topology(fingerprint):
return all(fingerprint.get(bus, {}).get(address) == size
for (bus, address), size in NORMAL_BUS_LAYOUT.items())
# V60 (EUCD): camera FSM0/FSM1/FSM3 and the ECM's EngineData, mirrored on the PT and camera buses (route 00000004).
# Its engine FW answers on bus 0: the all-brand OBD scan switched bus 1, the ESR radar's, into a CAN2 error and
# interrupt storm that left the panda's interruptRateCan2 fault on for the whole drive.
V60_BUS_LAYOUT = {(bus, address): 8 for bus in (0, 2) for address in (0x51, 0x12A, 0x260, 0x270)}
def v60_bus_topology(fingerprint):
return all(fingerprint.get(bus, {}).get(address) == size
for (bus, address), size in V60_BUS_LAYOUT.items())
+212
View File
@@ -0,0 +1,212 @@
import numpy as np
from opendbc.car.volvo.eucd_params import CANBUS, CarControllerEUCDParams, EcmAccState, LongMode
def create_eucd_button_msg(packer, resume=False, cancel=False, set_plus=False, minus=False, bus=0):
msg = {
"ACCOnOffBtn": cancel,
"ACCOnOffBtnInv": not cancel,
"ACCResumeBtn": resume,
"ACCResumeBtnInv": not resume,
"ACCSetBtn": set_plus,
"ACCSetBtnInv": not set_plus,
"ACCMinusBtn": minus,
"ACCMinusBtnInv": not minus,
}
return packer.make_can_msg("CCButtons", bus, msg)
def create_eucd_lkas_state_msg(packer, steering_angle: float, stock_values: dict):
# Servo state to the camera, LKA torque/active cleared
msg = {
"LKATorque": 0,
"SteeringAngleServo": steering_angle,
"byte0": stock_values["byte0"],
"byte4": stock_values["byte4"],
"byte7": stock_values["byte7"],
"LKAActive": int(stock_values["LKAActive"]) & 0xF5,
"EPSTorque": stock_values["EPSTorque"],
}
return packer.make_can_msg("PSCM1", 2, msg)
def calculate_eucd_lka_checksum(dat: bytes) -> int:
steer_angle_request = ((dat[3] & 0x3F) << 8) + dat[4]
steering_direction_request = dat[5] & 0x03
trqlim = dat[2]
s = (trqlim + steering_direction_request + steer_angle_request + (steer_angle_request >> 8)) & 0xFF
return s ^ 0xFF
def create_eucd_lka_msg(packer, apply_steer: float, steer_direction: int):
values = {
"LKAAngleReq": apply_steer,
"LKASteerDirection": steer_direction,
"TrqLim": 0,
"SET_X_22": 0x25,
"SET_X_02": 0,
"SET_X_10": 0x10,
"SET_X_A4": 0xa7,
}
# Checksum
dat = packer.make_can_msg("FSM2", 0, values)[1]
values["Checksum"] = calculate_eucd_lka_checksum(dat)
return packer.make_can_msg("FSM2", 0, values)
def eucd_brake_thresholds(v_ego: float | None) -> tuple[float, float]:
"""BRAKE enter and exit accel at this speed; None is the highway's."""
CCP = CarControllerEUCDParams
if v_ego is None:
return CCP.EUCD_BRAKE_ENTER, CCP.EUCD_BRAKE_EXIT
enter = float(np.interp(v_ego, CCP.EUCD_BRAKE_ENTER_BP, CCP.EUCD_BRAKE_ENTER_V))
return enter, min(enter + CCP.EUCD_BRAKE_HYSTERESIS, 0.)
def eucd_next_long_mode(mode: LongMode, accel: float, brake_offset: float = 0., v_ego: float | None = None) -> LongMode:
# brake_offset shifts the BRAKE thresholds by the slope
CCP = CarControllerEUCDParams
brake_enter, brake_exit = eucd_brake_thresholds(v_ego)
if mode == LongMode.BRAKE:
if accel <= brake_exit + brake_offset:
return LongMode.BRAKE
elif mode == LongMode.DRIVE:
if accel >= CCP.EUCD_DRIVE_EXIT:
return LongMode.DRIVE
enter_offset = brake_offset * (1. + CCP.EUCD_UPHILL_BRAKE_ENTER_EXTRA) if brake_offset < 0. else brake_offset
if accel < brake_enter + enter_offset:
return LongMode.BRAKE
if accel > CCP.EUCD_DRIVE_ENTER:
return LongMode.DRIVE
return LongMode.COAST
def eucd_fsm3_traction(accel: float, mode: LongMode) -> int:
# FSM3 ACC_TractionRequest
if mode == LongMode.BRAKE:
return 0
if mode == LongMode.DRIVE:
gain, offset = CarControllerEUCDParams.EUCD_TRACTION_DRIVE
return min(max(round(gain * accel + offset), 0), 255)
gain, offset = CarControllerEUCDParams.EUCD_TRACTION_COAST
return min(max(round(gain * accel + offset), -127), -1) & 0xFF
def _eucd_copy(stock, skip=()):
# Stock frame signals, without the ones overlapping others
return {k: v for k, v in stock.items() if k not in skip}
def create_eucd_longitudinal(packer, stock_fsm3, accel, acc_check, mode: LongMode | None = None, standstill: bool | None = None):
# Camera FSM3 with OP's accel, ACC_Check, mode and traction; standstill set = OP's stop to 0
values = _eucd_copy(stock_fsm3)
values |= {
"ACC_AccelerationRequest": accel,
"ACC_Check": acc_check,
}
if standstill is not None:
values["ACC_Standstill"] = int(standstill)
values["ACC_NoTargetCancel"] = 0
if mode is not None:
values["ACC_Mode"] = int(mode)
values["ACC_TractionRequest"] = eucd_fsm3_traction(accel, mode)
return packer.make_can_msg("FSM3", 0, values)
def eucd_fsm4_brake_value(accel: float, brake: bool) -> int:
# FSM4 brake word: 0x8000 | brake flag 0x4000 | 14-bit target
CCP = CarControllerEUCDParams
if brake:
lo, hi = CCP.EUCD_FSM4_BRAKE_ACCEL_RANGE
return 0xC000 | int(round(CCP.EUCD_FSM4_BRAKE_ZERO + CCP.EUCD_FSM4_BRAKE_GAIN * min(max(accel, lo), hi)))
return 0x8000 | int(round(float(np.interp(accel, CCP.EUCD_FSM4_NO_BRAKE_ACCEL_BP, CCP.EUCD_FSM4_NO_BRAKE_VALUE_V))))
def create_eucd_fsm4(packer, stock_fsm4, accel: float, mode: LongMode | None = None):
# Camera FSM4; brake flag and target follow OP's accel when either side brakes
values = _eucd_copy(stock_fsm4)
op_brake = mode == LongMode.BRAKE
cam_brake = bool(stock_fsm4["ACC_BrakeRequest"])
if mode is not None and (op_brake or cam_brake):
value = eucd_fsm4_brake_value(accel, op_brake)
values["Byte_5_b7"] = (value >> 15) & 1
values["ACC_BrakeRequest"] = (value >> 14) & 1
values["ACC_BrakeTarget"] = value & 0x3FFF
return packer.make_can_msg("FSM4", 0, values)
def create_eucd_fsm0(packer, stock_fsm0, ecm_engaged: bool):
# Camera FSM0, never ACC enabled without the ECM engaged
values = _eucd_copy(stock_fsm0, skip=("ACC_BrakeAlert",))
if not ecm_engaged:
values["ACC_Enabled"] = 0
return packer.make_can_msg("FSM0", 0, values)
def create_eucd_cam_wheel_status(packer, stock_wheel_rear, standby: bool):
# WheelRear to the camera; standby: no ACC brake request, applied brake nor hold (seen in standby it latches FC, routes 886/888)
values = _eucd_copy(stock_wheel_rear, skip=("WhlSpdRR", "WhlSpdLR"))
if standby:
values |= {"BrakeReqActive": 0, "ACC_BrakeApplied": 0, "StandstillHold": 0}
return packer.make_can_msg("WheelRear", CANBUS.cam, values)
def create_eucd_cam_brake_request_ack(packer, stock_brake_req_ack, standby: bool):
# BrakeReqAck to the camera; standby: no brake ack (active low) nor hold
values = _eucd_copy(stock_brake_req_ack)
if standby:
values |= {"BrakeReqNotAck": 1, "StandstillHold": 0}
return packer.make_can_msg("BrakeReqAck", CANBUS.cam, values)
def create_eucd_cam_button(packer, stock_ccbuttons, standby: bool):
# CEM's CCButtons to the camera; standby: Set, Minus and Resume shown released, or the camera would engage its ACC
values = _eucd_copy(stock_ccbuttons)
if standby:
values |= {"ACCSetBtn": 0, "ACCSetBtnInv": 1, "ACCMinusBtn": 0, "ACCMinusBtnInv": 1, "ACCResumeBtn": 0, "ACCResumeBtnInv": 1}
return packer.make_can_msg("CCButtons", CANBUS.cam, values)
def create_eucd_resume_button(packer, stock_ccbuttons):
# CEM's CCButtons to the ECM with Resume pressed, the other bytes as the CEM's
values = _eucd_copy(stock_ccbuttons)
values |= {"ACCResumeBtn": 1, "ACCResumeBtnInv": 0}
return packer.make_can_msg("CCButtons", CANBUS.pt, values)
def create_eucd_cam_engine_data(packer, stock_engine_data, show_standby: bool):
# EngineData to the camera; show_standby: ECM engaged shown as standby (driver cancelled), as in route 881
values = _eucd_copy(stock_engine_data)
if show_standby and int(values["ACC_State_ECM"]) == EcmAccState.ENGAGED:
values["ACC_State_ECM"] = EcmAccState.STANDBY
values["Byte_2"] = int(values["Byte_2"]) & ~0x20 # E7 -> C7
return packer.make_can_msg("EngineData", CANBUS.cam, values)
def create_eucd_cam_acc_hold(packer, stock_acc_hold, show_standby: bool):
# 0x325 to the camera; show_standby: no ACC engaged (C4) nor ACC standstill hold (87), as standby (84)
values = _eucd_copy(stock_acc_hold)
if show_standby:
values |= {"ACC_Engaged": 0, "ACC_StandstillHold": 0}
return packer.make_can_msg("AccHold", CANBUS.cam, values)
def create_eucd_cam_brake_hold(packer, stock_brake_hold, frozen_b0: int | None):
# 0x1FF to the camera; b0 held while stopped (its 0x70 -> 0xD0 fires the camera's brake alert)
values = _eucd_copy(stock_brake_hold)
if frozen_b0 is not None:
values["Byte_0"] = frozen_b0
return packer.make_can_msg("BrakeHold", CANBUS.cam, values)
def create_eucd_radar(packer, stock_fsm1, mode: LongMode | None = None):
# Camera FSM1; ACC_Braking follows OP braking
values = _eucd_copy(stock_fsm1)
if mode is not None:
values["ACC_Braking"] = 1 if mode == LongMode.BRAKE else 0
return packer.make_can_msg("FSM1", 0, values)
@@ -0,0 +1,378 @@
"""Volvo V60 (EUCD) controller; with OP's long on, OP owns the ECM and the camera's ACC is shown standby."""
import math
from opendbc.can.packer import CANPacker
from opendbc.car import Bus, DT_CTRL
from opendbc.car.interfaces import CarControllerBase
from opendbc.car.lateral import apply_std_steer_angle_limits
from opendbc.car.volvo.eucd_can import (create_eucd_button_msg, create_eucd_lka_msg, create_eucd_lkas_state_msg, create_eucd_longitudinal,
create_eucd_fsm0, create_eucd_fsm4, create_eucd_radar, create_eucd_cam_wheel_status,
create_eucd_cam_brake_request_ack, create_eucd_cam_brake_hold, create_eucd_cam_engine_data,
create_eucd_resume_button, create_eucd_cam_acc_hold, create_eucd_cam_button, eucd_fsm4_brake_value,
eucd_next_long_mode)
from opendbc.car.volvo.eucd_params import CarControllerEUCDParams, LongMode, SteerDirection
def eucd_cam_clean(CS) -> bool:
"""Camera engaged with no cancel nor abort: its frames can be the ECM's templates."""
fsm3 = CS.eucd_stock_FSM3
if fsm3["ACC_NoTargetCancel"] or int(fsm3["Byte_6"]):
return False
if any(f["ACC_AbortCode"] or not f["ACC_Enabled"] for f in CS.eucd_stock_FSM0_frames):
return False
return not any(int(f["Byte_2"]) == 0xFC for f in CS.eucd_stock_FSM4_frames)
class CarControllerEUCD(CarControllerBase):
def __init__(self, dbc_names, CP):
super().__init__(dbc_names, CP)
self.packer = CANPacker(dbc_names[Bus.pt])
self.eucd_apply_steer_prev = 0
self.eucd_apply_steer_dir_prev = SteerDirection.NONE
self.eucd_latActive_prev = False
self.eucd_steer_blocked = False
self.eucd_steer_blocked_cnt = 0
self.eucd_steer_dir_bf_block = SteerDirection.NONE
# Resume (SNG)
self.eucd_last_resume_frame = 0
self.eucd_distance = 0
self.eucd_waiting = False
self.eucd_sng_count = 0
self.eucd_op_resume_frames = 0
self.eucd_sng_ack_frames = 0
self.eucd_resume_hold_frames = 0 # Resume held to the ECM, frames left
self.eucd_last_ccbuttons = None # CEM's last CCButtons, copied for the Resume
# Longitudinal
self.eucd_next_long_tx_nanos = 0
self.eucd_long_mode = LongMode.COAST
self.eucd_accel = 0.0
self.eucd_own = False # OP owns the ECM with the camera's templates, the camera shown ACC standby
self.eucd_exit_standby_frames = 0 # OP's long ended with the ECM still engaged: camera still shown standby
self.eucd_tpl_fsm0: dict[int, dict] = {} # camera's clean frames: FSM0 by Byte_0, FSM3 data/type, FSM4
self.eucd_tpl_fsm3: dict[str, dict] = {}
self.eucd_tpl_fsm4: dict | None = None
self.eucd_brake_hold_b0: int | None = None
# OP's stop to 0 (lead, red light, stop sign), as the camera's (route 807)
self.eucd_driver_gas = False # driver on the gas: OP's long off, the ECM kept engaged with no accel nor brake
self.eucd_stopped_frames = 0
self.eucd_car_hold_frames = 0
self.eucd_stopping = False # FSM4 b1 F9
self.eucd_holding = False # the car holds the stop: brake request released
self.eucd_standstill = False # FSM3 ACC_Standstill to the ECM, and the cruise standstill carstate reports
self.eucd_driving_off = False # resume sent, standstill released
self.eucd_drive_off_request = False # set with the resume burst, taken on the next frame
self.eucd_drive_off_frames = 0
self.eucd_drive_off_moved = False
def update(self, CC, CS, now_nanos):
actuators = CC.actuators
can_sends = []
if CC.cruiseControl.cancel and CS.out.vEgo > CarControllerEUCDParams.EUCD_MIN_STEER_SPEED and not CS.out.brakePressed:
can_sends.append(create_eucd_button_msg(self.packer, cancel=True))
if self.frame % 2 == 0:
can_sends += self._eucd_lateral(CC, CS)
self._eucd_ownership(CC, CS)
# Carstate takes the ACC standstill from OP while it owns the ECM
CS.eucd_op_owns_ecm = self.eucd_own
CS.eucd_op_standstill = self.eucd_standstill
self._eucd_resume_buttons(CC, CS, can_sends)
for stock_fsm0 in CS.eucd_stock_FSM0_frames:
can_sends.append(create_eucd_fsm0(self.packer, self._eucd_fsm0(stock_fsm0, CC.hudControl.leadVisible), CS.eucd_ecm_acc_engaged))
if now_nanos >= self.eucd_next_long_tx_nanos:
period = int(CarControllerEUCDParams.EUCD_LONG_TX_PERIOD * 1e9)
next_tx = self.eucd_next_long_tx_nanos + period
if self.eucd_next_long_tx_nanos == 0 or next_tx <= now_nanos:
next_tx = now_nanos + period
self.eucd_next_long_tx_nanos = next_tx
can_sends += self._eucd_longitudinal(CC, CS)
can_sends += self._eucd_relay_fsm4(CS)
can_sends += self._eucd_relay_to_camera(CS)
new_actuators = actuators.as_builder()
new_actuators.steeringAngleDeg = self.eucd_apply_steer_prev
if CC.longActive:
new_actuators.accel = self.eucd_accel
self.frame += 1
return new_actuators, can_sends
def _eucd_lateral(self, CC, CS):
"""FSM2 steering request and PSCM1 servo state to the camera, 50 Hz."""
CCP = CarControllerEUCDParams
actuators = CC.actuators
if CC.latActive and CS.out.vEgo > CCP.EUCD_MIN_STEER_SPEED:
apply_steer = apply_std_steer_angle_limits(
actuators.steeringAngleDeg, self.eucd_apply_steer_prev, CS.out.vEgoRaw,
CS.out.steeringAngleDeg, CC.latActive, CCP.EUCD_ANGLE_LIMITS
)
apply_steer_dir = SteerDirection.LEFT if apply_steer > 0 else SteerDirection.RIGHT
error = CS.out.steeringAngleDeg - apply_steer
error_with_deadzone = 0 if abs(error) < CCP.EUCD_DEADZONE else error
if not self.eucd_latActive_prev:
self.eucd_apply_steer_dir_prev = apply_steer_dir
# Block direction flips until the servo catches up
if self.eucd_steer_blocked:
if (apply_steer_dir == self.eucd_steer_dir_bf_block) or (self.eucd_steer_blocked_cnt <= 0) or (error_with_deadzone == 0):
self.eucd_steer_blocked = False
else:
if apply_steer_dir != self.eucd_apply_steer_dir_prev and error_with_deadzone != 0:
self.eucd_steer_blocked = True
self.eucd_steer_blocked_cnt = CCP.EUCD_BLOCK_LEN
self.eucd_steer_dir_bf_block = self.eucd_apply_steer_dir_prev
if self.eucd_steer_blocked:
self.eucd_steer_blocked_cnt -= 1
apply_steer_dir = SteerDirection.NONE
elif error_with_deadzone == 0:
apply_steer_dir = self.eucd_apply_steer_dir_prev
else:
apply_steer = 0
apply_steer_dir = SteerDirection.NONE
self.eucd_apply_steer_prev = apply_steer
self.eucd_apply_steer_dir_prev = apply_steer_dir
self.eucd_latActive_prev = CC.latActive
return [
create_eucd_lka_msg(self.packer, apply_steer, int(apply_steer_dir)),
# Servo state to the camera
create_eucd_lkas_state_msg(self.packer, CS.out.steeringAngleDeg, CS.eucd_pscm_stock_values),
]
def _eucd_resume_buttons(self, CC, CS, can_sends):
"""Resume burst when the lead moves away."""
CCP = CarControllerEUCDParams
at_standstill = CS.out.cruiseState.enabled and CS.out.cruiseState.standstill and CS.out.vEgo < 0.01
self.eucd_op_resume_frames = self.eucd_op_resume_frames + 1 if CC.cruiseControl.resume else 0
op_resume = self.eucd_op_resume_frames * DT_CTRL >= CCP.EUCD_SNG_OP_RESUME_TIME
if (self.frame - self.eucd_last_resume_frame) * DT_CTRL > CCP.EUCD_RESUME_BURST_INTERVAL:
if at_standstill and not self.eucd_waiting:
self.eucd_distance = CS.eucd_acc_distance
self.eucd_waiting = True
self.eucd_sng_count = 0
# In OP's stop only the planner's resume drives off (as Ford/Toyota), not the camera's distance jitter (route 884)
lead_moved = CS.eucd_acc_distance > self.eucd_distance and not self.eucd_own
# The driver's Resume also drives off OP's stop: the ECM takes it, but held in standstill it stays (route 8ab, 436 s)
driver_resume = CS.eucd_driver_resume and self.eucd_own
drive_off = lead_moved or op_resume or driver_resume or self.eucd_driver_gas
# The ECM takes the driver's Resume at once, so OP follows it without waiting for its ready (route 38, 42 s)
if at_standstill and self.eucd_waiting and drive_off and (driver_resume or self._eucd_drive_off_ready(CS)):
self.eucd_resume_hold_frames = CCP.EUCD_RESUME_HOLD_FRAMES
if self.eucd_sng_count == 0:
self.eucd_sng_ack_frames = round(CCP.EUCD_SNG_ACK_TIME / CCP.EUCD_LONG_TX_PERIOD) # counted down per FSM3
self.eucd_sng_count += 1
self.eucd_drive_off_request = self.eucd_own
if self.eucd_waiting and (self.eucd_sng_count >= CCP.EUCD_RESUME_BURST_MAX or not CS.out.cruiseState.standstill):
self.eucd_waiting = False
self.eucd_last_resume_frame = self.frame
# Resume held as the driver's: the CEM's frame with Resume pressed, every frame
if CS.eucd_stock_CCButtons_frames:
self.eucd_last_ccbuttons = CS.eucd_stock_CCButtons_frames[-1]
if self.eucd_resume_hold_frames > 0 and self.eucd_last_ccbuttons is not None:
can_sends.append(create_eucd_resume_button(self.packer, self.eucd_last_ccbuttons))
self.eucd_resume_hold_frames = max(self.eucd_resume_hold_frames - 1, 0)
# ---- OP owning the ECM ----
def _eucd_ownership(self, CC, CS):
"""Templates, and when OP takes and gives back the ECM."""
CCP = CarControllerEUCDParams
clean = eucd_cam_clean(CS)
if CS.eucd_ecm_acc_engaged and clean and not self.eucd_own:
for f in CS.eucd_stock_FSM0_frames:
self.eucd_tpl_fsm0[int(f["Byte_0"])] = f
# ACC_Check is the camera's instant ack: kept out of the template, the ECM braked in the drive-off (routes 8a2, 8a3)
self.eucd_tpl_fsm3["data" if int(CS.eucd_stock_FSM3["FrameKind"]) == 0x81 else "type"] = {**CS.eucd_stock_FSM3, "ACC_Check": 0}
if CS.eucd_stock_FSM4_frames:
self.eucd_tpl_fsm4 = CS.eucd_stock_FSM4_frames[-1]
have_templates = self.eucd_tpl_fsm0 and len(self.eucd_tpl_fsm3) == 2 and self.eucd_tpl_fsm4 is not None
# Driver's gas keeps OP owning (the panda keeps the camera off the ECM) until OP's long is back (route 518bf777|6e)
self.eucd_driver_gas = self.eucd_own and CC.enabled and (CS.out.gasPressed or (self.eucd_driver_gas and not CC.longActive))
# Ended by the driver with the ECM still engaged: the camera kept in standby until the ECM drops (route 896)
if self.eucd_exit_standby_frames > 0:
done = not CS.eucd_ecm_acc_engaged or self.eucd_exit_standby_frames * DT_CTRL >= CCP.EUCD_EXIT_STANDBY_MAX
self.eucd_exit_standby_frames = 0 if (done or self.eucd_own) else self.eucd_exit_standby_frames + 1
if not (CC.longActive or self.eucd_driver_gas):
if self.eucd_own and CS.eucd_ecm_acc_engaged:
self.eucd_exit_standby_frames = 1
self._eucd_release()
elif not self.eucd_own and have_templates and clean:
self.eucd_own = True
if CS.out.standstill:
# Engaged at a stop: in standstill at once, as the camera, or the car keeps holding (route 38, 40 s)
self.eucd_stopping = self.eucd_standstill = True
self.eucd_stopped_frames = int(CCP.EUCD_STANDSTILL_DELAY / DT_CTRL)
if self.eucd_own:
self._eucd_update_stop(CC, CS)
self.eucd_drive_off_request = False
def _eucd_release(self):
self.eucd_own = self.eucd_driving_off = self.eucd_driver_gas = False
self.eucd_standstill = self.eucd_stopping = self.eucd_holding = False
self.eucd_stopped_frames = self.eucd_car_hold_frames = 0
def _eucd_update_stop(self, CC, CS):
"""Stopping, the car's hold, standstill and the drive-off, as the camera does them."""
CCP = CarControllerEUCDParams
standstill = CS.out.standstill
self.eucd_stopped_frames = self.eucd_stopped_frames + 1 if standstill else 0
# The driver's gas drives off as OP's resume does
self.eucd_drive_off_request |= self.eucd_driver_gas and not self.eucd_driving_off
if self.eucd_drive_off_request:
self.eucd_driving_off, self.eucd_drive_off_frames, self.eucd_drive_off_moved = True, 0, False
if self.eucd_driving_off:
# Stopped again (or never moved): standstill sequence again, resume retried
self.eucd_drive_off_frames += 1
self.eucd_drive_off_moved |= not standstill
if standstill and self.eucd_drive_off_moved:
self.eucd_driving_off = False
self.eucd_stopped_frames = 1
elif standstill and self.eucd_drive_off_frames * DT_CTRL > CCP.EUCD_GO_RETRY_TIME:
# Never moved: straight back to standstill, so the resume burst goes again
self.eucd_driving_off = False
self.eucd_stopping = True
self.eucd_stopped_frames = int(CCP.EUCD_STANDSTILL_DELAY / DT_CTRL)
# Latched until the resume only once in standstill; before it OP drives off on traction, as the camera (route 807)
at_stop = not self.eucd_driving_off and standstill and (self.eucd_standstill or CS.eucd_ecm_standstill_ready)
stopping = not self.eucd_driving_off and ((CS.out.vEgo < CCP.EUCD_STOPPING_FLAG_SPEED and CC.actuators.accel <= 0.) or
(at_stop and (self.eucd_stopping or CS.eucd_car_hold)))
self.eucd_car_hold_frames = self.eucd_car_hold_frames + 1 if (stopping and standstill and CS.eucd_car_hold) else 0
self.eucd_stopping = stopping
# Held until OP asks to drive after the resume, so no brake pulse at the start
self.eucd_holding = not self.eucd_driver_gas and (
self.eucd_car_hold_frames > CCP.EUCD_HOLD_RELEASE_FRAMES or
(self.eucd_holding and self.eucd_driving_off and standstill and CC.actuators.accel <= 0.))
self.eucd_standstill = stopping and self.eucd_stopped_frames * DT_CTRL >= CCP.EUCD_STANDSTILL_DELAY
def _eucd_drive_off_ready(self, CS) -> bool:
"""The resume burst may go: the ECM ready to drive off from its standstill (or it never said so in time)."""
if not self.eucd_own or CS.eucd_ecm_standstill_ready:
return True
CCP = CarControllerEUCDParams
return self.eucd_stopped_frames * DT_CTRL >= CCP.EUCD_STANDSTILL_DELAY + CCP.EUCD_ECM_READY_TIMEOUT
def _eucd_fsm0(self, stock_fsm0, lead: bool):
"""FSM0 to the ECM: the camera's, or its template while OP owns the ECM (its standby kept from the ECM)."""
if not self.eucd_own:
return stock_fsm0
tpl = self.eucd_tpl_fsm0.get(int(stock_fsm0["Byte_0"]), next(iter(self.eucd_tpl_fsm0.values())))
# Lead icon from OP's lead, not the template's frozen one, which flickered between keys (route 37, seg 3)
return {**tpl, "ACC_FrontCar": int(lead)}
# ---- Longitudinal ----
def _eucd_longitudinal(self, CC, CS):
"""FSM1/FSM3 at 50 Hz: OP's accel and mode on the camera's template, or the camera's own frames."""
CCP = CarControllerEUCDParams
if self.eucd_own:
if self.eucd_driver_gas:
accel, mode = 0., LongMode.COAST
else:
accel, mode = self._eucd_long_decision(CC, CS)
if self.eucd_holding:
# The car holds the stop: the camera's standstill request (route 807)
accel, mode = CCP.EUCD_HOLD_ACCEL, LongMode.BRAKE
elif self.eucd_stopping:
# Stopping flag on: at least the camera's brake, or it drops to 0 and the car rolls on (route 2e, 59 s)
accel, mode = min(accel, CCP.EUCD_STOPPING_ACCEL), LongMode.BRAKE
self.eucd_long_mode = mode
fsm3 = self.eucd_tpl_fsm3["data" if int(CS.eucd_stock_FSM3["FrameKind"]) == 0x81 else "type"]
standstill = self.eucd_standstill
elif CS.eucd_ecm_acc_engaged:
# The camera drives (OP's long off, or its frames not seen yet): its frames as they are, with the resume's ACC_Check
accel, mode, standstill = float(CS.eucd_stock_FSM3["ACC_AccelerationRequest"]), None, None
self.eucd_long_mode = LongMode.COAST
fsm3 = CS.eucd_stock_FSM3
else:
# ECM off: the panda forwards the camera's FSM1/FSM3, a copy would be duplicated or blocked (route 2c, 837 s)
self.eucd_long_mode = LongMode.COAST
return []
self.eucd_accel = accel
if self.eucd_sng_ack_frames > 0:
acc_check = 1
self.eucd_sng_ack_frames -= 1
else:
acc_check = int(fsm3["ACC_Check"])
return [
create_eucd_radar(self.packer, CS.eucd_stock_FSM1, mode),
create_eucd_longitudinal(self.packer, fsm3, accel, acc_check, mode, standstill=standstill),
]
def _eucd_long_decision(self, CC, CS):
"""OP's accel within the limits and rate, and its mode."""
CCP = CarControllerEUCDParams
accel = min(max(CC.actuators.accel, CCP.EUCD_ACCEL_MIN), CCP.EUCD_ACCEL_MAX)
accel = self._eucd_jerk_limit(accel, self.eucd_accel)
brake_offset = self._eucd_slope_brake_offset(CC, CS.out.vEgo)
return accel, eucd_next_long_mode(self.eucd_long_mode, accel, brake_offset, CS.out.vEgo)
def _eucd_jerk_limit(self, accel, last_accel):
"""Rate limit OP's accel request: braking only against jumps, rising moderate."""
CCP = CarControllerEUCDParams
dt = CCP.EUCD_LONG_TX_PERIOD
return min(max(accel, last_accel - CCP.EUCD_JERK_DOWN * dt), last_accel + CCP.EUCD_JERK_UP * dt)
@staticmethod
def _eucd_slope_brake_offset(CC, v_ego=None):
"""Coast accel from pitch, faded out at low speed where coasting does not slow the car (route 22, 878 s)."""
if len(CC.orientationNED) != 3:
return 0.
CCP = CarControllerEUCDParams
offset = min(-CCP.EUCD_COAST_PITCH_GAIN * math.sin(CC.orientationNED[1]), CCP.EUCD_DOWNHILL_BRAKE_OFFSET_MAX)
if v_ego is None:
return offset
lo, hi = CCP.EUCD_BRAKE_ENTER_BP
return offset * min(max((v_ego - lo) / (hi - lo), 0.), 1.)
def _eucd_relay_fsm4(self, CS):
"""FSM4 to the ECM: OP's brake on the camera's template, or the camera's own."""
sends = []
for stock_fsm4 in CS.eucd_stock_FSM4_frames:
if not self.eucd_own:
sends.append(create_eucd_fsm4(self.packer, stock_fsm4, self.eucd_accel))
continue
# b0 alternates 55/AA as the camera's, b1 F1 -> F9 stopping, no brake but OP's
fsm4 = {**self.eucd_tpl_fsm4, "Byte_0": stock_fsm4["Byte_0"], "ACC_BrakeRequest": 0, "ACC_Stopping": int(self.eucd_stopping),
"Byte_5_b7": 1, "ACC_BrakeTarget": eucd_fsm4_brake_value(0., False) & 0x3FFF}
# The car holds (or the driver's gas): brake request released, like the camera 50 ms after the hold
mode = None if (self.eucd_holding or self.eucd_driver_gas) else self.eucd_long_mode
sends.append(create_eucd_fsm4(self.packer, fsm4, self.eucd_accel, mode))
return sends
def _eucd_relay_to_camera(self, CS):
"""Car frames to the camera: with OP owning the ECM, ACC standby, no ACC brake, hold nor engaging button shown."""
standby = self.eucd_own or self.eucd_exit_standby_frames > 0
sends = []
for stock_wheel_rear in CS.eucd_stock_WheelRear_frames:
sends.append(create_eucd_cam_wheel_status(self.packer, stock_wheel_rear, standby))
for stock_brake_req_ack in CS.eucd_stock_BrakeReqAck_frames:
sends.append(create_eucd_cam_brake_request_ack(self.packer, stock_brake_req_ack, standby))
for stock_engine_data in CS.eucd_stock_EngineData_frames:
sends.append(create_eucd_cam_engine_data(self.packer, stock_engine_data, standby))
for stock_acc_hold in CS.eucd_stock_AccHold_frames:
sends.append(create_eucd_cam_acc_hold(self.packer, stock_acc_hold, standby))
for stock_ccbuttons in CS.eucd_stock_CCButtons_frames:
sends.append(create_eucd_cam_button(self.packer, stock_ccbuttons, standby))
# 0x1FF b0 held while stopped (its 0x70 -> 0xD0 fires the camera's brake alert)
hold_mask = self.eucd_own and CS.out.standstill
for stock_brake_hold in CS.eucd_stock_BrakeHold_frames:
if not hold_mask or self.eucd_brake_hold_b0 is None:
self.eucd_brake_hold_b0 = int(stock_brake_hold["Byte_0"])
sends.append(create_eucd_cam_brake_hold(self.packer, stock_brake_hold, self.eucd_brake_hold_b0 if hold_mask else None))
return sends
@@ -0,0 +1,216 @@
import copy
from opendbc.can.parser import CANParser
from opendbc.car import Bus, ButtonType, create_button_events, structs
from opendbc.car.common.conversions import Conversions as CV
from opendbc.car.dashboard_speed_limit import Tracker as LimitTracker, parser_expiry, volvo_sign
from opendbc.car.interfaces import CarStateBase
from opendbc.car.volvo.eucd_params import CANBUS, CarControllerEUCDParams, EcmAccState
from opendbc.car.volvo.values import DBC
GearShifter = structs.CarState.GearShifter
def eucd_all_frames(cp: CANParser, name: str) -> list[dict[str, float]]:
sigs = cp.vl_all[name]
return [dict(zip(sigs.keys(), vals, strict=True)) for vals in zip(*sigs.values(), strict=True)]
class CarStateEUCD(CarStateBase):
def __init__(self, CP):
super().__init__(CP)
self.eucd_cruise_enabled_prev = False
self.eucd_eps_torque_timer = 0
self.eucd_ecm_acc_engaged = False
self.eucd_pscm_stock_values = {}
self._eucd_cruise_speed_prev_kph = 0
self._eucd_pending_delta = 0
self._eucd_custom_acc_step = 1
self.eucd_gap_button_states = {"TimeGapIncreaseBtn": False, "TimeGapDecreaseBtn": False}
self.eucd_driver_onoff = False # driver's ACC On/Off held (bit set, inverted copy cleared)
self.eucd_driver_resume = False # driver's Resume held (bit set, inverted copy cleared)
# Set by the carcontroller: while OP owns the ECM, the ACC standstill is OP's
self.eucd_op_owns_ecm = False
self.eucd_op_standstill = False
self.eucd_ecm_standstill_ready = False
self.eucd_lka_on = False # the driver's LKA on/off, always on lateral follows it
self.eucd_gas_pressed = False
self.eucd_lka_state_prev: bool | None = None
self.dashboard_limit = LimitTracker()
def update(self, can_parsers) -> structs.CarState:
pt_cp = can_parsers[Bus.pt]
cam_cp = can_parsers[Bus.cam]
ret = structs.CarState()
# car speed
ret.vEgoRaw = pt_cp.vl["VehicleSpeed1"]["VehicleSpeed"] * CV.KPH_TO_MS
ret.vEgo, ret.aEgo = self.update_speed_kf(ret.vEgoRaw)
ret.standstill = ret.vEgoRaw < 0.1
# Gas: 10% to press, under 9% to release, as the panda (route 00000007)
self.eucd_gas_pressed = pt_cp.vl["AccPedal"]["AccPedal"] >= (9 if self.eucd_gas_pressed else 10)
ret.gasPressed = self.eucd_gas_pressed
# brake pedal
ret.brakePressed = pt_cp.vl["Brake_Info"]["BrakePedal"] == 2
# steering
ret.steeringAngleDeg = pt_cp.vl["PSCM1"]["SteeringAngleServo"]
ret.steeringRateDeg = pt_cp.vl["SAS0"]["SteeringRateOfChange"]
eucd_steering_direction = pt_cp.vl["SAS0"]["SteeringDirection"]
ret.steeringTorque = pt_cp.vl["PSCM1"]["EPSTorque"]
if eucd_steering_direction:
ret.steeringTorque = -abs(ret.steeringTorque)
ret.steeringTorqueEps = pt_cp.vl["PSCM1"]["LKATorque"]
ret.steeringPressed = abs(ret.steeringTorque) > 50
# cruise state
set_speed = pt_cp.vl["ACC_Speed"]["ACC_Speed"] * CV.KPH_TO_MS
ret.cruiseState.speed = set_speed
ret.cruiseState.speedCluster = ret.cruiseState.speed
ret.cruiseState.available = bool(cam_cp.vl["FSM0"]["ACC_Available"])
# ECM is the ACC master
self.eucd_ecm_acc_engaged = int(pt_cp.vl["EngineData"]["ACC_State_ECM"]) == EcmAccState.ENGAGED
ret.cruiseState.enabled = self.eucd_ecm_acc_engaged
# Camera standstill hold, gated by the car's standstill; OP's own while it owns the ECM
if self.eucd_op_owns_ecm:
ret.cruiseState.standstill = self.eucd_op_standstill and ret.standstill
else:
ret.cruiseState.standstill = bool(cam_cp.vl["FSM3"]["ACC_Standstill"]) and ret.standstill
# The car holds the stop (BrakeReqAck b0 bit7, route 807)
self.eucd_car_hold = bool(pt_cp.vl["BrakeReqAck"]["StandstillHold"])
# The ECM takes a resume only once 0x1FF b0 goes 70 -> D0, ~1.5 s after ACC_Standstill (routes 899, 89b)
self.eucd_ecm_standstill_ready = int(pt_cp.vl["BrakeHold"]["Byte_0"]) == 0xD0
ret.cruiseState.nonAdaptive = False
ret.accFaulted = False
self.eucd_acc_distance = cam_cp.vl["FSM1"]["ACC_Distance"]
# Servo timeout while ACC is active
if ret.cruiseState.enabled and ret.vEgo > CarControllerEUCDParams.EUCD_MIN_STEER_SPEED:
if not self.eucd_cruise_enabled_prev:
self.eucd_eps_torque_timer = 0
if ret.steeringTorqueEps == 0:
self.eucd_eps_torque_timer += 1
else:
self.eucd_eps_torque_timer = 0
ret.steerFaultTemporary = self.eucd_eps_torque_timer >= CarControllerEUCDParams.EUCD_STEER_TIMEOUT
else:
ret.steerFaultTemporary = False
self.eucd_cruise_enabled_prev = ret.cruiseState.enabled
# Gear lever position
ret.gearShifter = {
0: GearShifter.park,
1: GearShifter.reverse,
2: GearShifter.neutral,
3: GearShifter.drive,
}[int(pt_cp.vl["GearSelector"]["GearLever"])]
# safety
ret.stockFcw = False
ret.stockAeb = False
# button presses
ret.leftBlinker = pt_cp.vl["MiscCarInfo"]["TurnSignal"] == 1
ret.rightBlinker = pt_cp.vl["MiscCarInfo"]["TurnSignal"] == 3
# One accelCruise/decelCruise per frame from the pending delta
cruise_kph_now = round(set_speed * CV.MS_TO_KPH)
# Stopped, Set+/- only sets the speed: no accel/decel press, or the planner reads it as "go" (route 8b2, 572 s/591 s)
if ret.standstill:
self._eucd_pending_delta = 0
elif ret.cruiseState.enabled and self.eucd_cruise_enabled_prev:
self._eucd_pending_delta += cruise_kph_now - self._eucd_cruise_speed_prev_kph
self._eucd_cruise_speed_prev_kph = cruise_kph_now
# One event per ACC step
step = max(1, self._eucd_custom_acc_step)
button_events = []
if self._eucd_pending_delta >= 1:
button_events.append(structs.CarState.ButtonEvent(pressed=False, type=ButtonType.accelCruise))
self._eucd_pending_delta = max(0, self._eucd_pending_delta - step)
elif self._eucd_pending_delta <= -1:
button_events.append(structs.CarState.ButtonEvent(pressed=False, type=ButtonType.decelCruise))
self._eucd_pending_delta = min(0, self._eucd_pending_delta + step)
# Gap buttons cycle the personality (bit set, inverted copy cleared)
for signal in self.eucd_gap_button_states:
pressed = bool(pt_cp.vl["CCButtons"][signal]) and not pt_cp.vl["CCButtons"][signal + "Inv"]
button_events.extend(create_button_events(pressed, self.eucd_gap_button_states[signal], {True: ButtonType.gapAdjustCruise}))
self.eucd_gap_button_states[signal] = pressed
# Driver's On/Off as cancel, so OP disengages before the panda drops permission (route 22, 418.4 s)
driver_onoff = bool(pt_cp.vl["CCButtons"]["ACCOnOffBtn"]) and not pt_cp.vl["CCButtons"]["ACCOnOffBtnInv"]
button_events.extend(create_button_events(driver_onoff, self.eucd_driver_onoff, {True: ButtonType.cancel}))
self.eucd_driver_onoff = driver_onoff
driver_resume = bool(pt_cp.vl["CCButtons"]["ACCResumeBtn"]) and not pt_cp.vl["CCButtons"]["ACCResumeBtnInv"]
button_events.extend(create_button_events(driver_resume, self.eucd_driver_resume, {True: ButtonType.resumeCruise}))
self.eucd_driver_resume = driver_resume
# LKA button: no own bit, each press flips LKA_State (route 8a8)
lka_state = bool(pt_cp.vl["CCButtons"]["LKA_State"])
if self.eucd_lka_state_prev is not None and lka_state != self.eucd_lka_state_prev:
button_events += [structs.CarState.ButtonEvent(pressed=True, type=ButtonType.lkas),
structs.CarState.ButtonEvent(pressed=False, type=ButtonType.lkas)]
self.eucd_lka_state_prev = lka_state
self.eucd_lka_on = lka_state
ret.buttonEvents = button_events
# lock info
ret.doorOpen = not all([pt_cp.vl["Doors"]["DriverDoorClosed"], pt_cp.vl["Doors"]["PassengerDoorClosed"]])
ret.seatbeltUnlatched = False
self.eucd_pscm_stock_values = pt_cp.vl["PSCM1"]
self.eucd_stock_FSM1 = copy.copy(cam_cp.vl["FSM1"])
self.eucd_stock_FSM3 = copy.copy(cam_cp.vl["FSM3"])
# Frames carcontroller relays 1:1
self.eucd_stock_FSM0_frames = eucd_all_frames(cam_cp, "FSM0")
self.eucd_stock_FSM4_frames = eucd_all_frames(cam_cp, "FSM4")
self.eucd_stock_WheelRear_frames = eucd_all_frames(pt_cp, "WheelRear")
self.eucd_stock_BrakeReqAck_frames = eucd_all_frames(pt_cp, "BrakeReqAck")
self.eucd_stock_BrakeHold_frames = eucd_all_frames(pt_cp, "BrakeHold")
self.eucd_stock_EngineData_frames = eucd_all_frames(pt_cp, "EngineData")
self.eucd_stock_AccHold_frames = eucd_all_frames(pt_cp, "AccHold")
self.eucd_stock_CCButtons_frames = eucd_all_frames(pt_cp, "CCButtons")
# TSR speed limit, 0 = no sign
timestamp, expiry = parser_expiry(cam_cp, "FSM5", "TSR_Speed")
if timestamp > self.dashboard_limit.observation.observed_ns:
status, value_mps = volvo_sign(cam_cp.vl["FSM5"]["TSR_Speed"])
self.dashboard_limit.update(timestamp, status, value_mps, valid_until_ns=expiry)
return ret
@staticmethod
def get_can_parsers(CP):
pt_messages = [
("VehicleSpeed1", 50),
("AccPedal", 100),
("Brake_Info", 50),
("PSCM1", 50),
("ACC_Speed", 50),
("MiscCarInfo", 25),
("Doors", 20),
("SAS0", 100),
("EngineData", 66),
("CCButtons", 66),
("GearSelector", 66),
("WheelRear", 50),
("BrakeReqAck", 50),
("BrakeHold", 50),
("AccHold", 25),
]
cam_messages = [
("FSM0", 100),
("FSM1", 50),
("FSM3", 50),
("FSM4", 33),
("FSM5", 10),
]
return {
Bus.pt: CANParser(DBC[CP.carFingerprint][Bus.pt], pt_messages, CANBUS.pt),
Bus.cam: CANParser(DBC[CP.carFingerprint][Bus.pt], cam_messages, CANBUS.cam),
}
@@ -0,0 +1,101 @@
from enum import IntEnum
from opendbc.car import DT_CTRL
from opendbc.car.common.conversions import Conversions as CV
from opendbc.car.lateral import AngleSteeringLimits
class SteerDirection(IntEnum):
"""LKA steer direction; EUCD waits 8 frames on a direction change."""
NONE = 0
RIGHT = 1
LEFT = 2
BOTH = 3
class LongMode(IntEnum):
"""FSM3 Byte_2 mode bits; the ECM brakes hydraulically only in BRAKE."""
BRAKE = 0
COAST = 1
DRIVE = 2
class EcmAccState(IntEnum):
"""ECM ACC state, EngineData Byte_4 bits 5:4."""
OFF = 1
STANDBY = 2
ENGAGED = 3
class CarControllerEUCDParams:
EUCD_ANGLE_LIMITS: AngleSteeringLimits = AngleSteeringLimits(90,
([0., 5., 15.], [5., .8, .15]),
([0., 5., 15.], [5., 3.5, 0.4]),
)
EUCD_STEER_TIMEOUT = 30 / DT_CTRL # frames of 0 torque before the EPS faults
EUCD_BLOCK_LEN = 8 # frames to block steering on a direction change
EUCD_DEADZONE = 0.2 # deg, keep the previous direction inside it
# Resume held this long on copies of the CEM's CCButtons: a one-shot burst was lost amid its frames (route 89e)
EUCD_RESUME_HOLD_FRAMES = int(0.3 / DT_CTRL)
# s of planner resume before SNG: 0.2 let a red-light flicker through, the ECM drove off on its own (route 8a4)
EUCD_SNG_OP_RESUME_TIME = 0.5
EUCD_RESUME_BURST_INTERVAL = 1.0 # s between resume bursts at a standstill
EUCD_RESUME_BURST_MAX = 5 # bursts per standstill
EUCD_SNG_ACK_TIME = 0.5 # s of FSM3 ACC_Check with the first burst, as the camera's ack (~300 ms after engaging)
EUCD_MIN_STEER_SPEED = 0.1 # m/s, no steering nor cancel button below this
# OP's stop to 0 (route 807), with OP owning the ECM
EUCD_STOPPING_FLAG_SPEED = 2.6 * CV.KPH_TO_MS # FSM4 b1 F1 -> F9 below this
EUCD_HOLD_RELEASE_FRAMES = int(0.05 / DT_CTRL) # brake request released after the car's hold
EUCD_STANDSTILL_DELAY = 3.0 # s stopped before FSM3 ACC_Standstill
EUCD_HOLD_ACCEL = -0.08 # m/s^2, FSM3 accel while the car holds (raw 0x7C)
EUCD_STOPPING_ACCEL = -0.64 # m/s^2, at most while stopping, as the camera from its F9 to the car's hold (route 807)
EUCD_GO_RETRY_TIME = 2.0 # s still stopped after the resume burst -> standstill again, retry
EUCD_ECM_READY_TIMEOUT = 3.0 # s after FSM3 ACC_Standstill: resume sent even without the ECM's ready (seen 1.5 s)
EUCD_EXIT_STANDBY_MAX = 1.0 # s, OP's long ended with the ECM still engaged: camera kept in standby at most this long
# Longitudinal: FSM1/FSM3 sent at 50 Hz, limits
EUCD_LONG_TX_PERIOD = 0.02 # s
EUCD_ACCEL_MIN = -3.5 # m/s^2, as the panda's
EUCD_ACCEL_MAX = 2.0 # m/s^2
# FSM3 mode hysteresis on OP accel
EUCD_BRAKE_ENTER = -0.50 # m/s^2, at and above EUCD_BRAKE_ENTER_BP[-1]
EUCD_BRAKE_EXIT = -0.15
# Slower, BRAKE enters earlier like the camera's, as coasting there does not slow the car (routes 0a, 22, 24)
EUCD_BRAKE_ENTER_BP = [15. * CV.KPH_TO_MS, 40. * CV.KPH_TO_MS]
EUCD_BRAKE_ENTER_V = [-0.10, EUCD_BRAKE_ENTER]
EUCD_BRAKE_HYSTERESIS = EUCD_BRAKE_EXIT - EUCD_BRAKE_ENTER # exit this much above the enter, never above 0
EUCD_DRIVE_ENTER = 0.08
EUCD_DRIVE_EXIT = 0.04
# FSM3 Byte_3 traction = gain * accel + offset, as the camera sends it
EUCD_TRACTION_COAST = (94., -9.)
EUCD_TRACTION_DRIVE = (97., -6.)
# FSM4 14-bit brake target = zero + gain * accel, as the camera's own (248 segments, route 29); no-brake map below
EUCD_FSM4_BRAKE_ZERO = 13332
EUCD_FSM4_BRAKE_GAIN = 255. # counts per m/s^2
EUCD_FSM4_BRAKE_ACCEL_RANGE = (EUCD_ACCEL_MIN, 0.2)
EUCD_FSM4_NO_BRAKE_ACCEL_BP = [-0.45, -0.2, 0.0, 0.2, 0.45, 0.8, 1.5]
EUCD_FSM4_NO_BRAKE_VALUE_V = [13276, 13299, 13318, 13338, 13333, 13377, 13449]
# BRAKE thresholds shifted by the slope's coast accel
EUCD_COAST_PITCH_GAIN = 5.65 # m/s^2 per sin(pitch)
EUCD_DOWNHILL_BRAKE_OFFSET_MAX = 0.15 # m/s^2, downhill shift cap
# Extra uphill margin before BRAKE
EUCD_UPHILL_BRAKE_ENTER_EXTRA = 0.6 # fraction of the uphill offset
# Accel rate limits: falling only against jumps (as Toyota), rising moderate (route 1f, 678 s)
EUCD_JERK_UP = 4.0 # m/s^3
EUCD_JERK_DOWN = 12.0 # m/s^3
# Delphi ESR 2.5 on the aux bus, read directly
RADAR_ESR = "ESR"
class CANBUS:
pt = 0
body = 1 # aux bus: Delphi ESR radar, CEM dynamics
cam = 2
@@ -1,7 +1,10 @@
# ruff: noqa: E501
""" AUTO-FORMATTED USING opendbc/car/debug/format_fingerprints.py, EDIT STRUCTURE THERE."""
from opendbc.car.structs import CarParams
from opendbc.car.volvo.values import CAR
Ecu = CarParams.Ecu
FINGERPRINTS = {
CAR.VOLVO_V40: [
# V40 2017
@@ -20,7 +23,24 @@ FINGERPRINTS = {
CAR.POLESTAR_2: [{
7: 4, 21: 8, 22: 8, 23: 8, 26: 8, 35: 8, 37: 8, 53: 8, 58: 8, 67: 8, 69: 8, 70: 8, 85: 8, 87: 8, 88: 8, 96: 8, 103: 8, 104: 8, 105: 8, 112: 8, 117: 8, 128: 8, 133: 8, 138: 8, 144: 8, 146: 8, 147: 8, 151: 8, 256: 8, 277: 8, 278: 8, 284: 8, 293: 8, 309: 8, 320: 8, 325: 8, 336: 8, 339: 8, 341: 8, 348: 8, 349: 8, 352: 8, 368: 8, 370: 8, 373: 8, 375: 8, 376: 8, 389: 8, 395: 8, 400: 8, 408: 8, 411: 8, 417: 8, 420: 8, 426: 8, 429: 8, 435: 8, 440: 8, 464: 8, 556: 8, 640: 8, 656: 8, 666: 8, 773: 8, 778: 8, 789: 8, 791: 8, 800: 8, 805: 8, 807: 8, 816: 8, 821: 8, 832: 8, 837: 8, 841: 8, 848: 8, 853: 8, 854: 8, 858: 8, 860: 8, 873: 8, 882: 8, 889: 8, 890: 8, 891: 8, 892: 8, 893: 8, 896: 8, 899: 8, 901: 8, 917: 8, 919: 8, 1043: 8, 1045: 8, 1061: 8, 1072: 8, 1077: 8, 1088: 8, 1093: 8, 1120: 8, 1127: 8, 1160: 8, 1168: 8, 1171: 8, 1174: 8, 1175: 8, 1177: 8, 1296: 8, 1302: 8, 1320: 8, 1334: 8, 1336: 8, 1407: 8, 1422: 8, 1423: 8, 1424: 8, 1425: 8, 1426: 8, 1428: 8, 1429: 8, 1430: 8, 1431: 8, 1432: 8, 1554: 8, 1584: 8, 1587: 8, 2022: 8
}],
CAR.VOLVO_V60: [
{
16: 8, 32: 8, 81: 8, 99: 8, 104: 8, 112: 8,
277: 8, 307: 8, 320: 8, 328: 8, 336: 8, 343: 8,
352: 8, 359: 8, 384: 8, 465: 8, 511: 8, 522: 8,
544: 8, 565: 8, 582: 8, 608: 8, 609: 8, 610: 8,
624: 8, 648: 8, 665: 8, 673: 8, 704: 8, 706: 8,
750: 8, 751: 8, 788: 8, 797: 8, 802: 8, 807: 8,
821: 8, 978: 8,
},
],
}
FW_VERSIONS: dict[str, dict[tuple, list[bytes]]] = {
CAR.VOLVO_V60: {
(Ecu.engine, 0x7e0, None): [
b'31361041 AJ\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00',
b'31441016 AA\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00',
],
},
}
+35 -10
View File
@@ -1,19 +1,27 @@
from collections import deque
from collections import Counter, deque
from opendbc.car import structs, get_safety_config
from opendbc.car import Bus, structs, get_safety_config
from opendbc.car.interfaces import CarInterfaceBase
from opendbc.car.volvo.carstate import CarState
from opendbc.car.volvo.carcontroller import CarController
from opendbc.car.volvo.helpers import pscm_status_validation_class
from opendbc.car.volvo.values import CAR, VolvoC1PlatformConfig, VolvoSPAPlatformConfig, VolvoSafetyFlags
from opendbc.car.volvo.radar_interface import RadarInterface
from opendbc.car.volvo.values import CAR, DBC, VolvoC1PlatformConfig, VolvoEUCDPlatformConfig, VolvoSPAPlatformConfig, VolvoSafetyFlags
class CarInterface(CarInterfaceBase):
CarState = CarState
CarController = CarController
RadarInterface = RadarInterface # Delphi ESR 2.5 on the V60; the others have no radar DBC
def __init__(self, CP):
if not isinstance(CAR(CP.carFingerprint).config, VolvoC1PlatformConfig):
config = CAR(CP.carFingerprint).config
if isinstance(config, VolvoEUCDPlatformConfig):
from opendbc.car.volvo.eucd_carstate import CarStateEUCD
from opendbc.car.volvo.eucd_carcontroller import CarControllerEUCD
self.CarState = CarStateEUCD
self.CarController = CarControllerEUCD
elif not isinstance(config, VolvoC1PlatformConfig):
from opendbc.car.volvo.cma_carstate import CarStateCMA
from opendbc.car.volvo.cma_carcontroller import CarControllerCMA
self.CarState = CarStateCMA
@@ -44,8 +52,14 @@ class CarInterface(CarInterfaceBase):
actuators, messages = super().apply(c, now_nanos)
if self.CP.carFingerprint == CAR.POLESTAR_2:
if not self.CC.lat_active:
# Preserve source counters and cadence instead of resampling the latest frame.
messages = list(self.stock_relay)
# Panda only retains four source packets per address. After a backlog,
# resume each stream with its newest packet instead of bursting stale copies.
counts = Counter(address for address, _, _ in self.stock_relay)
if max(counts.values(), default=0) > 4:
latest = {frame[0]: index for index, frame in enumerate(self.stock_relay)}
messages = [frame for index, frame in enumerate(self.stock_relay) if index == latest[frame[0]]]
else:
messages = list(self.stock_relay)
self.stock_relay.clear()
return actuators, messages
@@ -54,16 +68,27 @@ class CarInterface(CarInterfaceBase):
ret.brand = 'volvo'
platform = CAR(candidate).config
c1 = isinstance(platform, VolvoC1PlatformConfig)
eucd = isinstance(platform, VolvoEUCDPlatformConfig)
safety_param = VolvoSafetyFlags.C1.value if c1 else VolvoSafetyFlags.SPA.value if isinstance(platform, VolvoSPAPlatformConfig) else 0
if eucd:
safety_param = VolvoSafetyFlags.EUCD.value
if candidate == CAR.POLESTAR_2:
safety_param |= VolvoSafetyFlags.LCA2_MOD15.value
ret.safetyConfigs = [get_safety_config(structs.CarParams.SafetyModel.volvo, safety_param)]
ret.steerActuatorDelay = 0.2 if c1 else 0.3
ret.steerLimitTimer = 0.1
ret.steerActuatorDelay = 0.2 if (c1 or eucd) else 0.3
ret.steerLimitTimer = 0.8 if eucd else 0.1
ret.steerAtStandstill = not c1
ret.steerControlType = structs.CarParams.SteerControlType.angle
ret.radarUnavailable = True
ret.alphaLongitudinalAvailable = False
ret.radarUnavailable = Bus.radar not in DBC[candidate]
ret.alphaLongitudinalAvailable = eucd
if eucd:
# OP long: stock ACC engages and owns the set speed; OP replaces FSM3
ret.openpilotLongitudinalControl = alpha_long
if ret.openpilotLongitudinalControl:
ret.longitudinalActuatorDelay = 0.5 # FSM3 accel to aEgo delay
# Integral-only accel loop, the car brakes short of OP's request (route 89d)
ret.longitudinalTuning.kiBP = [0.]
ret.longitudinalTuning.kiV = [0.2]
ret.pcmCruise = True
if c1:
ret.transmissionType = structs.CarParams.TransmissionType.automatic
@@ -0,0 +1,77 @@
from math import cos, sin
from opendbc.can.parser import CANParser
from opendbc.car import Bus, structs
from opendbc.car.common.conversions import Conversions as CV
from opendbc.car.interfaces import RadarInterfaceBase
from opendbc.car.volvo.eucd_params import CANBUS
from opendbc.car.volvo.values import DBC
# Delphi ESR 2.5: 64 tracks at 0x500..0x53F, 20 Hz, bus 1
DELPHI_ESR_TRACK_ADDRS = list(range(0x500, 0x540)) # Target1..Target64
DELPHI_ESR_TRACK_NAMES = [f"Target{i}" for i in range(1, 65)]
# (addr, name) pairs
TRACK_ADDR_NAMES = list(zip(DELPHI_ESR_TRACK_ADDRS, DELPHI_ESR_TRACK_NAMES, strict=True))
TRIGGER_MSG_ADDR = DELPHI_ESR_TRACK_ADDRS[-1]
# Track status: 0 no target, 6 invalid coasted
INVALID_STATUSES = {0, 6}
# Consecutive valid frames before a track is published
MIN_VALID_CNT = 3
def _create_radar_can_parser(CP) -> CANParser:
messages = [(name, 20) for name in DELPHI_ESR_TRACK_NAMES]
return CANParser(DBC[CP.carFingerprint][Bus.radar], messages, CANBUS.body)
class RadarInterface(RadarInterfaceBase):
def __init__(self, CP):
super().__init__(CP)
self.updated_messages: set[int] = set()
self.valid_cnt: dict[int, int] = {addr: 0 for addr in DELPHI_ESR_TRACK_ADDRS}
self.track_id = 0
self.rcp = None if CP.radarUnavailable else _create_radar_can_parser(CP)
def update(self, can_strings):
if self.rcp is None:
return super().update(can_strings)
self.updated_messages.update(self.rcp.update(can_strings))
# Publish after the last slot of a sweep
if TRIGGER_MSG_ADDR not in self.updated_messages:
return None
self.updated_messages.clear()
ret = structs.RadarData()
if not self.rcp.can_valid:
ret.errors.canError = True
for addr, name in TRACK_ADDR_NAMES:
cpt = self.rcp.vl[name]
rng = cpt["CAN_TX_TRACK_RANGE"]
status = int(cpt["CAN_TX_TRACK_STATUS"])
valid = status not in INVALID_STATUSES and rng > 0.5
if valid:
self.valid_cnt[addr] = min(self.valid_cnt[addr] + 1, MIN_VALID_CNT + 2)
else:
self.valid_cnt[addr] = max(self.valid_cnt[addr] - 1, 0)
# Keep the last good reading on flicker
if valid and self.valid_cnt[addr] >= MIN_VALID_CNT:
if addr not in self.pts:
self.pts[addr] = structs.RadarData.RadarPoint()
self.pts[addr].trackId = self.track_id
self.track_id += 1
angle_rad = cpt["CAN_TX_TRACK_ANGLE"] * CV.DEG_TO_RAD
# Flip the ESR angle for left-positive yRel
self.pts[addr].dRel = rng * cos(angle_rad)
self.pts[addr].yRel = -rng * sin(angle_rad)
self.pts[addr].vRel = cpt["CAN_TX_TRACK_RANGE_RATE"]
elif self.valid_cnt[addr] < MIN_VALID_CNT and addr in self.pts:
del self.pts[addr]
ret.points = list(self.pts.values())
return ret
@@ -17,6 +17,8 @@ EXPECTED = {'VOLVO_V40': (2, 1610, 2.647, 14.7, .2),
'VOLVO_XC40_RECHARGE': (0, 2170, 2.702, 15.8, .3),
'VOLVO_S60_RECHARGE': (1, 2020, 2.872, 16.2, .3),
'POLESTAR_2': (5, 2123, 2.735, 15.8, .3)}
# The V60 (EUCD) only shares the params and fingerprint checks; the shared runtime fixtures model CMA/V40 frames
PARAMS = {**EXPECTED, 'VOLVO_V60': (8, 1750, 2.776, 15.0, .2)}
def interface(identity, alpha=False, release=False):
@@ -63,26 +65,28 @@ def sources(identity, cruise=True, *, frame=0):
return checked
@pytest.mark.parametrize('identity', EXPECTED)
@pytest.mark.parametrize('identity', PARAMS)
@pytest.mark.parametrize('alpha', [False, True])
@pytest.mark.parametrize('release', [False, True])
def test_all_final_params_and_angle_factory(identity, alpha, release):
from openpilot.selfdrive.controls.lib.lateral_controller_factory import create_lateral_controller
from openpilot.selfdrive.controls.lib.latcontrol_angle import LatControlAngle
cp, ci = interface(identity, alpha, release)
param, mass, wheelbase, ratio, delay = EXPECTED[identity]
param, mass, wheelbase, ratio, delay = PARAMS[identity]
assert cp.mass == mass + STD_CARGO_KG
# These declared CarParams fields are Float32; compare exact wire values.
expected_geometry = struct.unpack('<3f', struct.pack('<3f', wheelbase, ratio, delay))
assert (cp.wheelbase, cp.steerRatio, cp.steerActuatorDelay) == expected_geometry
assert cp.safetyConfigs[0].safetyParam == param
assert cp.steerControlType == structs.CarParams.SteerControlType.angle
assert cp.pcmCruise and cp.radarUnavailable and not cp.dashcamOnly
assert not cp.alphaLongitudinalAvailable and not cp.openpilotLongitudinalControl
assert cp.pcmCruise and not cp.dashcamOnly
assert cp.radarUnavailable == (identity != 'VOLVO_V60') # the V60's Delphi ESR
assert cp.alphaLongitudinalAvailable == (identity == 'VOLVO_V60')
assert cp.openpilotLongitudinalControl == (alpha and identity == 'VOLVO_V60')
assert isinstance(create_lateral_controller(cp, ci, .01, mode='stock'), LatControlAngle)
@pytest.mark.parametrize('identity', EXPECTED)
@pytest.mark.parametrize('identity', PARAMS)
def test_all_dom_captures_identify_through_real_eliminator(identity):
for capture in FINGERPRINTS[CAR(identity)]:
cars = all_legacy_fingerprint_cars()
@@ -50,7 +50,7 @@ def test_pending_queue_is_bounded():
ci.update([(1_000_000_000, received)])
assert len(ci.stock_relay) == 128
_, output = ci.apply(structs.CarControl.new_message().as_reader(), 1_010_000_000)
assert output == forwarded(received[-128:])
assert output == forwarded(received[-1:])
@pytest.mark.parametrize('changes', [
@@ -85,3 +85,17 @@ def test_stock_received_while_active_cannot_leak_into_later_withdrawal():
assert not ci.stock_relay
_, output = ci.apply(structs.CarControl.new_message().as_reader(), 1_020_000_000)
assert output == []
def test_recovery_sends_latest_frames_in_source_order():
ci = interface()
angle = packets()
status = (0x16, bytes(8), 2)
other = (0x58, bytes(8), 0)
received = [status, angle[0], other, angle[1], status, angle[2], other, angle[0], angle[1], status, other, other]
for i, frame in enumerate(received):
ci.update([(1_000_000_000 + i * 10_000_000, [frame])])
_, output = ci.apply(structs.CarControl.new_message().as_reader(), 1_120_000_000)
assert output == forwarded([angle[1], status, other])
_, output = ci.apply(structs.CarControl.new_message().as_reader(), 1_130_000_000)
assert output == []
@@ -0,0 +1,355 @@
import pytest
from opendbc.can import CANPacker
from opendbc.car import Bus, ButtonType, CanData, structs
from opendbc.car.common.conversions import Conversions as CV
from opendbc.car.dashboard_speed_limit import Status
from opendbc.car.volvo.eucd_can import calculate_eucd_lka_checksum, create_eucd_lka_msg
from opendbc.car.volvo.eucd_carcontroller import CarControllerEUCD
from opendbc.car.volvo.eucd_carstate import CarStateEUCD
from opendbc.car.volvo.eucd_params import CarControllerEUCDParams, EcmAccState
from opendbc.car.volvo.interface import CarInterface
from opendbc.car.volvo.values import CAR, DBC, VolvoSafetyFlags
GearShifter = structs.CarState.GearShifter
DBC_NAME = DBC[CAR.VOLVO_V60][Bus.pt]
def params(alpha=False, release=False):
cp = CarInterface.get_non_essential_params(CAR.VOLVO_V60)
return CarInterface._get_params(cp, CAR.VOLVO_V60, {0: {}, 1: {}, 2: {}}, [], alpha, release, False)
def required_frames(**overrides):
packer = CANPacker(DBC_NAME)
values = {
"VehicleSpeed1": {"VehicleSpeed": 72},
"AccPedal": {"AccPedal": 0},
"Brake_Info": {"BrakePedal": 0},
"PSCM1": {"SteeringAngleServo": 12.5, "EPSTorque": 10, "LKATorque": 5},
"ACC_Speed": {"ACC_Speed": 100},
"MiscCarInfo": {"TurnSignal": 1},
"Doors": {"DriverDoorClosed": 1, "PassengerDoorClosed": 1},
"SAS0": {"SteeringRateOfChange": 2, "SteeringDirection": 0},
"EngineData": {"ACC_State_ECM": EcmAccState.ENGAGED},
"CCButtons": {},
"GearSelector": {"GearLever": 3},
"WheelRear": {}, "BrakeReqAck": {}, "BrakeHold": {}, "AccHold": {},
}
cam_values = {"FSM0": {"ACC_Available": 1}, "FSM1": {}, "FSM3": {"ACC_Standstill": 0}, "FSM4": {}, "FSM5": {"TSR_Speed": 0}}
for name, signals in overrides.items():
(cam_values if name in cam_values else values)[name] = signals
return [CanData(*packer.make_can_msg(name, 0, signals)) for name, signals in values.items()] + \
[CanData(*packer.make_can_msg(name, 2, signals)) for name, signals in cam_values.items()]
def car_state(**overrides):
cp = params()
cs = CarStateEUCD(cp)
parsers = cs.get_can_parsers(cp)
frames = required_frames(**overrides)
for parser in parsers.values():
parser.update([(1_000_000_000, frames)])
return cs, parsers, cp
def test_params_and_alpha_long():
for alpha in (False, True):
for release in (False, True):
cp = params(alpha, release)
config = cp.safetyConfigs[0]
assert (config.safetyModel, config.safetyParam) == (structs.CarParams.SafetyModel.volvo, VolvoSafetyFlags.EUCD.value)
assert cp.pcmCruise and cp.alphaLongitudinalAvailable
assert cp.openpilotLongitudinalControl == alpha
assert not cp.radarUnavailable # Delphi ESR 2.5 on the aux bus
assert cp.steerControlType == structs.CarParams.SteerControlType.angle
assert cp.minSteerSpeed == 0.
assert cp.steerActuatorDelay == pytest.approx(0.2)
assert cp.steerLimitTimer == pytest.approx(0.8)
assert cp.steerAtStandstill
def test_interface_selects_the_eucd_implementation():
cp = params()
interface = CarInterface(cp)
assert isinstance(interface.CS, CarStateEUCD)
assert isinstance(interface.CC, CarControllerEUCD)
def test_required_can_and_state_contract():
cs, parsers, _ = car_state()
assert all(parser.can_valid for parser in parsers.values())
ret = cs.update(parsers)
assert ret.vEgoRaw == pytest.approx(72 * CV.KPH_TO_MS)
assert ret.steeringAngleDeg == pytest.approx(12.5, abs=0.05)
assert ret.gearShifter == GearShifter.drive
assert ret.cruiseState.available and ret.cruiseState.enabled
assert ret.cruiseState.speed == pytest.approx(100 * CV.KPH_TO_MS)
assert ret.leftBlinker and not ret.rightBlinker
assert not ret.doorOpen
@pytest.mark.parametrize("state, engaged", [(EcmAccState.OFF, False), (EcmAccState.STANDBY, False), (EcmAccState.ENGAGED, True)])
def test_cruise_follows_the_ecm(state, engaged):
cs, parsers, _ = car_state(EngineData={"ACC_State_ECM": state})
assert cs.update(parsers).cruiseState.enabled == engaged
@pytest.mark.parametrize("gear, expected", [(0, GearShifter.park), (1, GearShifter.reverse), (2, GearShifter.neutral), (3, GearShifter.drive)])
def test_gear_lever(gear, expected):
cs, parsers, _ = car_state(GearSelector={"GearLever": gear})
assert cs.update(parsers).gearShifter == expected
def test_gas_press_and_release_have_the_panda_hysteresis():
# A foot held at 10% flickered gas each frame (route 00000007): 10% presses, under 9% releases, as the panda
cs, parsers, _ = car_state()
t = 1_000_000_000
for pedal, pressed in ((9.9, False), (10, True), (9.9, True), (9, True), (8.9, False), (9.9, False), (10, True)):
t += 10_000_000
for parser in parsers.values():
parser.update([(t, required_frames(AccPedal={"AccPedal": pedal}))])
assert cs.update(parsers).gasPressed == pressed, pedal
def test_driver_onoff_is_a_cancel_button():
# Route 22, 418.4 s: the driver's On/Off reached the panda's permission before OP saw the ECM disengage
cs, parsers, _ = car_state()
t = 1_000_000_000
events = []
for pressed in (False, True, True, False):
t += 20_000_000
buttons = {"ACCOnOffBtn": 1, "ACCOnOffBtnInv": 0} if pressed else {"ACCOnOffBtnInv": 1}
for parser in parsers.values():
parser.update([(t, required_frames(CCButtons=buttons))])
events.append([(e.type, e.pressed) for e in cs.update(parsers).buttonEvents if e.type == ButtonType.cancel])
assert events == [[], [(ButtonType.cancel, True)], [], [(ButtonType.cancel, False)]]
def control(lat_active, angle=0., cancel=False):
cc = structs.CarControl()
cc.latActive = lat_active
cc.actuators.steeringAngleDeg = angle
cc.cruiseControl.cancel = cancel
return cc.as_reader()
def controller_state(speed=20., angle=0., brake=False):
cs = type("CS", (), {})()
cs.out = structs.CarState(vEgo=speed, vEgoRaw=speed, steeringAngleDeg=angle, brakePressed=brake)
cs.eucd_pscm_stock_values = {"byte0": 0, "byte4": 0, "byte7": 0, "LKAActive": 0xFF, "EPSTorque": 0}
cs.eucd_ecm_acc_engaged = False
cs.eucd_ecm_standstill_ready = False
cs.eucd_car_hold = False
cs.eucd_acc_distance = 255
cs.eucd_driver_resume = False
cs.eucd_stock_FSM1 = {"ACC_Braking": 0}
cs.eucd_stock_FSM3 = {"ACC_AccelerationRequest": 0., "ACC_Mode": 1, "ACC_NoTargetCancel": 0, "Byte_6": 0, "FrameKind": 0x81, "ACC_Check": 0}
for name in ("FSM0", "FSM4", "WheelRear", "BrakeReqAck", "BrakeHold", "EngineData", "AccHold", "CCButtons"):
setattr(cs, f"eucd_stock_{name}_frames", [])
return cs
def controller():
return CarControllerEUCD({Bus.pt: DBC_NAME}, params())
def test_inactive_sends_zero_angle_and_no_direction():
sends = controller().update(control(False, 10.), controller_state(), 0)[1]
assert [s[0] for s in sends][:2] == [0x262, 0x246]
assert sends[0][1][5] & 0x3 == 0
assert ((sends[0][1][3] & 0x3F) << 8) + sends[0][1][4] == 8192 # 0 deg
def test_active_steering_is_rate_limited_and_50hz():
cc = controller()
new_actuators, sends = cc.update(control(True, 10.), controller_state(), 0)
assert [s[0] for s in sends][:2] == [0x262, 0x246]
assert 0 < new_actuators.steeringAngleDeg <= 0.15 + 1e-3
assert 0x262 not in [s[0] for s in cc.update(control(True, 10.), controller_state(), 0)[1]]
assert sends[0][1][5] & 0x3 == 2 # left
def test_direction_flip_pauses_on_none():
cc = controller()
cc.eucd_apply_steer_prev = 0.05
cc.eucd_apply_steer_dir_prev = 2
cc.eucd_latActive_prev = True
sends = cc.update(control(True, -10.), controller_state(angle=5.), 0)[1]
assert sends[0][1][5] & 0x3 == 0
assert cc.eucd_steer_blocked and cc.eucd_steer_blocked_cnt == 7
def test_pscm_relay_clears_lka_state():
sends = controller().update(control(False), controller_state(angle=4.), 0)[1]
assert sends[1][2] == 2
parser_values = {"LKAActive": 0xFF & 0xF5}
packer = CANPacker(DBC_NAME)
expected = packer.make_can_msg("PSCM1", 2, {**parser_values, "SteeringAngleServo": 4., "LKATorque": 0, "EPSTorque": 0})
assert sends[1][1] == expected[1]
@pytest.mark.parametrize("speed, brake, sent", [(20., False, True), (0., False, False), (20., True, False)])
def test_cancel_only_while_moving_and_off_the_brake(speed, brake, sent):
sends = controller().update(control(False, cancel=True), controller_state(speed, brake=brake), 0)[1]
assert (0x127 in [s[0] for s in sends]) == sent
def test_lka_checksum_matches_the_frame():
packer = CANPacker(DBC_NAME)
_, dat, _ = create_eucd_lka_msg(packer, -7.5, 1)
assert dat[6] == calculate_eucd_lka_checksum(dat)
def test_engine_firmware_identifies_the_v60():
from opendbc.car.fw_versions import match_fw_to_car
fw = structs.CarParams.CarFw(ecu=structs.CarParams.Ecu.engine, address=0x7e0, subAddress=0, brand="volvo",
fwVersion=b"31361041 AJ" + bytes(13))
assert match_fw_to_car([fw], "")[1] == {CAR.VOLVO_V60}
CCBUTTONS = 0x127
# CCButtons frames from V60 routes: idle, time gap increase, time gap decrease
IDLE = bytes.fromhex("88108761a7ff0000")
GAP_INCREASE = bytes.fromhex("88108761a5ff0200")
GAP_DECREASE = bytes.fromhex("88108761a3ff0400")
# increase bit set without its inverted copy cleared: not a press
GAP_INCREASE_NO_INV = bytes.fromhex("88108761a7ff0200")
@pytest.fixture
def car():
cp = params()
return CarStateEUCD(cp), CarStateEUCD.get_can_parsers(cp)
def step(car, t, frames):
cs, parsers = car
for parser in parsers.values():
parser.update([(t, frames)])
return cs.update(parsers)
def button_step(car, t, dat):
return [(be.type, be.pressed) for be in step(car, t, [CanData(CCBUTTONS, dat, 0)]).buttonEvents]
@pytest.mark.parametrize("pressed", [GAP_INCREASE, GAP_DECREASE])
def test_gap_button_press_and_release(car, pressed):
assert button_step(car, 1_000_000, IDLE) == []
assert button_step(car, 2_000_000, pressed) == [(ButtonType.gapAdjustCruise, True)]
assert button_step(car, 3_000_000, pressed) == []
assert button_step(car, 4_000_000, IDLE) == [(ButtonType.gapAdjustCruise, False)]
def test_gap_button_needs_inverted_signal(car):
assert button_step(car, 1_000_000, IDLE) == []
assert button_step(car, 2_000_000, GAP_INCREASE_NO_INV) == []
def test_driver_resume_events(car):
# Resume needs the bit set and its inverted copy cleared, frames from route 8ab
resume = bytes.fromhex("88108761a7df0020")
no_inv = bytes.fromhex("88108761a7ff0020")
assert button_step(car, 1_000_000, IDLE) == []
assert button_step(car, 2_000_000, no_inv) == []
assert button_step(car, 3_000_000, resume) == [(ButtonType.resumeCruise, True)]
assert button_step(car, 4_000_000, resume) == []
assert button_step(car, 5_000_000, IDLE) == [(ButtonType.resumeCruise, False)]
@pytest.mark.parametrize("speed_kph, expected", [(0, []), (40, [(ButtonType.accelCruise, False)])])
def test_set_plus_stopped_is_not_accel(car, speed_kph, expected):
# Stopped, Set+ only sets the speed: an accelCruise there reads as "go" to the planner (route 8b2, 572 s)
packer = CANPacker(DBC_NAME)
events = []
for t, set_kph in enumerate((30, 30, 35)):
msgs = [packer.make_can_msg("EngineData", 0, {"ACC_State_ECM": EcmAccState.ENGAGED}),
packer.make_can_msg("VehicleSpeed1", 0, {"VehicleSpeed": speed_kph}),
packer.make_can_msg("ACC_Speed", 0, {"ACC_Speed": set_kph})]
ret = step(car, 1_000_000 * (t + 1), [CanData(*m) for m in msgs])
events = [(be.type, be.pressed) for be in ret.buttonEvents]
assert events == expected
@pytest.mark.parametrize("tsr_kph, status", [(0, Status.ABSENT), (30, Status.VALID), (80, Status.VALID), (120, Status.VALID)])
def test_tsr_speed_limit(tsr_kph, status):
cs, parsers, _ = car_state(FSM5={"TSR_Speed": tsr_kph})
packer = CANPacker(DBC_NAME)
# the parser learns the FSM5 cadence over repeated frames before the tracker trusts it
for i in range(1, 12):
frame = CanData(*packer.make_can_msg("FSM5", 2, {"TSR_Speed": tsr_kph}))
for parser in parsers.values():
parser.update([(1_000_000_000 + i * 100_000_000, [frame])])
cs.update(parsers)
observation = cs.dashboard_limit.observation
assert observation.status == status
assert observation.speed_mps == pytest.approx(tsr_kph * CV.KPH_TO_MS)
def test_longitudinal_tx_is_50hz_and_keeps_the_relays():
cc = controller()
cs = controller_state()
cs.eucd_stock_CCButtons_frames = [{"ACCResumeBtn": 0, "ACCResumeBtnInv": 1, "ACCSetBtn": 0, "ACCSetBtnInv": 1}]
cs.eucd_ecm_acc_engaged = True
sent = []
for i in range(10):
sent += [s[0] for s in cc.update(control(False), cs, i * 10_000_000)[1]]
assert sent.count(0x270) == sent.count(0x260) == 5 # FSM3, FSM1
assert sent.count(0x127) == 10 # CEM frames relayed to the camera
def test_no_fsm1_fsm3_with_the_ecm_off():
# Route 2c, 837 s: with the ECM off the panda forwards the camera's frames and blocked OP's copies
cc = controller()
cs = controller_state()
sent = []
for i in range(10):
sent += [s[0] for s in cc.update(control(False), cs, i * 10_000_000)[1]]
assert 0x270 not in sent and 0x260 not in sent
def test_lka_press_events(car):
packer = CANPacker(DBC_NAME)
cs, _ = car
presses = []
for t, lka in enumerate((1, 1, 0, 0, 1)):
ret = step(car, 1_000_000 * (t + 1), [CanData(*packer.make_can_msg("CCButtons", 0, {"LKA_State": lka}))])
presses.append(sum(be.type == ButtonType.lkas and be.pressed for be in ret.buttonEvents))
assert cs.eucd_lka_on == bool(lka)
assert presses == [0, 0, 1, 0, 1] # one press per LKA_State flip, none at start
def test_radar_publishes_an_esr_track():
# card crashed on the first valid track: aRel/yvRel/measured are deprecated in the v7 RadarPoint
from opendbc.car.volvo.eucd_params import CANBUS
from opendbc.car.volvo.radar_interface import DELPHI_ESR_TRACK_NAMES, RadarInterface
ri = RadarInterface(params())
packer = CANPacker(DBC[CAR.VOLVO_V60][Bus.radar])
track = {"CAN_TX_TRACK_STATUS": 3, "CAN_TX_TRACK_RANGE": 40., "CAN_TX_TRACK_ANGLE": 0., "CAN_TX_TRACK_RANGE_RATE": -2.}
ret = None
for sweep in range(4):
frames = [CanData(*packer.make_can_msg(name, CANBUS.body, track if name == "Target1" else {})) for name in DELPHI_ESR_TRACK_NAMES]
ret = ri.update([(1_000_000_000 + sweep * 50_000_000, frames)])
assert ret is not None and len(ret.points) == 1
point = ret.points[0]
assert point.dRel == pytest.approx(40., abs=0.1)
assert point.yRel == pytest.approx(0., abs=0.1)
assert point.vRel == pytest.approx(-2., abs=0.01)
def test_stopping_keeps_the_camera_brake():
# Route 2e, 59 s: the planner's -0.15 at the stopping flag dropped the brake to 0 and the car rolled on a climb
cc = controller()
cs = controller_state(speed=0.5)
cs.eucd_ecm_acc_engaged = True
cc.eucd_own = True
cc.eucd_tpl_fsm3 = {"data": dict(cs.eucd_stock_FSM3), "type": {**cs.eucd_stock_FSM3, "FrameKind": 0}}
cc.eucd_tpl_fsm4 = {"Byte_0": 0x55, "ACC_BrakeRequest": 0, "ACC_BrakeTarget": 13332, "Byte_5_b7": 1}
cc.eucd_tpl_fsm0 = {0: {"Byte_0": 0, "ACC_AbortCode": 0, "ACC_Enabled": 1}}
CC = structs.CarControl(enabled=True, latActive=False, longActive=True)
CC.actuators.accel = -0.15
sends = cc.update(CC.as_reader(), cs, 0)[1]
fsm3 = next(s[1] for s in sends if s[0] == 0x270)
assert cc.eucd_stopping and fsm3[2] & 0x3 == 0 # BRAKE
assert fsm3[1] == round((CarControllerEUCDParams.EUCD_STOPPING_ACCEL + 5.04) / 0.04)
@@ -0,0 +1,248 @@
import math
from types import SimpleNamespace
import pytest
from opendbc.car import Bus, DT_CTRL
from opendbc.car.volvo.interface import CarInterface
from opendbc.car.volvo.values import CAR
from opendbc.car.volvo.eucd_carcontroller import CarControllerEUCD as CarController
from opendbc.car.volvo.eucd_params import CarControllerEUCDParams as CarControllerParams, LongMode
from opendbc.car.volvo import eucd_can as volvocan
from opendbc.car.volvo.eucd_can import eucd_next_long_mode
CCP = CarControllerParams
def test_traction_continuous_at_drive_switch():
# Coast and drive traction meet at the DRIVE threshold, like the camera
a = CCP.EUCD_DRIVE_ENTER
coast = volvocan.eucd_fsm3_traction(a, LongMode.COAST) - 256
drive = volvocan.eucd_fsm3_traction(a, LongMode.DRIVE)
assert drive - coast <= 6
def offset(pitch_deg):
return CarController._eucd_slope_brake_offset(SimpleNamespace(orientationNED=[0., math.radians(pitch_deg), 0.]))
def test_uphill_coast_is_not_braking():
# Coast on a 5.4 deg climb is not braking
assert eucd_next_long_mode(LongMode.COAST, -0.84) == LongMode.BRAKE
assert eucd_next_long_mode(LongMode.COAST, -0.84, offset(5.4)) == LongMode.COAST
assert eucd_next_long_mode(LongMode.COAST, -1.5, offset(5.4)) == LongMode.BRAKE
def test_uphill_coast_overshoot_is_not_braking():
# Coast-cap overshoot on a 5 deg climb
assert eucd_next_long_mode(LongMode.COAST, -1.15, offset(5.0)) == LongMode.COAST
assert eucd_next_long_mode(LongMode.COAST, -1.6, offset(5.0)) == LongMode.BRAKE
# Holds down to the usual exit
assert eucd_next_long_mode(LongMode.BRAKE, -0.8, offset(5.0)) == LongMode.BRAKE
def test_downhill_brakes_earlier():
# Downhill brakes earlier
assert eucd_next_long_mode(LongMode.COAST, -0.4) == LongMode.COAST
assert eucd_next_long_mode(LongMode.COAST, -0.4, offset(-1.5)) == LongMode.BRAKE
assert offset(-10.) == CCP.EUCD_DOWNHILL_BRAKE_OFFSET_MAX
# BRAKE exit stays at or below 0
assert eucd_next_long_mode(LongMode.BRAKE, 0.01, offset(-10.)) == LongMode.COAST
def test_slope_offset_fades_out_slow():
cc = SimpleNamespace(orientationNED=[0., math.radians(3.), 0.]) # route 22, 878 s
lo, hi = CCP.EUCD_BRAKE_ENTER_BP
assert CarController._eucd_slope_brake_offset(cc, lo) == 0.
assert CarController._eucd_slope_brake_offset(cc, hi) == CarController._eucd_slope_brake_offset(cc)
assert CarController._eucd_slope_brake_offset(cc, (lo + hi) / 2) == pytest.approx(CarController._eucd_slope_brake_offset(cc) / 2)
def test_flat_unchanged():
assert offset(0.) == 0.
assert CarController._eucd_slope_brake_offset(SimpleNamespace(orientationNED=[])) == 0.
def limited(accel, last):
cc = CarController.__new__(CarController)
return cc._eucd_jerk_limit(accel, last)
def test_jerk_limit_only_cuts_jumps():
assert abs(limited(1.3, 0.0) - CCP.EUCD_JERK_UP * 0.02) < 1e-9 # rising moderate
assert abs(limited(-3.5, -1.0) - (-1.0 - CCP.EUCD_JERK_DOWN * 0.02)) < 1e-9 # braking only cut on jumps
assert limited(-0.4, -0.2) == -0.4 # the planner's own steps pass
# 0 to -3 m/s^2 in 0.25 s, not 0.75 s as before (route 1f: braking started late)
a, frames = 0., 0
while a > -3.:
a, frames = limited(-3., a), frames + 1
assert frames * 0.02 <= 0.26
def test_jerk_limit_reaches_target():
a = 1.3
for _ in range(100):
a = limited(-0.4, a)
assert a == -0.4
def owner():
cc = CarController({Bus.pt: "volvo_v60_2015_pt"}, CarInterface.get_non_essential_params(CAR.VOLVO_V60))
return cc
def car(engaged=True, cam_enabled=1, v=0., standstill=True, hold=False, gas=False):
return SimpleNamespace(eucd_ecm_acc_engaged=engaged, eucd_car_hold=hold, eucd_ecm_standstill_ready=False,
eucd_stock_FSM3={"ACC_NoTargetCancel": 0, "Byte_6": 0, "FrameKind": 0x81, "ACC_Check": 0},
eucd_stock_FSM0_frames=[{"Byte_0": 0, "ACC_AbortCode": 0, "ACC_Enabled": cam_enabled}],
eucd_stock_FSM4_frames=[{"Byte_2": 0, "Byte_0": 0x55, "ACC_BrakeRequest": 0}],
out=SimpleNamespace(vEgo=v, standstill=standstill, gasPressed=gas))
def control(long_active=True, accel=-1.):
return SimpleNamespace(enabled=long_active, longActive=long_active, actuators=SimpleNamespace(accel=accel))
def owning(cc, CS, CC):
"""Templates seen (data and type frames), then OP owns the ECM."""
for kind in (0x81, 0):
CS.eucd_stock_FSM3 = {**CS.eucd_stock_FSM3, "FrameKind": kind}
cc._eucd_ownership(CC, CS)
CS.eucd_stock_FSM3 = {**CS.eucd_stock_FSM3, "FrameKind": 0x81}
assert cc.eucd_own
def test_template_never_keeps_the_camera_ack():
"""The camera's ACC_Check (engaging at standstill) left in the template made the ECM brake in the drive-off (8a3)."""
cc, CS = owner(), car()
CS.eucd_stock_FSM3["ACC_Check"] = 1
cc._eucd_ownership(control(long_active=False), CS)
assert cc.eucd_tpl_fsm3["data"]["ACC_Check"] == 0
assert CS.eucd_stock_FSM3["ACC_Check"] == 1 # the camera's frame untouched
def test_op_owns_the_ecm_at_highway_speed():
# The camera's ACC shown standby whenever OP's long is on, so it never disagrees with OP (routes 1f, 2d)
cc, CS, CC = owner(), car(v=30., standstill=False), control(accel=0.5)
owning(cc, CS, CC)
CS.eucd_stock_FSM0_frames = [{"Byte_0": 0, "ACC_AbortCode": 0, "ACC_Enabled": 0}] # the camera in standby
for _ in range(int(5. / DT_CTRL)):
cc._eucd_ownership(CC, CS)
assert cc.eucd_own and not cc.eucd_stopping
CC.longActive = CC.enabled = False
cc._eucd_ownership(CC, CS)
assert not cc.eucd_own and cc.eucd_exit_standby_frames == 1 # standby until the ECM drops
def test_no_ownership_before_the_templates():
cc, CS = owner(), car(cam_enabled=0) # the camera not engaged yet: nothing clean to replay
cc._eucd_ownership(control(), CS)
assert not cc.eucd_own
def stopped(seconds=3.):
"""OP's stop at standstill, the car holding."""
cc, CS, CC = owner(), car(hold=True, v=5., standstill=False), control()
owning(cc, CS, CC)
CS.out.vEgo, CS.out.standstill = 0., True
CS.eucd_stock_FSM0_frames = [{"Byte_0": 0, "ACC_AbortCode": 0, "ACC_Enabled": 0}]
for _ in range(int(seconds / DT_CTRL)):
cc._eucd_ownership(CC, CS)
assert cc.eucd_holding and cc.eucd_standstill == (seconds >= CCP.EUCD_STANDSTILL_DELAY)
return cc, CC, CS
def fsm4_brake_requested(cc, CS):
dat = cc._eucd_relay_fsm4(CS)[0][1]
return bool((dat[5] >> 6) & 1)
def test_driver_gas_in_the_stop_drives_off_engaged():
cc, CC, CS = stopped()
CS.out.gasPressed, CC.longActive = True, False
cc._eucd_ownership(CC, CS)
assert cc.eucd_own and cc.eucd_driver_gas and cc.eucd_driving_off
assert not cc.eucd_standstill and not cc.eucd_holding
assert not fsm4_brake_requested(cc, CS) # no brake from OP on the gas
def test_disengaged_on_the_gas_ends_the_stop():
cc, CC, CS = stopped()
CS.out.gasPressed, CC.longActive, CC.enabled = True, False, False
cc._eucd_ownership(CC, CS)
assert not cc.eucd_own and not cc.eucd_driver_gas
def test_gas_release_keeps_owning_until_op_long_is_back():
cc, CC, CS = stopped()
CS.out.gasPressed, CC.longActive = True, False
cc._eucd_ownership(CC, CS)
CS.out.gasPressed = False # pedal released, OP's long back a frame later
cc._eucd_ownership(CC, CS)
assert cc.eucd_own and cc.eucd_driver_gas
CC.longActive = True
cc._eucd_ownership(CC, CS)
assert cc.eucd_own and not cc.eucd_driver_gas
def test_short_stop_drives_off_on_traction():
cc, CC, CS = stopped(seconds=1.)
CC.actuators.accel = 0.5
cc._eucd_ownership(CC, CS)
assert cc.eucd_own and not cc.eucd_stopping and not cc.eucd_holding and not cc.eucd_standstill
def test_long_stop_waits_for_the_resume():
cc, CC, CS = stopped()
CC.actuators.accel = 0.5
cc._eucd_ownership(CC, CS)
assert cc.eucd_stopping and cc.eucd_holding and cc.eucd_standstill
def test_ecm_in_standstill_waits_for_the_resume():
cc, CC, CS = stopped(seconds=1.)
CS.eucd_ecm_standstill_ready, CC.actuators.accel = True, 0.5
cc._eucd_ownership(CC, CS)
assert cc.eucd_stopping and cc.eucd_holding
def resume_buttons_after(driver_resume, own, ecm_ready=True):
"""One frame stopped in standstill: the Resume hold frames left and the drive-off request."""
cc = owner()
cc.frame = 1000
cc.eucd_own = own
CS = SimpleNamespace(out=SimpleNamespace(cruiseState=SimpleNamespace(enabled=True, standstill=True), vEgo=0.),
eucd_acc_distance=0, eucd_stock_CCButtons_frames=[], eucd_driver_resume=driver_resume,
eucd_ecm_standstill_ready=ecm_ready)
cc._eucd_resume_buttons(SimpleNamespace(cruiseControl=SimpleNamespace(resume=False)), CS, [])
return cc.eucd_resume_hold_frames, cc.eucd_drive_off_request
def test_driver_resume_drives_off_ops_stop():
assert resume_buttons_after(True, True) == (CCP.EUCD_RESUME_HOLD_FRAMES - 1, True)
assert resume_buttons_after(False, True) == (0, False)
assert resume_buttons_after(True, False) == (0, False) # the camera's own stop takes it by itself
def test_driver_resume_does_not_wait_for_the_ecm_ready():
# The ECM releases its hold on the driver's Resume at once (route 38, 42 s)
assert resume_buttons_after(True, True, ecm_ready=False) == (CCP.EUCD_RESUME_HOLD_FRAMES - 1, True)
def test_engaged_at_a_stop_starts_in_standstill():
# Engaged behind a stopped lead that soon left: OP must hold and resume, not ask traction of a holding car (route 38, 40 s)
cc, CS, CC = owner(), car(hold=True), control(accel=0.6)
owning(cc, CS, CC)
assert cc.eucd_stopping and cc.eucd_standstill
for _ in range(10):
cc._eucd_ownership(CC, CS)
assert cc.eucd_stopping and cc.eucd_holding and cc.eucd_standstill
def test_lead_icon_follows_op_not_the_template():
# Templates kept from different moments flickered the lead icon on the dash (route 37, seg 3)
cc = owner()
cc.eucd_own = True
cc.eucd_tpl_fsm0 = {0x10: {"Byte_0": 0x10, "ACC_FrontCar": 0}, 0x15: {"Byte_0": 0x15, "ACC_FrontCar": 1}}
for lead in (True, False):
assert {cc._eucd_fsm0({"Byte_0": b}, lead)["ACC_FrontCar"] for b in (0x10, 0x15, 0x00)} == {int(lead)}
@@ -0,0 +1,273 @@
import copy
import math
import pytest
from opendbc.can.packer import CANPacker
from opendbc.can.parser import CANParser
from opendbc.car.volvo import eucd_can as volvocan
from opendbc.car.volvo.eucd_params import CarControllerEUCDParams as CarControllerParams, EcmAccState, LongMode
DBC = "volvo_v60_2015_pt"
FSM3 = 0x270
# stock FSM3 frames from the camera, route 00000808 (ACC engaged); b4=0x81 data, 0x00 type
STOCK = {
("data", LongMode.BRAKE): ["aa7ad40081000000", "aa7ed40081000000"],
("data", LongMode.COAST): ["aa6ed5b881000000", "aa78d5dd81000000"],
("data", LongMode.DRIVE): ["aa98d65f81000000", "aa88d61d81000000"],
("type", LongMode.BRAKE): ["0082000000000000", "0076000000000000"],
("type", LongMode.COAST): ["007a01ec00000000", "007c01f300000000"],
("type", LongMode.DRIVE): ["0088022100000000", "008a022600000000"],
}
ALL_FRAMES = [(kind, mode, bytes.fromhex(h)) for (kind, mode), hs in STOCK.items() for h in hs]
def parse(name: str, addr: int, freq: int, dat: bytes) -> dict:
cp = CANParser(DBC, [(name, freq)], 0)
cp.update([(0, [(addr, dat, 0)])])
return copy.copy(cp.vl[name])
def parse_fsm3(dat: bytes) -> dict:
return parse("FSM3", FSM3, 50, dat)
def build(stock: bytes, accel=None, mode=None) -> bytes:
fsm3 = parse_fsm3(stock)
if accel is None:
accel = fsm3["ACC_AccelerationRequest"]
return volvocan.create_eucd_longitudinal(CANPacker(DBC), fsm3, accel, int(fsm3["ACC_Check"]), mode)[1]
@pytest.mark.parametrize("kind,mode,stock", ALL_FRAMES)
def test_relay_is_byte_identical(kind, mode, stock):
assert build(stock) == stock
@pytest.mark.parametrize("kind,mode,stock", ALL_FRAMES)
def test_stock_mode_and_traction_reproduce_frame(kind, mode, stock):
# Camera's own mode leaves Byte_2 untouched
out = build(stock, mode=mode)
assert out[2] == stock[2]
assert out[:2] == stock[:2] and out[4:] == stock[4:]
if mode == LongMode.BRAKE:
assert out[3] == 0
@pytest.mark.parametrize("kind,stock_mode,stock", ALL_FRAMES)
@pytest.mark.parametrize("mode", list(LongMode))
def test_op_mode_keeps_cadence(kind, stock_mode, stock, mode):
accel = {LongMode.BRAKE: -1.5, LongMode.COAST: -0.1, LongMode.DRIVE: 0.8}[mode]
out = build(stock, accel=accel, mode=mode)
assert out[2] & 0x03 == mode
assert out[2] & 0xFC == stock[2] & 0xFC # 0xD4 data / 0x00 type kept
assert out[4] == stock[4] # data/type marker kept
assert out[0] == stock[0] # standstill and status bits kept
assert out[1] == math.floor((accel + 5.04) / 0.04 + 0.5) # packer rounds half up
assert out[3] == volvocan.eucd_fsm3_traction(accel, mode)
def test_traction():
assert volvocan.eucd_fsm3_traction(-2.0, LongMode.BRAKE) == 0
assert volvocan.eucd_fsm3_traction(1.0, LongMode.DRIVE) == 91
assert volvocan.eucd_fsm3_traction(2.0, LongMode.DRIVE) == 188
assert volvocan.eucd_fsm3_traction(-0.5, LongMode.DRIVE) == 0
assert volvocan.eucd_fsm3_traction(-0.1, LongMode.COAST) == 256 - 18
assert volvocan.eucd_fsm3_traction(0.5, LongMode.COAST) == 0xFF # never non-negative in COAST
def test_mode_hysteresis():
CCP = CarControllerParams
m = LongMode.COAST
m = volvocan.eucd_next_long_mode(m, -0.4)
assert m == LongMode.COAST
m = volvocan.eucd_next_long_mode(m, CCP.EUCD_BRAKE_ENTER - 0.01)
assert m == LongMode.BRAKE
m = volvocan.eucd_next_long_mode(m, CCP.EUCD_BRAKE_EXIT - 0.05) # stays braking until BRAKE_EXIT
assert m == LongMode.BRAKE
m = volvocan.eucd_next_long_mode(m, CCP.EUCD_BRAKE_EXIT + 0.05)
assert m == LongMode.COAST
m = volvocan.eucd_next_long_mode(m, 0.06)
assert m == LongMode.COAST
m = volvocan.eucd_next_long_mode(m, 0.1)
assert m == LongMode.DRIVE
m = volvocan.eucd_next_long_mode(m, 0.05)
assert m == LongMode.DRIVE
m = volvocan.eucd_next_long_mode(m, -1.0) # hard brake: DRIVE straight to BRAKE
assert m == LongMode.BRAKE
m = volvocan.eucd_next_long_mode(m, 1.0)
assert m == LongMode.DRIVE
def test_brake_enters_earlier_when_slower():
# Route 22: below 20 km/h the camera brakes from -0.1; coasting there let D creep the car toward the lead
kph = 1 / 3.6
assert volvocan.eucd_next_long_mode(LongMode.COAST, -0.15, v_ego=8 * kph) == LongMode.BRAKE
assert volvocan.eucd_next_long_mode(LongMode.COAST, -0.15, v_ego=30 * kph) == LongMode.COAST
assert volvocan.eucd_next_long_mode(LongMode.COAST, -0.35, v_ego=30 * kph) == LongMode.BRAKE
# highway unchanged
assert volvocan.eucd_next_long_mode(LongMode.COAST, -0.45, v_ego=100 * kph) == LongMode.COAST
assert volvocan.eucd_next_long_mode(LongMode.COAST, -0.55, v_ego=100 * kph) == LongMode.BRAKE
# slow: stays braking until OP asks for traction, never left with a decel request
assert volvocan.eucd_next_long_mode(LongMode.BRAKE, -0.01, v_ego=8 * kph) == LongMode.BRAKE
assert volvocan.eucd_next_long_mode(LongMode.BRAKE, 0.1, v_ego=8 * kph) == LongMode.DRIVE
for v in (0., 10., 25., 40., 120.):
enter, exit_ = volvocan.eucd_brake_thresholds(v * kph)
assert enter < exit_ <= 0.
FSM4 = 0x31A
FSM1 = 0x260
# stock camera frames, route 00000808 (ACC engaged)
STOCK_FSM4 = ["aaf1343a8ef24600", "aaf15e5e8af3cb00", "aaf173748ab40b00", "aaf173738ab3f800"] # Byte_5 0xF2/0xF3 brake, 0xB4/0xB3 not
STOCK_FSM1 = ["ffffb80049e37408", "5ad4bc0049e37408", "46ff000000e31408", "23f4040000e31408"] # Byte_2 data 0xB8/0xBC, type 0x00/0x04
@pytest.mark.parametrize("stock", [bytes.fromhex(h) for h in STOCK_FSM4])
def test_fsm4_relay_is_byte_identical(stock):
assert volvocan.create_eucd_fsm4(CANPacker(DBC), parse("FSM4", FSM4, 33, stock), 0.0)[1] == stock
def fsm4(stock: bytes, accel: float, mode) -> bytes:
return volvocan.create_eucd_fsm4(CANPacker(DBC), parse("FSM4", FSM4, 33, stock), accel, mode)[1]
@pytest.mark.parametrize("stock", [bytes.fromhex(h) for h in STOCK_FSM4])
@pytest.mark.parametrize("accel", [-3.5, -2.0, -1.0, -0.6, -0.1])
def test_fsm4_op_brake_sets_value_from_accel(stock, accel):
out = fsm4(stock, accel, LongMode.BRAKE)
value = (out[5] << 8) | out[6]
assert value == volvocan.eucd_fsm4_brake_value(accel, True)
assert value & 0xC000 == 0xC000 # bit15 always, bit14 = hydraulic brake request
assert out[:5] == stock[:5] and out[7:] == stock[7:]
@pytest.mark.parametrize("accel, camera", [(-3.0, 12568), (-2.5, 12688), (-2.0, 12821), (-1.0, 13084), (-0.5, 13212)])
def test_fsm4_brake_value_as_the_camera(accel, camera):
# Route 29, 1110 s: the old map asked ~0.5 m/s^2 less than the camera at -2.8 and the stop ended at 1.5 m
assert abs((volvocan.eucd_fsm4_brake_value(accel, True) & 0x3FFF) - camera) <= 10
def test_fsm4_brake_value_matches_stock_levels():
# Matches the stock Byte_5 levels
assert volvocan.eucd_fsm4_brake_value(-3.5, True) >> 8 == 0xF0
assert volvocan.eucd_fsm4_brake_value(0.0, True) >> 8 == 0xF4
values = [volvocan.eucd_fsm4_brake_value(a / 10, True) for a in range(-40, 5)]
assert values == sorted(values) # stronger decel, lower value
# Smooth: a small step moves a few counts
assert all(abs(volvocan.eucd_fsm4_brake_value(a / 50, True) - volvocan.eucd_fsm4_brake_value((a + 1) / 50, True)) < 16 for a in range(-200, 10))
@pytest.mark.parametrize("stock", [bytes.fromhex(h) for h in STOCK_FSM4[2:]])
@pytest.mark.parametrize("mode", [LongMode.COAST, LongMode.DRIVE])
def test_fsm4_no_brake_keeps_camera_value(stock, mode):
assert fsm4(stock, 0.3, mode) == stock
@pytest.mark.parametrize("stock", [bytes.fromhex(h) for h in STOCK_FSM4[:2]])
@pytest.mark.parametrize("mode", [LongMode.COAST, LongMode.DRIVE])
def test_fsm4_camera_brake_cleared_when_op_does_not_brake(stock, mode):
out = fsm4(stock, 0.3, mode)
value = (out[5] << 8) | out[6]
assert value == volvocan.eucd_fsm4_brake_value(0.3, False)
assert value & 0xC000 == 0x8000
assert out[:5] == stock[:5] and out[7:] == stock[7:]
@pytest.mark.parametrize("stock", [bytes.fromhex(h) for h in STOCK_FSM1])
def test_fsm1_relay_is_byte_identical(stock):
assert volvocan.create_eucd_radar(CANPacker(DBC), parse("FSM1", FSM1, 50, stock))[1] == stock
@pytest.mark.parametrize("stock", [bytes.fromhex(h) for h in STOCK_FSM1])
@pytest.mark.parametrize("mode", list(LongMode))
def test_fsm1_brake_bit_follows_op(stock, mode):
out = volvocan.create_eucd_radar(CANPacker(DBC), parse("FSM1", FSM1, 50, stock), mode)[1]
assert out[2] == (stock[2] & ~0x04) | (0x04 if mode == LongMode.BRAKE else 0)
assert out[:2] == stock[:2] and out[3:] == stock[3:]
WHEEL_REAR_ADDR = 0x220
BRAKE_REQ_ACK_ADDR = 0x299
# Stock WheelRear and BrakeReqAck frames, route 816
STOCK_WHEEL_REAR = ["8b11e000a2577a30", "8b11e400a245a216", "8b11e500a1f6a1d3"]
STOCK_BRAKE_REQ_ACK = ["40054c020dff2235", "4005480201f72239"]
@pytest.mark.parametrize("stock", [bytes.fromhex(h) for h in STOCK_WHEEL_REAR])
@pytest.mark.parametrize("standby", [False, True])
def test_wheel_rear_relay_to_camera(stock, standby):
addr, dat, bus = volvocan.create_eucd_cam_wheel_status(CANPacker(DBC), parse("WheelRear", WHEEL_REAR_ADDR, 50, stock), standby)
assert (addr, bus) == (WHEEL_REAR_ADDR, 2)
# standby: no brake request (bit2) nor ACC brake applied (bit0), 0xE5 -> 0xE0, and no hold (b0 bit6)
assert dat[2] == (stock[2] & ~0x05 if standby else stock[2])
assert dat[0] == (stock[0] & ~0x40 if standby else stock[0])
assert dat[1] == stock[1] and dat[3:] == stock[3:]
@pytest.mark.parametrize("stock", [bytes.fromhex(h) for h in STOCK_BRAKE_REQ_ACK])
@pytest.mark.parametrize("standby", [False, True])
def test_brake_req_ack_relay_to_camera(stock, standby):
addr, dat, bus = volvocan.create_eucd_cam_brake_request_ack(CANPacker(DBC), parse("BrakeReqAck", BRAKE_REQ_ACK_ADDR, 50, stock), standby)
assert (addr, bus) == (BRAKE_REQ_ACK_ADDR, 2)
assert dat[5] == (stock[5] | 0x08 if standby else stock[5]) # 0xF7 -> 0xFF
assert dat[0] == (stock[0] & ~0x80 if standby else stock[0])
assert dat[1:5] == stock[1:5] and dat[6:] == stock[6:]
FSM0 = 0x51
# Camera FSM0 before and after an abort, route 816
FSM0_OK = bytes.fromhex("15e3860091955f7a")
FSM0_ABORT = bytes.fromhex("15e3821091955f7e")
def fsm0(stock: bytes, ecm_engaged: bool) -> bytes:
return volvocan.create_eucd_fsm0(CANPacker(DBC), parse("FSM0", FSM0, 100, stock), ecm_engaged)[1]
@pytest.mark.parametrize("stock", [FSM0_OK, FSM0_ABORT])
def test_fsm0_relay_is_byte_identical(stock):
assert fsm0(stock, True) == stock
def test_fsm0_never_enabled_without_ecm():
out = fsm0(FSM0_OK, False)
assert out[2] == FSM0_OK[2] & ~0x04
assert out[:2] == FSM0_OK[:2] and out[3:] == FSM0_OK[3:]
ENGINE_DATA = 0x12A
# Stock 0x12A Byte_4: 0xA8 standby, 0x98 off, 0xB8 engaged
@pytest.mark.parametrize("b4,state", [(0xA8, EcmAccState.STANDBY), (0x98, EcmAccState.OFF), (0xB8, EcmAccState.ENGAGED)])
def test_ecm_acc_state_decoding(b4, state):
dat = bytes([0xEA, 0x00, 0xC7, 0xF8, b4, 0xF8, 0xE5, 0x7A])
assert int(parse("EngineData", ENGINE_DATA, 66, dat)["ACC_State_ECM"]) == state
def test_resume_button_copies_the_cem_frame():
stock = bytes.fromhex("88108761a7ff0000") # CEM's CCButtons, no button pressed (route 89e)
addr, dat, bus = volvocan.create_eucd_resume_button(CANPacker(DBC), parse("CCButtons", 0x127, 50, stock))
assert (addr, bus) == (0x127, 0)
pressed = parse("CCButtons", 0x127, 50, dat)
assert pressed["ACCResumeBtn"] == 1 and pressed["ACCResumeBtnInv"] == 0
# only the Resume bits differ from the CEM's frame: b7 bit5 set, its inverted copy b5 bit5 cleared
expected = bytearray(stock)
expected[5] &= ~0x20
expected[7] |= 0x20
assert dat == bytes(expected)
@pytest.mark.parametrize("standby", [False, True])
def test_camera_buttons_engaging_released_in_standby(standby):
# Set+ to raise the ECM's speed would engage the camera's ACC while it is shown standby
packer = CANPacker(DBC)
pressed = {"ACCSetBtn": 1, "ACCSetBtnInv": 0, "ACCMinusBtn": 1, "ACCMinusBtnInv": 0, "ACCResumeBtn": 1, "ACCResumeBtnInv": 0,
"ACCOnOffBtn": 0, "ACCOnOffBtnInv": 1, "TimeGapIncreaseBtn": 1, "TimeGapIncreaseBtnInv": 0, "LKA_State": 1}
stock = packer.make_can_msg("CCButtons", 0, pressed)[1]
out = parse("CCButtons", 0x127, 66, volvocan.create_eucd_cam_button(packer, parse("CCButtons", 0x127, 66, stock), standby)[1])
for btn in ("ACCSetBtn", "ACCMinusBtn", "ACCResumeBtn"):
assert out[btn] == (0 if standby else 1) and out[btn + "Inv"] == (1 if standby else 0)
assert out["TimeGapIncreaseBtn"] == 1 and out["LKA_State"] == 1 and out["ACCOnOffBtnInv"] == 1 # the rest as the CEM's
@@ -4,7 +4,7 @@ from pathlib import Path
from unittest.mock import patch
import pytest
from opendbc.car import car_helpers
from opendbc.car import car_helpers, fw_versions
from opendbc.car.can_definitions import CanData
from opendbc.car.ford.discovery import normal_bus_query_brand
from opendbc.car.hyundai.discovery import normal_bus_topology as hyundai_probe
@@ -103,3 +103,57 @@ def test_discovery_fix_keeps_reported_irq_fault_blocking():
ci, _, _, _ = discover()
assert blocking_fault_mask(8, ci.CP)
assert blocking_fault_list([log.PandaState.FaultType.interruptRateCan2], ci.CP)
def v60_rows():
# Live V60 CAN as in route 00000004: its fingerprint and EngineData mirrored on buses 0 and 2, the ESR on bus 1
from opendbc.car.volvo.fingerprints import FINGERPRINTS
addrs = set(FINGERPRINTS[CAR.VOLVO_V60][0]) | {0x12A}
rows = [CanData(a, bytes(8), bus) for bus in (0, 2) for a in sorted(addrs)]
return rows + [CanData(a, bytes(8), 1) for a in range(0x500, 0x540)]
def test_v60_layout_is_its_own():
from opendbc.car.volvo.discovery import V60_BUS_LAYOUT, v60_bus_topology
assert v60_bus_topology(fingerprint(v60_rows()))
assert not normal_bus_topology(fingerprint(v60_rows()))
assert not v60_bus_topology(fingerprint(frames())) # Polestar
for key in V60_BUS_LAYOUT:
assert not v60_bus_topology(fingerprint([f for f in v60_rows() if (f.src, f.address) != key]))
# GM shares FSM1/EngineData addresses, not FSM0/FSM3
gm = [CanData(a, bytes(8), bus) for bus in (0, 2) for a in (0x12A, 0x260, 0x262)]
assert not v60_bus_topology(fingerprint(gm))
def test_v60_queries_only_its_engine_on_bus0_without_the_obd_scan():
from opendbc.car import structs
rows = v60_rows()
peer = CapturedCan()
peer.recv = lambda wait_for_one=False: (setattr(peer, 'clock', peer.clock + .01), [rows])[1]
engine = structs.CarParams.CarFw(ecu=structs.CarParams.Ecu.engine, address=0x7e0, bus=0, brand='volvo',
fwVersion=b'31361041 AJ\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00',
request=[bytes.fromhex('22f1a2')], responseAddress=0x7e8)
with patch.dict(car_helpers.os.environ, {'FINGERPRINT': '', 'SKIP_FW_QUERY': '', 'DISABLE_FW_CACHE': ''}), \
patch.object(car_helpers.time, 'monotonic', side_effect=lambda: peer.clock), \
patch.object(car_helpers.time, 'sleep', side_effect=lambda seconds: setattr(peer, 'clock', peer.clock + seconds)), \
patch.object(car_helpers, 'get_present_ecus', return_value=set()) as present, \
patch.object(car_helpers, 'get_fw_versions_ordered', return_value=[]) as generic, \
patch.object(car_helpers, 'get_fw_versions', return_value=[engine]) as normal:
ci = car_helpers.get_car(peer.recv, peer.send, peer.switches.append, False, False)
assert peer.switches and set(peer.switches) == {False}
assert all(f.src == 0 for f in peer.sent)
normal.assert_called_once()
assert normal.call_args.kwargs == {'query_brand': 'volvo', 'normal_bus_only': True}
present.assert_not_called()
generic.assert_not_called()
assert ci.CP.carFingerprint == CAR.VOLVO_V60
assert str(ci.CP.fingerprintSource) == 'fw'
def test_v60_firmware_request_cannot_enter_all_brand_fallback():
assert 'volvo' not in fw_versions.get_brand_ecu_matches({(0x7e8, None, 0)})
assert all(brand != 'volvo' for brand, _, _ in fw_versions.firmware_requests())
requests = fw_versions.firmware_requests('volvo')
assert len(requests) == 1
assert requests[0][2].bus == 0
assert requests[0][2].request == [bytes.fromhex('22f1a2')]
+21 -3
View File
@@ -1,14 +1,15 @@
from dataclasses import dataclass, field
from enum import IntFlag
from opendbc.car import Bus, CarSpecs, DbcDict, PlatformConfig, Platforms
from opendbc.car import Bus, CarSpecs, DbcDict, PlatformConfig, Platforms, uds
from opendbc.car.structs import CarParams
from opendbc.car.common.conversions import Conversions as CV
from opendbc.car.docs_definitions import CarDocs, CarHarness, CarParts
from opendbc.car.fw_query_definitions import FwQueryConfig
from opendbc.car.fw_query_definitions import FwQueryConfig, Request, p16
from opendbc.car.lateral import AngleSteeringLimits
# C1 support is adapted from the original dragonpilot V40 port:
# https://github.com/dragonpilot/dragonpilot/commit/773dce507082d931236b64dca8024dce9625446f
# V60 (EUCD) support is adapted from sunnypilot's volvo_oplong port.
Ecu = CarParams.Ecu
@@ -16,6 +17,7 @@ class VolvoSafetyFlags(IntFlag):
SPA = 1
C1 = 2
LCA2_MOD15 = 4
EUCD = 8
class CarControllerParams:
@@ -54,6 +56,11 @@ class VolvoSPAPlatformConfig(PlatformConfig):
Bus.pt: 'volvo_front_1_spa',
})
@dataclass
class VolvoEUCDPlatformConfig(PlatformConfig):
dbc_dict: DbcDict = field(default_factory=lambda: {Bus.pt: 'volvo_v60_2015_pt', Bus.radar: 'ESR'})
class CAR(Platforms):
VOLVO_V40 = VolvoC1PlatformConfig(
[VolvoCarDocs("Volvo V40 2013-19")], CarSpecs(mass=1610, wheelbase=2.647, steerRatio=14.7, centerToFrontRatio=0.44, minSteerSpeed=1.0 * CV.KPH_TO_MS)
@@ -86,6 +93,17 @@ class CAR(Platforms):
centerToFrontRatio=0.52,
),
)
VOLVO_V60 = VolvoEUCDPlatformConfig(
[VolvoCarDocs("Volvo V60 2010-18")],
# minSteerSpeed stays 0: EUCD_MIN_STEER_SPEED is the port's limit, above 0 an alert fires at every first stop
CarSpecs(mass=1750, wheelbase=2.776, steerRatio=15.0, centerToFrontRatio=0.44, minSteerSpeed=0.),
)
FW_QUERY_CONFIG = FwQueryConfig(requests=[], fw_version_regex=br"(?!)")
# The V60's CAN fingerprint is not exhaustive: it is identified by its engine FW. The others by CAN only.
VOLVO_VERSION_REQUEST = bytes([uds.SERVICE_TYPE.READ_DATA_BY_IDENTIFIER]) + p16(0xf1a2)
VOLVO_VERSION_RESPONSE = bytes([uds.SERVICE_TYPE.READ_DATA_BY_IDENTIFIER + 0x40]) + p16(0xf1a2)
FW_QUERY_CONFIG = FwQueryConfig(
requests=[Request([VOLVO_VERSION_REQUEST], [VOLVO_VERSION_RESPONSE], bus=0, brand_query_only=True)],
fw_version_regex=br"[0-9]{8} [A-Z]{2}\x00{13}",
)
DBC = CAR.create_dbc_map()
@@ -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";
+191 -25
View File
@@ -1,6 +1,5 @@
VERSION ""
NS_ :
NS_DESC_
CM_
@@ -44,10 +43,27 @@ BO_ 16 SAS0: 8 SAS
SG_ SteeringAngle : 53|14@0+ (0.0445,0) [0|65535] "degrees" XXX
BO_ 32 AccPedal: 8 XXX
SG_ AccPedal : 17|10@0+ (0.1,0) [0|100.0] "%" XXX
SG_ AccPedal : 17|10@0+ (0.1,0) [0|102.3] "%" XXX
BO_ 81 FSM0: 8 FSM
SG_ ACCStatus : 18|3@0+ (1,0) [0|7] "" XXX
SG_ ACC_FrontCar : 16|1@0+ (1,0) [0|1] "" XXX
SG_ ACC_Available : 17|1@0+ (1,0) [0|7] "" XXX
SG_ ACC_Enabled : 18|1@0+ (1,0) [0|1] "" XXX
SG_ ACC_BrakeAlert : 27|1@0+ (1,0) [0|1] "" XXX
SG_ Byte_0 : 7|8@0+ (1,0) [0|255] "" XXX
SG_ Byte_1 : 15|8@0+ (1,0) [0|255] "" XXX
SG_ Byte_2_b7_3 : 23|5@0+ (1,0) [0|31] "" XXX
SG_ ACC_AbortCode : 31|8@0+ (1,0) [0|255] "" XXX
SG_ Byte_4 : 39|8@0+ (1,0) [0|255] "" XXX
SG_ Byte_5 : 47|8@0+ (1,0) [0|255] "" XXX
SG_ Byte_6 : 55|8@0+ (1,0) [0|255] "" XXX
SG_ Byte_7 : 63|8@0+ (1,0) [0|255] "" XXX
BO_ 99 GearSelector: 8 XXX
SG_ GearLever : 54|2@0+ (1,0) [0|3] "" XXX
BO_ 112 ButtonPanel: 8 XXX
SG_ Console_Button_Pressed : 18|1@0+ (1,0) [0|1] "" XXX
BO_ 277 NEW_MSG_7: 8 XXX
SG_ NEW_SIGNAL_1 : 39|16@0+ (1,0) [0|65535] "" XXX
@@ -65,6 +81,20 @@ BO_ 295 CCButtons: 8 CEM
SG_ ACCOnOffBtn : 59|1@0+ (1,0) [0|1] "" XXX
SG_ ACCResumeBtn : 61|1@0+ (1,0) [0|1] "" XXX
SG_ ACCSetBtn : 63|1@0+ (1,0) [0|1] "" XXX
SG_ Byte_0 : 7|8@0+ (1,0) [0|255] "" XXX
SG_ Byte_1 : 15|8@0+ (1,0) [0|255] "" XXX
SG_ Byte_2_b7_3 : 23|5@0+ (1,0) [0|31] "" XXX
SG_ LKA_State : 18|1@0+ (1,0) [0|1] "" XXX
SG_ Byte_2_b1_0 : 17|2@0+ (1,0) [0|3] "" XXX
SG_ Byte_3 : 31|8@0+ (1,0) [0|255] "" XXX
SG_ Byte_4_b7_3 : 39|5@0+ (1,0) [0|31] "" XXX
SG_ Byte_5_b6 : 46|1@0+ (1,0) [0|1] "" XXX
SG_ Byte_5_b4 : 44|1@0+ (1,0) [0|1] "" XXX
SG_ Byte_5_b2_0 : 42|3@0+ (1,0) [0|7] "" XXX
SG_ Byte_6_b7_3 : 55|5@0+ (1,0) [0|31] "" XXX
SG_ Byte_7_b6 : 62|1@0+ (1,0) [0|1] "" XXX
SG_ Byte_7_b4 : 60|1@0+ (1,0) [0|1] "" XXX
SG_ Byte_7_b2_0 : 58|3@0+ (1,0) [0|7] "" XXX
BO_ 298 EngineData: 8 XXX
SG_ NEW_SIGNAL_1 : 1|10@0+ (1,0) [0|1023] "" XXX
@@ -73,13 +103,25 @@ BO_ 298 EngineData: 8 XXX
SG_ NEW_SIGNAL_2 : 33|10@0- (1,0) [0|7] "" XXX
SG_ NEW_SIGNAL_3 : 34|1@0+ (1,0) [0|1] "" XXX
SG_ NEW_SIGNAL_4 : 35|1@0+ (1,0) [0|1] "" XXX
SG_ NEW_SIGNAL_5 : 36|1@0+ (1,0) [0|1] "" XXX
SG_ NEW_SIGNAL_6 : 37|1@0+ (1,0) [0|1] "" XXX
SG_ ACC_State_ECM : 37|2@0+ (1,0) [0|3] "" XXX
SG_ BrakePressed : 38|1@0+ (1,0) [0|1] "" XXX
SG_ EngineRpm : 52|13@0+ (1,0) [0|8000] "" XXX
SG_ Byte_0_b7_3 : 7|5@0+ (1,0) [0|31] "" XXX
SG_ Byte_2 : 23|8@0+ (1,0) [0|255] "" XXX
SG_ Byte_3_b7_2 : 31|6@0+ (1,0) [0|63] "" XXX
SG_ Byte_4_b7 : 39|1@0+ (1,0) [0|1] "" XXX
SG_ Byte_6_b7_5 : 55|3@0+ (1,0) [0|7] "" XXX
BO_ 307 NEW_MSG_133: 8 XXX
SG_ Brake : 14|7@0+ (1,0) [0|127] "" XXX
BO_ 307 BrakeLevel: 8 XXX
SG_ Byte_0 : 7|8@0+ (1,0) [0|255] "" XXX
SG_ Byte_1_b7 : 15|1@0+ (1,0) [0|1] "" XXX
SG_ BrakeLevel : 14|7@0+ (1,0) [0|127] "" XXX
SG_ Byte_2 : 23|8@0+ (1,0) [0|255] "" XXX
SG_ Byte_3 : 31|8@0+ (1,0) [0|255] "" XXX
SG_ Byte_4 : 39|8@0+ (1,0) [0|255] "" XXX
SG_ Byte_5 : 47|8@0+ (1,0) [0|255] "" XXX
SG_ Byte_6 : 55|8@0+ (1,0) [0|255] "" XXX
SG_ Byte_7 : 63|8@0+ (1,0) [0|255] "" XXX
BO_ 328 VehicleSpeed1: 8 XXX
SG_ BrakePressure2 : 33|10@0+ (1,0) [0|63] "" XXX
@@ -93,40 +135,78 @@ BO_ 336 NEW_MSG_8: 8 XXX
SG_ NEW_SIGNAL_4 : 51|12@0+ (1,0) [0|4095] "" XXX
BO_ 359 ACC_Speed: 8 XXX
SG_ Byte_0_b7_1 : 7|7@0+ (1,0) [0|127] "" XXX
SG_ ACC_Speed : 0|8@0+ (1,0) [0|255] "km/h" XXX
SG_ GasPedal : 51|12@0- (1,0) [0|255] "" XXX
SG_ GasPressed : 52|1@0+ (1,0) [0|1] "" XXX
SG_ Byte_1_b0 : 8|1@0+ (1,0) [0|1] "" XXX
SG_ Byte_2 : 23|8@0+ (1,0) [0|255] "" XXX
SG_ Byte_3 : 31|8@0+ (1,0) [0|255] "" XXX
SG_ Byte_4 : 39|8@0+ (1,0) [0|255] "" XXX
SG_ Byte_5 : 47|8@0+ (1,0) [0|255] "" XXX
SG_ Byte_6_b7_5 : 55|3@0+ (1,0) [0|7] "" XXX
SG_ ECM_AccTorque : 52|13@0+ (1,-4096) [-4096|4095] "" XXX
BO_ 384 Accessories_02: 8 XXX
SG_ Park_Assist_State : 42|1@0+ (1,0) [0|1] "" XXX
SG_ StartStop_Inv : 44|1@0+ (1,0) [0|1] "" XXX
BO_ 465 NEW_MSG_4: 8 XXX
BO_ 465 Gear_Info: 8 XXX
SG_ BrakePressedInv : 3|1@0+ (1,0) [0|1] "" XXX
SG_ NEW_SIGNAL_1 : 55|16@0+ (1,0) [0|4095] "" XXX
SG_ Byte_3 : 31|8@0+ (1,0) [0|255] "" XXX
BO_ 511 BrakeHold: 8 XXX
SG_ Byte_0 : 7|8@0+ (1,0) [0|255] "" XXX
SG_ Byte_1 : 15|8@0+ (1,0) [0|255] "" XXX
SG_ Byte_2 : 23|8@0+ (1,0) [0|255] "" XXX
SG_ Byte_3 : 31|8@0+ (1,0) [0|255] "" XXX
SG_ Byte_4 : 39|8@0+ (1,0) [0|255] "" XXX
SG_ Byte_5 : 47|8@0+ (1,0) [0|255] "" XXX
SG_ Byte_6 : 55|8@0+ (1,0) [0|255] "" XXX
SG_ Byte_7 : 63|8@0+ (1,0) [0|255] "" XXX
BO_ 522 Brake_Info: 8 XXX
SG_ Byte_0_b7_2 : 7|6@0+ (1,0) [0|63] "" XXX
SG_ NEW_SIGNAL_2 : 1|1@0+ (1,0) [0|1] "" XXX
SG_ Byte_0_b0 : 0|1@0+ (1,0) [0|1] "" XXX
SG_ Byte_1_b7_6 : 15|2@0+ (1,0) [0|3] "" XXX
SG_ Byte_1_b4 : 12|1@0+ (1,0) [0|1] "" XXX
SG_ Byte_2_b7_4 : 23|4@0+ (1,0) [0|15] "" XXX
SG_ Byte_4_b3_2 : 35|2@0+ (1,0) [0|3] "" XXX
SG_ Byte_6 : 55|8@0+ (1,0) [0|255] "" XXX
SG_ Byte_7 : 63|8@0+ (1,0) [0|255] "" XXX
SG_ COUNTER : 11|4@0+ (1,0) [0|15] "" XXX
SG_ BrakeCmd : 13|1@0+ (1,0) [0|1] "" XXX
SG_ BrakePressure : 17|10@0+ (1,0) [0|255] "" XXX
SG_ BrakePressure : 17|10@0+ (1,0) [0|1023] "" XXX
SG_ BrakePedal : 19|2@0+ (1,0) [0|3] "" XXX
SG_ BrakePedal2 : 33|2@0+ (1,0) [0|3] "" XXX
SG_ CHECKSUM : 39|4@0+ (1,0) [0|15] "" XXX
SG_ NEW_SIGNAL_1 : 47|8@0+ (1,0) [0|255] "" XXX
BO_ 544 wheelspeed1: 8 BCM
BO_ 544 WheelRear: 8 BCM
SG_ WhlSpdRR : 39|16@0+ (0.01,-327.68) [0|65535] "" XXX
SG_ WhlSpdLR : 55|16@0+ (0.01,-327.68) [0|65535] "" XXX
SG_ Byte_0_b7 : 7|1@0+ (1,0) [0|1] "" XXX
SG_ StandstillHold : 6|1@0+ (1,0) [0|1] "" XXX
SG_ Byte_0_b5_0 : 5|6@0+ (1,0) [0|63] "" XXX
SG_ Byte_1 : 15|8@0+ (1,0) [0|255] "" XXX
SG_ Byte_2_b7_3 : 23|5@0+ (1,0) [0|31] "" XXX
SG_ BrakeReqActive : 18|1@0+ (1,0) [0|1] "" XXX
SG_ Byte_2_b1 : 17|1@0+ (1,0) [0|1] "" XXX
SG_ ACC_BrakeApplied : 16|1@0+ (1,0) [0|1] "" XXX
SG_ Byte_3 : 31|8@0+ (1,0) [0|255] "" XXX
SG_ Byte_4 : 39|8@0+ (1,0) [0|255] "" XXX
SG_ Byte_5 : 47|8@0+ (1,0) [0|255] "" XXX
SG_ Byte_6 : 55|8@0+ (1,0) [0|255] "" XXX
SG_ Byte_7 : 63|8@0+ (1,0) [0|255] "" XXX
BO_ 565 wheelspeed0: 8 BCM
BO_ 565 WheelFront: 8 BCM
SG_ WhlSpdRF : 39|16@0+ (0.01,-327.68) [0|65535] "" XXX
SG_ WhlSpdLF : 55|16@0+ (0.01,-327.68) [0|65535] "" XXX
BO_ 582 PSCM1: 8 PSCM
SG_ byte0 : 7|8@0+ (1,0) [0|255] "" XXX
SG_ SteeringWheelRateOfChange : 15|8@0+ (1,0) [0|255] "" XXX
SG_ SteeringAngleServo : 23|16@0+ (0.0447,-1464.8) [0|65535] "deg" XXX
SG_ EPSTorque : 15|8@0+ (1,0) [0|255] "" XXX
SG_ SteeringAngleServo : 23|16@0+ (0.0447,-1465) [0|65535] "deg" XXX
SG_ LKATorque : 35|12@0+ (1,-2000) [0|65535] "" XXX
SG_ byte4 : 39|4@0+ (1,0) [0|15] "" XXX
SG_ LKAActive : 55|8@0+ (1,0) [0|255] "" XXX
@@ -134,6 +214,15 @@ BO_ 582 PSCM1: 8 PSCM
BO_ 608 FSM1: 8 FSM
SG_ ACC_Distance : 7|8@0+ (1,0) [0|255] "" XXX
SG_ Byte_1 : 15|8@0+ (1,0) [0|255] "" XXX
SG_ Byte_2_b7_3 : 23|5@0+ (1,0) [0|31] "" XXX
SG_ ACC_Braking : 18|1@0+ (1,0) [0|1] "" XXX
SG_ Byte_2_b1_0 : 17|2@0+ (1,0) [0|3] "" XXX
SG_ Byte_3 : 31|8@0+ (1,0) [0|255] "" XXX
SG_ Byte_4 : 39|8@0+ (1,0) [0|255] "" XXX
SG_ Byte_5 : 47|8@0+ (1,0) [0|255] "" XXX
SG_ Byte_6 : 55|8@0+ (1,0) [0|255] "" XXX
SG_ Byte_7 : 63|8@0+ (1,0) [0|255] "" XXX
BO_ 609 fromWhere: 8 XXX
SG_ COUNTER : 3|4@0+ (1,0) [0|15] "" XXX
@@ -152,13 +241,23 @@ BO_ 610 FSM2: 8 FSM
BO_ 612 Accessories_03: 8 XXX
SG_ Park_Assist_Button : 60|1@0+ (1,0) [0|1] "" XXX
SG_ RearParkWarning_Button : 58|1@0+ (1,0) [0|1] "" XXX
BO_ 624 FSM3: 8 FSM
SG_ ACC_Standstill : 0|1@0+ (1,0) [0|1] "" XXX
SG_ Byte_02 : 1|1@0+ (1,0) [0|1] "" XXX
SG_ ACC_Check : 2|1@0+ (1,0) [0|1] "" XXX
SG_ ACC_AccelDecel : 15|8@0+ (1,0) [0|255] "" XXX
SG_ ACC_Some : 17|10@0+ (1,0) [0|255] "" XXX
SG_ NEW_SIGNAL_3 : 47|8@0+ (1,0) [0|255] "" XXX
SG_ Byte_01 : 7|5@0+ (1,0) [0|31] "" XXX
SG_ ACC_AccelerationRequest : 15|8@0+ (0.04,-5.04) [0|255] "" XXX
SG_ Byte_2_b7_6 : 23|2@0+ (1,0) [0|3] "" XXX
SG_ ACC_NoTargetCancel : 21|1@0+ (1,0) [0|1] "" XXX
SG_ Byte_2_b4_2 : 20|3@0+ (1,0) [0|7] "" XXX
SG_ ACC_Mode : 17|2@0+ (1,0) [0|3] "" XXX
SG_ ACC_TractionRequest : 31|8@0+ (1,0) [0|255] "" XXX
SG_ FrameKind : 39|8@0+ (1,0) [0|255] "" XXX
SG_ Byte_5 : 47|8@0+ (1,0) [0|255] "" XXX
SG_ Byte_6 : 55|8@0+ (1,0) [0|255] "" XXX
SG_ Byte_7 : 63|8@0+ (1,0) [0|255] "" XXX
BO_ 648 BrakePedal: 8 XXX
SG_ Counter : 0|3@1+ (1,0) [0|6] "" XXX
@@ -169,13 +268,65 @@ BO_ 750 HandBrake: 8 XXX
SG_ Hand_Brake_State : 44|4@0+ (1,0) [0|15] "" XXX
BO_ 794 FSM4: 8 FSM
SG_ Byte_0 : 7|8@0+ (1,0) [0|255] "" XXX
SG_ Byte_1_b7_4 : 15|4@0+ (1,0) [0|15] "" XXX
SG_ ACC_Stopping : 11|1@0+ (1,0) [0|1] "" XXX
SG_ Byte_1_b2_0 : 10|3@0+ (1,0) [0|7] "" XXX
SG_ Byte_2 : 23|8@0+ (1,0) [0|255] "" XXX
SG_ ACC_LeadSpeed : 31|8@0+ (1,0) [0|255] "" XXX
SG_ NEW_SIGNAL_2 : 32|4@1+ (1,0) [0|15] "" XXX
SG_ NEW_SIGNAL_1 : 47|16@0+ (1,-46090) [0|16383] "" XXX
SG_ Byte_4 : 39|8@0+ (1,0) [0|255] "" XXX
SG_ Byte_5_b7 : 47|1@0+ (1,0) [0|1] "" XXX
SG_ ACC_BrakeRequest : 46|1@0+ (1,0) [0|1] "" XXX
SG_ ACC_BrakeTarget : 45|14@0+ (1,0) [0|16383] "" XXX
SG_ Byte_7 : 63|8@0+ (1,0) [0|255] "" XXX
BO_ 665 BrakeReqAck: 8 XXX
SG_ StandstillHold : 7|1@0+ (1,0) [0|1] "" XXX
SG_ Byte_0_b6_0 : 6|7@0+ (1,0) [0|127] "" XXX
SG_ Byte_1 : 15|8@0+ (1,0) [0|255] "" XXX
SG_ Byte_2 : 23|8@0+ (1,0) [0|255] "" XXX
SG_ Byte_3 : 31|8@0+ (1,0) [0|255] "" XXX
SG_ Byte_4 : 39|8@0+ (1,0) [0|255] "" XXX
SG_ Byte_5_b7_4 : 47|4@0+ (1,0) [0|15] "" XXX
SG_ BrakeReqNotAck : 43|1@0+ (1,0) [0|1] "" XXX
SG_ Byte_5_b2_0 : 42|3@0+ (1,0) [0|7] "" XXX
SG_ Byte_6 : 55|8@0+ (1,0) [0|255] "" XXX
SG_ Byte_7 : 63|8@0+ (1,0) [0|255] "" XXX
BO_ 706 RearParkWarning_Status: 8 XXX
SG_ RearParkWarning_State : 35|1@0+ (1,0) [0|1] "" XXX
BO_ 807 ParkAssist_Status: 8 XXX
SG_ Park_Assist_Off : 40|1@0+ (1,0) [0|1] "" XXX
BO_ 802 StartStop: 8 XXX
SG_ StartStop : 8|1@0+ (1,0) [0|1] "" XXX
BO_ 805 AccHold: 8 XXX
SG_ Byte_0_b7 : 7|1@0+ (1,0) [0|1] "" XXX
SG_ ACC_Engaged : 6|1@0+ (1,0) [0|1] "" XXX
SG_ Byte_0_b5_2 : 5|4@0+ (1,0) [0|15] "" XXX
SG_ ACC_StandstillHold : 1|2@0+ (1,0) [0|3] "" XXX
SG_ Byte_1 : 15|8@0+ (1,0) [0|255] "" XXX
SG_ Byte_2 : 23|8@0+ (1,0) [0|255] "" XXX
SG_ Byte_3 : 31|8@0+ (1,0) [0|255] "" XXX
SG_ Byte_4 : 39|8@0+ (1,0) [0|255] "" XXX
SG_ Byte_5 : 47|8@0+ (1,0) [0|255] "" XXX
SG_ Byte_6 : 55|8@0+ (1,0) [0|255] "" XXX
SG_ Byte_7 : 63|8@0+ (1,0) [0|255] "" XXX
BO_ 803 BrakeStatus: 8 XXX
SG_ Byte_0 : 7|8@0+ (1,0) [0|255] "" XXX
SG_ Byte_1 : 15|8@0+ (1,0) [0|255] "" XXX
SG_ Byte_2 : 23|8@0+ (1,0) [0|255] "" XXX
SG_ Byte_3 : 31|8@0+ (1,0) [0|255] "" XXX
SG_ Byte_4_b7_5 : 39|3@0+ (1,0) [0|7] "" XXX
SG_ BrakeApplied : 36|1@0+ (1,0) [0|1] "" XXX
SG_ Byte_4_b3_0 : 35|4@0+ (1,0) [0|15] "" XXX
SG_ Byte_5 : 47|8@0+ (1,0) [0|255] "" XXX
SG_ Byte_6 : 55|8@0+ (1,0) [0|255] "" XXX
SG_ Byte_7 : 63|8@0+ (1,0) [0|255] "" XXX
BO_ 923 Accessories_01: 8 XXX
SG_ NEW_SIGNAL_1 : 15|16@0+ (1,0) [0|65535] "" XXX
SG_ Wipers : 38|2@0+ (1,0) [0|3] "" XXX
@@ -264,9 +415,25 @@ BO_ 2015 diagGlobalReq: 8 XXX
SG_ byte6 : 55|8@0+ (1,0) [0|255] "" XXX
SG_ byte7 : 63|8@0+ (1,0) [0|255] "" XXX
CM_ SG_ 112 Console_Button_Pressed "Any console button (LKA, rear park warning, park assist, start/stop)";
CM_ SG_ 81 ACC_AbortCode "0x10 generic abort, 0x04 latched fault";
CM_ SG_ 608 ACC_Braking "Set while ACC brakes";
CM_ SG_ 624 ACC_NoTargetCancel "Camera cancels: slow with no target";
CM_ SG_ 624 ACC_Mode "0 brake, 1 coast, 2 drive";
CM_ SG_ 624 ACC_TractionRequest "Signed in coast (negative = engine drag), unsigned in drive";
CM_ SG_ 794 Byte_5_b7 "Always 1";
CM_ SG_ 794 ACC_BrakeRequest "Hydraulic brake requested";
CM_ SG_ 794 ACC_BrakeTarget "Brake target, lower = more braking";
CM_ SG_ 307 BrakeLevel "Brake level seen by the camera";
CM_ SG_ 544 BrakeReqActive "Brake request active, seen by the camera";
CM_ SG_ 665 BrakeReqNotAck "Active low: 0 = car acknowledges the camera brake request";
CM_ SG_ 803 BrakeApplied "Brake applied, seen by the camera";
CM_ SG_ 805 Byte_0 "0xC4 ACC engaged moving, 0x84 not, 0x87 ACC standstill hold (routes 807, 881)";
CM_ SG_ 298 Byte_2 "bit5 set while ACC engaged and moving (E7), clear at standstill or standby (C7)";
CM_ SG_ 511 Byte_0 "0x70 -> 0xD0 ~4.4 s into a stop: brake hold state change (routes 807, 87b)";
CM_ SG_ 16 SteeringDirection "0 = CCW, 1=CW (turning left or right of center)";
CM_ SG_ 16 SteeringRateOfChange "Rate of change? Torque?";
CM_ SG_ 81 ACCStatus "0=Acc Unavailable, 1=???, 2=Acc Ready, 3,4=???, 6= Acc Active, 7=Acc active tracking object (probably)";
CM_ SG_ 81 ACC_Available "0=Acc Unavailable, 1=???, 2=Acc Ready, 3,4=???, 6= Acc Active, 7=Acc active tracking object (probably)";
CM_ SG_ 295 ACCMinusBtnInv "Active zero when button pressed.";
CM_ SG_ 295 TimeGapIncreaseBtnInv "Active zero when button pressed.";
CM_ SG_ 295 TimeGapDecreaseBtnInv "Active zero when button pressed.";
@@ -283,16 +450,15 @@ CM_ SG_ 298 NEW_SIGNAL_4 "related to gas pedal";
CM_ SG_ 298 NEW_SIGNAL_5 "related to ACCStatus";
CM_ SG_ 298 NEW_SIGNAL_6 "went high at same time as ACCStatus >= 2";
CM_ SG_ 298 BrakePressed "driver";
CM_ SG_ 298 EngineRpm "Might be engine rpm. But behaves a bit weird.";
CM_ SG_ 298 EngineRpm "Might be engine rpm. But behaves abit weird.";
CM_ SG_ 582 byte0 "0=CCW, 1=CW, bit 2,";
CM_ SG_ 582 SteeringWheelRateOfChange "Some rate of change for steering wheel? Torque?";
CM_ SG_ 582 EPSTorque "Some rate of change for steering wheel? Torque?";
CM_ SG_ 582 byte4 "High nibble";
CM_ SG_ 582 LKAActive "Bit 1, 1 When LKA Active, Bit 3, 1 When denying?";
CM_ SG_ 608 ACC_Distance "Seems to track distance, or speed of vehicle in front.";
CM_ SG_ 610 SET_X_22 "0x20 Heartbeat, VEgo <58kph = 0x03, VEgo >65kph = 0x04, 0x05";
CM_ SG_ 624 ACC_AccelDecel "Might be some acc speed, moved a bit after activating acc";
CM_ SG_ 624 ACC_Some "Jumps to life after activating ACC, 0 when not active";
CM_ SG_ 648 Counter "counts 0 to 6";
CM_ SG_ 1021 TSR_Speed "Traffic Sign Recognition speed";
CM_ SG_ 1039 TurnSignal "0 = Nothing, 1= Left, 3=Right";
VAL_ 522 BrakePedal 1 "Not Pressed" 2 "Pressed";
VAL_ 99 GearLever 0 "P" 1 "R" 2 "N" 3 "D";
+2 -1
View File
@@ -511,7 +511,8 @@ static void gm_rx_hook(const CANPacket_t *msg) {
const int track2 = (msg->data[2] << 8) | msg->data[3];
const uint8_t state = msg->data[4] >> 4;
const uint8_t counter = msg->data[4] & 0xFU;
gm_pedal_sensor_good = (state == 0U) && (gm_pedal_crc(msg) == msg->data[5]) &&
const bool state_ok = (state == 0U) || ((state == 8U) && gm_bolt_pedal_drive_supported);
gm_pedal_sensor_good = state_ok && (gm_pedal_crc(msg) == msg->data[5]) &&
(!gm_pedal_counter_seen || (counter != gm_pedal_counter_last)) &&
(track1 <= 4095) && (track2 <= 4095);
gm_pedal_counter_seen = true;
+33 -1
View File
@@ -80,6 +80,28 @@ static const CanMsg HYUNDAI_TX_MSGS[] = {
// Classic-mode-only meanings. CANFD Carnival/angle bit8192 is untouched.
// Exact stock words deliberately do not admit blended alpha-long or other flags.
static bool hyundai_non_scc_software_cruise = false;
static bool hyundai_non_scc_software_cruise_param(uint16_t param) {
bool selected = false;
switch (param) {
case 0x1020U: case 0x1820U: case 0x1420U: case 0x1C20U:
case 0x1060U: case 0x1860U: case 0x1460U: case 0x1C60U:
case 0x1061U: case 0x1861U: case 0x1461U: case 0x1C61U:
case 0x1022U: case 0x1822U: case 0x1422U: case 0x1C22U:
selected = true;
break;
default:
break;
}
return selected;
}
static bool hyundai_non_scc_software_button_allowed(bool main_button) {
return controls_allowed && cruise_engaged_prev && vehicle_moving && !main_button &&
!brake_pressed && !gas_pressed && !relay_malfunction && !safety_rx_checks_invalid;
}
static bool hyundai_blended_stock = false;
// Exact prepared mixed longitudinal profiles.
static bool hyundai_blended_alpha = false;
@@ -526,6 +548,11 @@ static bool hyundai_tx_hook(const CANPacket_t *msg) {
bool allowed_resume = (button == 1) && controls_allowed;
bool allowed_set = hyundai_blended_stock && (button == 2) && controls_allowed;
if (hyundai_non_scc_software_cruise) {
const bool stock_cruise_ready = hyundai_non_scc_software_button_allowed(GET_BIT(msg, 3U));
allowed_resume = (button == HYUNDAI_BTN_RESUME) && stock_cruise_ready;
allowed_set = (button == HYUNDAI_BTN_SET) && stock_cruise_ready;
}
bool allowed_cancel = (button == 4) && cruise_engaged_prev;
if (!(allowed_resume || allowed_set || allowed_cancel)) {
tx = false;
@@ -601,7 +628,11 @@ static const CanMsg HYUNDAI_LONG_TX_MSGS[] = {
};
#endif
static safety_config hyundai_init(uint16_t param) {
static safety_config hyundai_init(uint16_t safety_param) {
hyundai_non_scc_software_cruise = hyundai_non_scc_software_cruise_param(safety_param) &&
((alternative_experience == 0) || (alternative_experience == 32));
const uint16_t param = hyundai_non_scc_software_cruise ? (safety_param & ~0x0020U) : safety_param;
#ifndef ALLOW_DEBUG
static const CanMsg HYUNDAI_LONG_TX_MSGS[] = {
HYUNDAI_LONG_COMMON_TX_MSGS(0, false)
@@ -906,6 +937,7 @@ static safety_config hyundai_init(uint16_t param) {
}
static safety_config hyundai_legacy_init(uint16_t param) {
hyundai_non_scc_software_cruise = false;
// older hyundai models have less checks due to missing counters and checksums
static const RxCheck hyundai_legacy_rx_checks[] = {
HYUNDAI_COMMON_RX_CHECKS(true)
+12 -1
View File
@@ -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;
@@ -1,37 +1,70 @@
#pragma once
#include "opendbc/safety/modes/volvo_c1.h"
#include "opendbc/safety/modes/volvo_cma.h"
#include "opendbc/safety/modes/volvo_eucd.h"
#define VOLVO_PARAM_C1 2U
#define VOLVO_PARAM_EUCD 8U
static bool volvo_dispatch_c1;
static bool volvo_dispatch_eucd;
static safety_config volvo_dispatch_init(uint16_t param) {
volvo_dispatch_c1 = param == 2U;
return volvo_dispatch_c1 ? volvo_c1_init(param) : volvo_cma_init(param);
volvo_dispatch_c1 = param == VOLVO_PARAM_C1;
volvo_dispatch_eucd = param == VOLVO_PARAM_EUCD;
safety_config ret;
if (volvo_dispatch_eucd) {
ret = volvo_eucd_init(param);
} else if (volvo_dispatch_c1) {
ret = volvo_c1_init(param);
} else {
ret = volvo_cma_init(param);
}
return ret;
}
static void volvo_dispatch_rx(const CANPacket_t *msg) {
if (volvo_dispatch_c1) {
if (volvo_dispatch_eucd) {
volvo_eucd_rx_hook(msg);
} else if (volvo_dispatch_c1) {
volvo_c1_rx_hook(msg);
} else {
volvo_cma_rx_hook(msg);
}
}
static bool volvo_dispatch_tx(const CANPacket_t *msg) {
return volvo_dispatch_c1 ? volvo_c1_tx_hook(msg) : volvo_cma_tx_hook(msg);
bool tx;
if (volvo_dispatch_eucd) {
tx = volvo_eucd_tx_hook(msg);
} else if (volvo_dispatch_c1) {
tx = volvo_c1_tx_hook(msg);
} else {
tx = volvo_cma_tx_hook(msg);
}
return tx;
}
// C1 continues to ignore these hooks exactly as before; all of its RX
// declarations retain their existing ignore_checksum/quality settings.
// C1 and EUCD ignore these hooks; all of their RX
// declarations set ignore_checksum/quality.
static uint8_t volvo_dispatch_get_counter(const CANPacket_t *msg) {
return volvo_dispatch_c1 ? 0U : volvo_cma_lca2_counter(msg);
return (volvo_dispatch_c1 || volvo_dispatch_eucd) ? 0U : volvo_cma_lca2_counter(msg);
}
static uint32_t volvo_dispatch_get_checksum(const CANPacket_t *msg) {
return volvo_dispatch_c1 ? 0U : volvo_cma_get_checksum(msg);
return (volvo_dispatch_c1 || volvo_dispatch_eucd) ? 0U : volvo_cma_get_checksum(msg);
}
static uint32_t volvo_dispatch_compute_checksum(const CANPacket_t *msg) {
return volvo_dispatch_c1 ? 0U : volvo_cma_compute_checksum(msg);
return (volvo_dispatch_c1 || volvo_dispatch_eucd) ? 0U : volvo_cma_compute_checksum(msg);
}
static bool volvo_dispatch_quality(const CANPacket_t *msg) {
return volvo_dispatch_c1 || volvo_cma_receiver_quality_rx(msg);
return volvo_dispatch_c1 || volvo_dispatch_eucd || volvo_cma_receiver_quality_rx(msg);
}
static void volvo_dispatch_optional_rx(const CANPacket_t *msg) {
if (volvo_dispatch_eucd) {
volvo_eucd_optional_rx(msg);
}
}
static bool volvo_dispatch_fwd(int bus_num, int addr) {
return volvo_dispatch_eucd && volvo_eucd_fwd_hook(bus_num, addr);
}
const safety_hooks volvo_dispatch_hooks = {.init = volvo_dispatch_init, .rx = volvo_dispatch_rx, .tx = volvo_dispatch_tx,
.optional_rx = volvo_dispatch_optional_rx, .fwd = volvo_dispatch_fwd,
.get_counter = volvo_dispatch_get_counter,
.get_checksum = volvo_dispatch_get_checksum, .compute_checksum = volvo_dispatch_compute_checksum,
.get_quality_flag_valid = volvo_dispatch_quality};
@@ -0,0 +1,319 @@
#pragma once
#include "opendbc/safety/declarations.h"
#include "opendbc/safety/modes/volvo_eucd_aol.h"
// EUCD (V60 2010-18). Bus 0 is the car, bus 2 the forward camera; bus 1 is a radar-only aux bus, not monitored.
#define VOLVO_EUCD_MAIN_BUS 0U
#define VOLVO_EUCD_PARTY_BUS 2U
#define VOLVO_EUCD_AccPedal 0x020U // RX, gas pedal
#define VOLVO_EUCD_GAS_PRESS 100U // AccPedal raw (0.1 %)
#define VOLVO_EUCD_GAS_RELEASE 90U
#define VOLVO_EUCD_FSM0 0x051U // TX by OP, camera's relayed; ACC state
#define VOLVO_EUCD_EngineData 0x12AU // RX, ECM ACC state
#define VOLVO_EUCD_VehicleSpeed1 0x148U // RX, vehicle speed
#define VOLVO_EUCD_Brake_Info 0x20AU // RX, driver brake pressed
#define VOLVO_EUCD_CCButtons 0x127U // TX by OP, CC buttons
#define VOLVO_EUCD_PSCM1 0x246U // TX by OP to camera, PSCM state
#define VOLVO_EUCD_WHEEL_REAR 0x220U // TX by OP to camera, rear wheel speeds + brake request active
#define VOLVO_EUCD_BRAKE_REQ_ACK 0x299U // TX by OP to camera, brake request ack
#define VOLVO_EUCD_BRAKE_HOLD 0x1FFU // TX by OP to camera, brake hold state (masked in OP's no-target stop)
#define VOLVO_EUCD_ACC_HOLD 0x325U // TX by OP to camera, ECM ACC hold state (shown as standby in OP's no-target stop)
#define VOLVO_EUCD_FSM1 0x260U // TX by OP, ACC radar/distance message
#define VOLVO_EUCD_FSM2 0x262U // TX by OP, LKA command
#define VOLVO_EUCD_FSM3 0x270U // TX by OP, ACC accel request + status
#define VOLVO_EUCD_FSM4 0x31AU // TX by OP, camera's relayed; brake request
// The camera's own FSM3/FSM4 just received: relayed unchanged while it drives (OP's long off), even past OP's limits
#define VOLVO_EUCD_CAM_FRAMES 4U
#define VOLVO_EUCD_CAM_FRAME_MAX_AGE_US 100000U
typedef struct {
uint8_t data[VOLVO_EUCD_CAM_FRAMES][8];
uint32_t ts[VOLVO_EUCD_CAM_FRAMES];
bool valid[VOLVO_EUCD_CAM_FRAMES];
uint8_t index;
} VolvoEucdCamFrames;
static VolvoEucdCamFrames volvo_eucd_cam_fsm3;
static VolvoEucdCamFrames volvo_eucd_cam_fsm4;
// OP's stop (camera shown standby, ECM engaged): camera FSM1/FSM3 kept off the ECM also on the gas, per ECM frame
#define VOLVO_EUCD_OP_OWNS_ECM_FRAMES 3
static int volvo_eucd_op_owns_ecm_fresh = 0;
static void volvo_eucd_cam_frames_clear(VolvoEucdCamFrames *frames) {
frames->index = 0U;
for (uint8_t i = 0U; i < VOLVO_EUCD_CAM_FRAMES; i++) {
frames->valid[i] = false;
}
}
static void volvo_eucd_cam_frames_store(VolvoEucdCamFrames *frames, const CANPacket_t *msg) {
for (uint8_t byte = 0U; byte < 8U; byte++) {
frames->data[frames->index][byte] = msg->data[byte];
}
frames->ts[frames->index] = microsecond_timer_get();
frames->valid[frames->index] = true;
frames->index = (frames->index + 1U) % VOLVO_EUCD_CAM_FRAMES;
}
static bool volvo_eucd_cam_frames_match(const VolvoEucdCamFrames *frames, const CANPacket_t *msg) {
const uint32_t now = microsecond_timer_get();
bool matches_cam = false;
for (uint8_t i = 0U; i < VOLVO_EUCD_CAM_FRAMES; i++) {
bool matches = frames->valid[i] && (safety_get_ts_elapsed(now, frames->ts[i]) <= VOLVO_EUCD_CAM_FRAME_MAX_AGE_US);
for (uint8_t byte = 0U; byte < 8U; byte++) {
matches &= msg->data[byte] == frames->data[i][byte];
}
matches_cam |= matches;
}
return matches_cam;
}
static void volvo_eucd_rx_hook(const CANPacket_t *msg) {
if (msg->bus == VOLVO_EUCD_MAIN_BUS) {
const unsigned int addr = msg->addr;
if (addr == VOLVO_EUCD_VehicleSpeed1) {
// Signal: VehicleSpeed
unsigned int speed_raw = ((unsigned int)msg->data[6] << 8) | (unsigned int)msg->data[7];
vehicle_moving = speed_raw > 36U;
UPDATE_VEHICLE_SPEED(speed_raw * 0.01 / 3.6);
}
if (addr == VOLVO_EUCD_AccPedal) {
// Signal: AccPedal
unsigned int gas_raw = (((unsigned int)msg->data[2] & 0x03U) << 8) | (unsigned int)msg->data[3];
// 10% to press, under 9% to release, or a held foot flickers it (route 00000007, 273.7 s)
gas_pressed = gas_raw >= (gas_pressed ? VOLVO_EUCD_GAS_RELEASE : VOLVO_EUCD_GAS_PRESS);
}
if (addr == VOLVO_EUCD_CCButtons) {
// Signal: LKA_State, the driver's LKA on/off (always on lateral)
volvo_eucd_aol_lka_on = GET_BIT(msg, 18U);
}
if (addr == VOLVO_EUCD_Brake_Info) {
// Signal: BrakePedal
brake_pressed = (((unsigned int)msg->data[2] & 0x0CU) >> 2U) == 2U;
}
if (addr == VOLVO_EUCD_PSCM1) {
// Signal: SteeringAngleServo (factor 0.0447, offset -1465 deg), stored as angle_deg * 100
unsigned int angle_raw = ((unsigned int)msg->data[2] << 8) | (unsigned int)msg->data[3];
int angle_meas_new = ROUND(((angle_raw * 0.0447f) - 1465.0f) * 100.0f);
update_sample(&angle_meas, angle_meas_new);
}
if (addr == VOLVO_EUCD_EngineData) {
// Signal: ACC_State_ECM (byte 4 bits 5:4: 1 off, 2 standby, 3 engaged)
bool cruise_engaged = (((unsigned int)msg->data[4] >> 4) & 0x3U) == 0x3U;
pcm_cruise_check(cruise_engaged);
if (volvo_eucd_op_owns_ecm_fresh > 0) {
volvo_eucd_op_owns_ecm_fresh--;
}
}
} else if (msg->bus == VOLVO_EUCD_PARTY_BUS) {
if (msg->addr == VOLVO_EUCD_FSM0) {
// Signal: ACC_Available, the camera's ACC main on (always on lateral)
acc_main_on = GET_BIT(msg, 17U);
}
} else {
// no other bus is monitored
}
}
// Frames outside the RX checks: the camera's FSM3/FSM4 as it sends them
static void volvo_eucd_optional_rx(const CANPacket_t *msg) {
volvo_eucd_aol_observe(msg);
if (msg->bus == VOLVO_EUCD_PARTY_BUS) {
if (msg->addr == VOLVO_EUCD_FSM3) {
volvo_eucd_cam_frames_store(&volvo_eucd_cam_fsm3, msg);
}
if (msg->addr == VOLVO_EUCD_FSM4) {
volvo_eucd_cam_frames_store(&volvo_eucd_cam_fsm4, msg);
}
}
}
// EUCD sends LKAAngleReq=0 when not steering, so the angle must be exactly zero while disabled
static bool volvo_eucd_angle_cmd_checks(int desired_angle, const AngleSteeringLimits limits) {
const bool allowed = lateral_controls_allowed();
bool violation = false;
if (allowed) {
// Same rate limits as steer_angle_cmd_checks: speed fudged by 1 m/s, with 1 count of margin
const float fudged_speed = (vehicle_speed.min / VEHICLE_SPEED_FACTOR) - 1.;
int delta_angle_up = (safety_interpolate(limits.angle_rate_up_lookup, fudged_speed) * limits.angle_deg_to_can) + 1.;
int delta_angle_down = (safety_interpolate(limits.angle_rate_down_lookup, fudged_speed) * limits.angle_deg_to_can) + 1.;
int highest_desired_angle = desired_angle_last + ((desired_angle_last > 0) ? delta_angle_up : delta_angle_down);
int lowest_desired_angle = desired_angle_last - ((desired_angle_last >= 0) ? delta_angle_down : delta_angle_up);
violation |= safety_max_limit_check(desired_angle, highest_desired_angle, lowest_desired_angle);
desired_angle_last = desired_angle;
} else {
violation |= desired_angle != 0;
}
if (violation || !allowed) {
desired_angle_last = 0;
}
return violation;
}
static bool volvo_eucd_tx_hook(const CANPacket_t *msg) {
static const AngleSteeringLimits VOLVO_EUCD_STEERING_LIMITS = {
.max_angle = 9000, // 90 deg
.angle_deg_to_can = 100,
.angle_rate_up_lookup = {
{0., 5., 15.},
{5., .8, .15}
},
.angle_rate_down_lookup = {
{0., 5., 15.},
{5., 3.5, .4}
},
};
// FSM3 byte1 accel: raw = byte1 - 126, 0.04 m/s^2 per step (+2.0 to -3.52)
static const LongitudinalLimits VOLVO_EUCD_LONG_LIMITS = {
.max_accel = 50,
.min_accel = -88,
.inactive_accel = 0,
};
bool tx = true;
bool violation = false;
const unsigned int addr = msg->addr;
// Only ACC engaged, the same condition the fwd hook blocks the camera's frames on
const bool long_allowed = controls_allowed && !gas_pressed_prev;
// CC buttons to the car; the camera bus gets every CEM frame relayed, which cannot engage the ECM
if ((addr == VOLVO_EUCD_CCButtons) && (msg->bus == VOLVO_EUCD_MAIN_BUS)) {
// No resume without controls allowed, no cancel without cruise engaged
violation |= !cruise_engaged_prev && (GET_BIT(msg, 59U) || !(GET_BIT(msg, 43U))); // Signals: ACCOnOffBtn, ACCOnOffBtnInv (cancel)
violation |= !controls_allowed && (GET_BIT(msg, 61U) || !(GET_BIT(msg, 45U))); // Signals: ACCResumeBtn, ACCResumeBtnInv (resume)
}
// FSM0 from OP may report ACC enabled only while the ECM is engaged, so OP can never engage ACC by itself.
if (addr == VOLVO_EUCD_FSM0) {
bool acc_enabled = (msg->data[2] & 0x04U) != 0U;
violation |= acc_enabled && !cruise_engaged_prev;
}
// Safety check for Lane Keep Assist action.
if (addr == VOLVO_EUCD_FSM2) {
// Signal: LKAAngleReq (14 bits, 0.04 deg, offset -327.68), as angle_deg * 100
unsigned int angle_raw = (((unsigned int)msg->data[3] & 0x3FU) << 8) | (unsigned int)msg->data[4];
int desired_angle = ((int)angle_raw * 4) - 32768;
// Gate on the angle, not LKASteerDirection, which pauses ~8 frames on a direction change
if (volvo_eucd_angle_cmd_checks(desired_angle, VOLVO_EUCD_STEERING_LIMITS)) {
violation = true;
}
}
// EngineData to the camera showing ACC standby with the ECM engaged: OP's stop, it sends the ECM's FSM1/FSM3
if ((addr == VOLVO_EUCD_EngineData) && (msg->bus == VOLVO_EUCD_PARTY_BUS)) {
const bool shows_standby = (((unsigned int)msg->data[4] >> 4) & 0x3U) == 0x2U;
if (shows_standby && cruise_engaged_prev && controls_allowed) {
volvo_eucd_op_owns_ecm_fresh = VOLVO_EUCD_OP_OWNS_ECM_FRAMES;
}
}
// Long: controls_allowed and range check; stock FSM3 still flows cam->main
if (addr == VOLVO_EUCD_FSM3) {
int raw_accel = (int)msg->data[1] - 126;
// Neutral accel only without controls; with them the accel range, or the camera's own frame while it drives
const bool cam_frame = long_allowed && volvo_eucd_cam_frames_match(&volvo_eucd_cam_fsm3, msg);
bool accel_violation;
if (controls_allowed) {
const bool accel_valid = long_allowed && !safety_max_limit_check(raw_accel, VOLVO_EUCD_LONG_LIMITS.max_accel, VOLVO_EUCD_LONG_LIMITS.min_accel);
accel_violation = !accel_valid && (raw_accel != VOLVO_EUCD_LONG_LIMITS.inactive_accel) && !cam_frame;
} else {
accel_violation = raw_accel != VOLVO_EUCD_LONG_LIMITS.inactive_accel;
}
if (accel_violation) {
violation = true;
}
}
// FSM4 brake request only with OP's long allowed, or the camera's own frame unchanged (route 807)
if (addr == VOLVO_EUCD_FSM4) {
const bool brake_request = (msg->data[5] & 0x40U) != 0U;
violation |= brake_request && !long_allowed && !volvo_eucd_cam_frames_match(&volvo_eucd_cam_fsm4, msg);
}
if (violation) {
tx = false;
}
return tx;
}
static bool volvo_eucd_fwd_hook(int bus_num, int addr) {
bool block_msg = false;
// Camera FSM1/FSM3 blocked while OP controls; on the gas they go to the ECM, except in OP's stop (OP sends no accel)
const bool op_owns_ecm = volvo_eucd_op_owns_ecm_fresh > 0;
if (((unsigned int)bus_num == VOLVO_EUCD_PARTY_BUS) && controls_allowed && (!gas_pressed || op_owns_ecm)) {
if (((unsigned int)addr == VOLVO_EUCD_FSM1) || ((unsigned int)addr == VOLVO_EUCD_FSM3)) {
block_msg = true;
}
}
// FSM0 never forwarded main->cam (check_relay on the cam bus would trip on the camera's own FSM0)
if (((unsigned int)bus_num == VOLVO_EUCD_MAIN_BUS) && ((unsigned int)addr == VOLVO_EUCD_FSM0)) {
block_msg = true;
}
return block_msg;
}
static safety_config volvo_eucd_init(uint16_t param) {
(void)param;
volvo_eucd_cam_frames_clear(&volvo_eucd_cam_fsm3);
volvo_eucd_cam_frames_clear(&volvo_eucd_cam_fsm4);
volvo_eucd_op_owns_ecm_fresh = 0;
volvo_eucd_aol_reset();
volvo_eucd_aol_enabled = (unsigned int)alternative_experience == 32U;
if (volvo_eucd_aol_enabled) {
static const AolSafetyPolicy policy = {
.reset = volvo_eucd_aol_reset,
.request_mask = volvo_eucd_aol_request,
.permission_mask = volvo_eucd_aol_permission,
.rx_invalid = volvo_eucd_aol_reset,
};
aol_policy = &policy;
}
static const CanMsg VOLVO_EUCD_TX_MSGS[] = {
{VOLVO_EUCD_CCButtons, VOLVO_EUCD_MAIN_BUS, 8, .check_relay = false},
// relayed by OP, Set/Minus/Resume released while the camera is shown standby; check_relay so the CEM's frame does not pass
{VOLVO_EUCD_CCButtons, VOLVO_EUCD_PARTY_BUS, 8, .check_relay = true},
{VOLVO_EUCD_PSCM1, VOLVO_EUCD_PARTY_BUS, 8, .check_relay = true}, // OP replaces stock steering servo state
// car -> camera, relayed by OP
{VOLVO_EUCD_WHEEL_REAR, VOLVO_EUCD_PARTY_BUS, 8, .check_relay = true},
{VOLVO_EUCD_BRAKE_REQ_ACK, VOLVO_EUCD_PARTY_BUS, 8, .check_relay = true},
{VOLVO_EUCD_BRAKE_HOLD, VOLVO_EUCD_PARTY_BUS, 8, .check_relay = true},
{VOLVO_EUCD_ACC_HOLD, VOLVO_EUCD_PARTY_BUS, 8, .check_relay = true},
{VOLVO_EUCD_EngineData, VOLVO_EUCD_PARTY_BUS, 8, .check_relay = true}, // camera sees ACC standby in OP's no-target stop
{VOLVO_EUCD_FSM2, VOLVO_EUCD_MAIN_BUS, 8, .check_relay = true}, // OP replaces stock LKA command
// FSM1/FSM3: camera's pass through while OP does not control (relay delay faults the ECM)
{VOLVO_EUCD_FSM1, VOLVO_EUCD_MAIN_BUS, 8, .check_relay = false},
{VOLVO_EUCD_FSM3, VOLVO_EUCD_MAIN_BUS, 8, .check_relay = false},
// camera -> car, relayed by OP
{VOLVO_EUCD_FSM4, VOLVO_EUCD_MAIN_BUS, 8, .check_relay = true},
{VOLVO_EUCD_FSM0, VOLVO_EUCD_MAIN_BUS, 8, .check_relay = true},
};
// TODO: add counters
static RxCheck volvo_eucd_rx_checks[] = {
{.msg = {{VOLVO_EUCD_AccPedal, VOLVO_EUCD_MAIN_BUS, 8, .ignore_checksum = true, .ignore_counter = true, .ignore_quality_flag = true, .frequency = 100U}, { 0 }, { 0 }}},
{.msg = {{VOLVO_EUCD_FSM0, VOLVO_EUCD_PARTY_BUS, 8, .ignore_checksum = true, .ignore_counter = true, .ignore_quality_flag = true, .frequency = 100U}, { 0 }, { 0 }}},
{.msg = {{VOLVO_EUCD_EngineData, VOLVO_EUCD_MAIN_BUS, 8, .ignore_checksum = true, .ignore_counter = true, .ignore_quality_flag = true, .frequency = 67U}, { 0 }, { 0 }}},
{.msg = {{VOLVO_EUCD_CCButtons, VOLVO_EUCD_MAIN_BUS, 8, .ignore_checksum = true, .ignore_counter = true, .ignore_quality_flag = true, .frequency = 66U}, { 0 }, { 0 }}},
{.msg = {{VOLVO_EUCD_VehicleSpeed1, VOLVO_EUCD_MAIN_BUS, 8, .ignore_checksum = true, .ignore_counter = true, .ignore_quality_flag = true, .frequency = 50U}, { 0 }, { 0 }}},
{.msg = {{VOLVO_EUCD_Brake_Info, VOLVO_EUCD_MAIN_BUS, 8, .ignore_checksum = true, .ignore_counter = true, .ignore_quality_flag = true, .frequency = 50U}, { 0 }, { 0 }}},
{.msg = {{VOLVO_EUCD_PSCM1, VOLVO_EUCD_MAIN_BUS, 8, .ignore_checksum = true, .ignore_counter = true, .ignore_quality_flag = true, .frequency = 50U}, { 0 }, { 0 }}}, // steering angle meas
};
return BUILD_SAFETY_CFG(volvo_eucd_rx_checks, VOLVO_EUCD_TX_MSGS);
}
@@ -0,0 +1,53 @@
#pragma once
// V60 AOL: lateral with the LKA or ACC main on; host requests only narrow it
#define VOLVO_EUCD_GEAR_SELECTOR 0x063U
#define VOLVO_EUCD_AOL_GEAR_MAX_AGE_US 300000U
static bool volvo_eucd_aol_enabled = false;
static bool volvo_eucd_aol_lka_on = false;
static bool volvo_eucd_aol_drive = false;
static bool volvo_eucd_aol_gear_seen = false;
static uint32_t volvo_eucd_aol_gear_ts = 0U;
static void volvo_eucd_aol_reset(void) {
volvo_eucd_aol_lka_on = false;
volvo_eucd_aol_drive = false;
volvo_eucd_aol_gear_seen = false;
volvo_eucd_aol_gear_ts = 0U;
}
static uint8_t volvo_eucd_aol_request(void) {
uint8_t request = 0U;
if (heartbeat_engaged && aol_rx_healthy() && !safety_rx_checks_invalid && !relay_malfunction &&
(safety_get_ts_elapsed(microsecond_timer_get(), aol_host_request_ts) <= AOL_HOST_REQUEST_TIMEOUT_US)) {
request = aol_host_axis_mask;
}
return request;
}
static uint8_t volvo_eucd_aol_permission(void) {
const uint8_t request = volvo_eucd_aol_request();
uint8_t permission = 0U;
const bool drive = volvo_eucd_aol_gear_seen && volvo_eucd_aol_drive &&
(safety_get_ts_elapsed(microsecond_timer_get(), volvo_eucd_aol_gear_ts) <= VOLVO_EUCD_AOL_GEAR_MAX_AGE_US);
if (drive && (acc_main_on || volvo_eucd_aol_lka_on)) {
permission = request & 1U;
}
// No gas or brake check, as the tx hook: denying them dropped the AOL latch, a pink frame (routes 0000000a, 00000027)
if (drive && controls_allowed) {
permission |= request & 2U;
}
return permission;
}
static void volvo_eucd_aol_observe(const CANPacket_t *msg) {
if (volvo_eucd_aol_enabled && msg_matches(msg, VOLVO_EUCD_GEAR_SELECTOR, 0U)) {
volvo_eucd_aol_gear_seen = GET_LEN(msg) == 8U;
if (volvo_eucd_aol_gear_seen) {
volvo_eucd_aol_gear_ts = microsecond_timer_get();
// Signal: GearLever (byte 6 bits 6:5: 0 P, 1 R, 2 N, 3 D)
volvo_eucd_aol_drive = (((unsigned int)msg->data[6] >> 5) & 0x3U) == 0x3U;
}
}
}
+10 -2
View File
@@ -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,7 +526,15 @@ 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) {
if ((mode == SAFETY_VOLVO) && ((param > 2U) && (param != 5U))) {
#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;
current_safety_param = 0;
@@ -1026,6 +1026,10 @@ class SafetyTest(SafetyTestBase):
# generic cross-mode probe fabricates eight bytes, which the refresh
# variant accepts; exact 4/8-byte and bus checks live in Hyundai tests.
tx = list(filter(lambda m: m[:2] != [0x485, 0], tx))
# Volvo EUCD's FSM0 relay and the Hyundai CAN-FD EV longitudinal modes share 0x51 on bus 0.
if ((attr in ('TestHyundaiCanfdLKASteeringAltLongEV', 'TestHyundaiCanfdLKASteeringLongEV') and current_test == 'TestVolvoEUCD') or
(current_test in ('TestHyundaiCanfdLKASteeringAltLongEV', 'TestHyundaiCanfdLKASteeringLongEV') and attr == 'TestVolvoEUCD')):
tx = list(filter(lambda m: not (m[1] == 0 and m[0] == 0x51), tx))
all_tx.append([[m[0], m[1], attr] for m in tx])
# Independent protocol/whole-caller test files need not declare a SafetyTest
@@ -0,0 +1,53 @@
import signal
import subprocess
import sys
from opendbc.safety.tests.libsafety import libsafety_py
def assert_native_callback_finishes(test, model, param, address, bus, data, *, receive=True):
try:
mutant = libsafety_py.libsafety.mutation_get_active_mutant()
except AttributeError:
mutant = None
script = """import sys
from opendbc.safety.tests.libsafety import libsafety_py
libsafety_py.load(sys.argv[1])
safety = libsafety_py.libsafety
if sys.argv[2] != 'None':
safety.mutation_set_active_mutant(int(sys.argv[2]))
packet = libsafety_py.make_CANPacket(int(sys.argv[5]), int(sys.argv[6]), bytes.fromhex(sys.argv[7]))
print('NATIVE_SETUP_BEGIN', flush=True)
status = safety.set_safety_hooks(int(sys.argv[3]), int(sys.argv[4]))
print('NATIVE_SETUP_RETURN', flush=True)
if status != 0:
print('NATIVE_SETUP_ASSERTION', flush=True)
raise SystemExit(1)
safety.init_tests()
print('NATIVE_CALLBACK_BEGIN', flush=True)
receive = sys.argv[8] == 'True'
accepted = safety.safety_rx_hook(packet) if receive else safety.safety_tx_hook(packet)
print('NATIVE_CALLBACK_RETURN', flush=True)
raise SystemExit(0 if bool(accepted) == receive else 1)
"""
try:
result = subprocess.run([sys.executable, '-c', script, libsafety_py.libpath, str(mutant), str(model),
str(param), str(address), str(bus), bytes(data).hex(), str(receive)],
capture_output=True, text=True, timeout=10)
except subprocess.TimeoutExpired as exc:
output = exc.stdout or b''
if isinstance(output, bytes):
output = output.decode(errors='replace')
setup_entered = 'NATIVE_SETUP_BEGIN' in output and 'NATIVE_SETUP_RETURN' not in output
callback_entered = 'NATIVE_CALLBACK_BEGIN' in output and 'NATIVE_CALLBACK_RETURN' not in output
if not (setup_entered or callback_entered):
raise RuntimeError('Native probe timed out outside the checked native calls') from exc
test.fail('Native initialization or valid CAN callback did not finish within ten seconds')
setup_entered = 'NATIVE_SETUP_BEGIN' in result.stdout and 'NATIVE_SETUP_RETURN' not in result.stdout
callback_entered = 'NATIVE_CALLBACK_BEGIN' in result.stdout and 'NATIVE_CALLBACK_RETURN' not in result.stdout
if result.returncode == -signal.SIGSEGV and (setup_entered or callback_entered):
test.fail('Native initialization or valid CAN callback faulted: ' + result.stderr)
asserted = 'NATIVE_SETUP_ASSERTION' in result.stdout or 'NATIVE_CALLBACK_RETURN' in result.stdout
if result.returncode not in (0, 1) or not asserted:
raise RuntimeError(f'Native probe infrastructure failure ({result.returncode}): {result.stdout}{result.stderr}')
test.assertEqual(result.returncode, 0, result.stdout + result.stderr)

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