Compare commits

..

299 Commits

Author SHA1 Message Date
natehuby76 944e513e9f add official testing instructions to comma support 2026-11-25 01:16:59 -05:00
natehuby76 13ab471cc5 open private staff actions in older report threads 2026-11-25 01:02:49 -05:00
firestar5683 72aa8b89e1 Test Galaxy layout schema version 17 2026-11-25 00:01:06 -06:00
natehuby76 14babc867a open staff actions from the saved referral 2026-11-25 00:45:41 -05:00
natehuby76 69acfbb085 open staff actions privately from a ticket command 2026-11-25 00:41:25 -05:00
natehuby76 d4ddf420a5 match ticket colors and link fixes to testing requests 2026-11-25 00:33:35 -05:00
Raymond Nguyen 73eb7961d7 Honda Accord: angle steering for the modified EPS firmware 2026-11-24 23:29:49 -06:00
natehuby76 273f8b12e8 explain moved tickets to the reporter 2026-11-25 00:28:03 -05:00
natehuby76 cc36b77b65 share referral replies in the companion bot thread 2026-11-25 00:27:22 -05:00
natehuby76 3ab9f67c83 register the companion referral message command 2026-11-25 00:20:37 -05:00
firestar5683 df47158568 Fix Galaxy and C4 static analysis regressions 2026-11-24 23:11:51 -06:00
natehuby76 bc68e381ae recover companion referrals and confirm phone platform 2026-11-25 00:07:39 -05:00
Prabhaav Pillai f15af75c3a Adj Spot Monitoring for C4 2026-11-25 00:02:35 -05:00
natehuby76 1868dd0b90 update galaxy reporting and companion bot 2026-11-25 00:01:25 -05:00
firestar5683 5b21a4ba70 Retain stock MQB lateral intent after a fresh ACC Main cycle 2026-11-24 22:59:33 -06:00
firestar5683 6d5466a32f Scope Kona handoff helpers to supported builds 2026-11-24 22:52:34 -06:00
firestar5683 5dbc1d51b6 Qualify Kona factory steering handoff 2026-11-24 22:37:06 -06:00
firestar5683 48971bc6f9 Fix Galaxy route polling and CI regressions 2026-11-24 22:24:27 -06:00
firestar5683 6a958352e2 Restore continuous Kona factory steering handoff 2026-11-24 22:14:05 -06:00
firestar5683 bf8efea392 Recognize European 2019 Grand Cherokee diesel firmware 2026-11-24 21:34:19 -06:00
Danny 8f40396736 StarPort: Capture Brightness and Headunit Config in Logs 2026-11-24 17:52:26 -08:00
Raymond Nguyen b51d18fd56 honda: tidy the Accord carcontroller
Drop an extra blank line and a comment about an older tree; the prebuilt
receipt is refreshed for the source change.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-24 17:44:47 -08:00
Raymond Nguyen ac77f9a20c honda: rebuild the panda firmware for the Accord angle setpoint check
Built from 25323cef46 with the ARM64 device build container (DEBUG cert, as the
tracked images are), and the prebuilt receipt refreshed.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-24 17:26:38 -08:00
Raymond Nguyen 25323cef46 Honda Accord: angle steering for the modified EPS firmware
The 2020 Accord with EPS firmware 39990-TVA,A16C takes an angle setpoint in the
steering message. openpilot sends the setpoint, limited last by the 3.589 m/s^2
lateral acceleration and jerk limits, and the panda blocks any angle frame that
exceeds them.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-24 17:22:01 -08:00
firestar5683 b094bcb4f7 Make the Lead Indicator editable in Galaxy 2026-11-24 19:19:31 -06:00
firestar5683 ca16979a38 Keep Model Y pedal handoff smooth through coast 2026-11-24 19:11:53 -06:00
firestar5683 fa0914406f Dampen Palisade HDA II steering corrections 2026-11-24 19:10:24 -06:00
natehuby76 f86381d823 refresh prebuilt receipt for galaxy changes 2026-11-24 18:17:04 -05:00
natehuby76 206a8554db update galaxy support, connections and parked sentry alerts 2026-11-24 17:49:43 -05:00
firestar5683 b32fc5ec98 Verify Galaxy Bluetooth and Uniden preview behavior 2026-11-24 15:33:39 -06:00
firestar5683 22d4d34405 Move Card CAN callbacks into a dedicated module 2026-11-24 14:31:33 -06:00
firestar5683 0b18c93532 Improve moving Model Y accelerator handoff 2026-11-24 14:01:04 -06:00
firestar5683 0f8f2a5ace Prepare steering feedback before Card enters its control loop 2026-11-24 13:53:50 -06:00
firestar5683 a1084ad630 Reduce straight-line steering oscillation on Sienna with four-byte smartDSU 2026-11-24 13:53:11 -06:00
firestar5683 6509fa1a00 Recognize stock Corolla CAN mirroring during startup 2026-11-24 13:52:59 -06:00
firestar5683 f06a781387 Smooth Palisade HDA II exit steering 2026-11-24 13:51:36 -06:00
firestar5683 5c20480f13 Soften Model Y scroll-wheel acceleration transitions 2026-11-24 13:48:26 -06:00
firestar5683 13b4344a06 Test Palisade idle forwarding and expiry 2026-11-24 13:21:51 -06:00
firestar5683 be196c0baa Check the current FLM source-time disclosure 2026-11-24 12:53:53 -06:00
firestar5683 bf0344ffd7 Repair testing safety and static CI regressions 2026-11-24 12:46:18 -06:00
firestar5683 24b5235ed5 Default lane centering to off on new installs 2026-11-24 12:40:28 -06:00
firestar5683 725a530d8e Refine Ioniq 5 HDA I steering damping 2026-11-24 12:36:09 -06:00
firestar5683 1a53844575 Damp steering transients on Ioniq 5 HDA I 2026-11-24 12:33:02 -06:00
firestar5683 eaeb680b0a Keep HKG HDA II steering streams exclusive 2026-11-24 12:21:38 -06:00
firestar5683 7e9e2b43b3 Fix Palisade HDA II steering handoff 2026-11-24 11:57:55 -06:00
firestar5683 d0a212be98 Finish FLM recording queues without redundant reads 2026-11-24 11:48:34 -06:00
dirwin31 c9fea63596 Merge pull request #346 from dirwin31/Uniden
Uniden Radar Muting and Screen Integration
2026-11-24 09:19:57 -08:00
Danny 8852c7bce6 Build 2026-11-24 09:16:56 -08:00
Danny 71a9228954 Uniden: Integration 2026-11-24 09:16:53 -08:00
firestar5683 63fe5bb3e1 Pause highway smoothing while steering is limited 2026-11-24 10:31:29 -06:00
firestar5683 697dcf29e0 Show repeated steering requests in FLM drive reviews 2026-11-24 09:44:02 -06:00
firestar5683 591c5fcf53 Resume Corolla TSS2 from a PCM hold behind moving traffic 2026-11-24 09:35:27 -06:00
clementatt 78303dda84 Translate StarPilot into Simplified Chinese 2026-11-24 09:30:29 -06:00
clementatt fb4468b347 Translate StarPilot into Simplified Chinese
Complete app_zh-CHS.po for the device UI and Galaxy (5565 entries,
all translated).

Rebuild the Noto Sans CJK SC subset from the upstream font so it
covers the original cmap plus every character in app_zh-CHS.po, and
record the source and subset hashes in Noto-SOURCE.txt.

app_zh-CHS.po now exceeds the 120 KiB text limit, so add it to the
large-file allowlist alongside the other catalogs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 19:28:11 +09:00
firestar5683 c707dd4938 Repair GM, Palisade and Galaxy CI fixtures 2026-11-24 01:18:20 -06:00
firestar5683 698a203cbc Test preference reset with the real navigation owner 2026-11-23 23:48:12 -06:00
firestar5683 db79a4620d Align Subaru and Toyota CI with current vehicle contracts 2026-11-23 23:43:42 -06:00
firestar5683 48fb24ee48 Repair alert and Galaxy test fixtures 2026-11-23 23:37:59 -06:00
firestar5683 22f010c1ac Requalify FLM source provenance after navigation changes 2026-11-23 23:27:58 -06:00
firestar5683 d89f221d06 Repair static analysis and settings CI regressions 2026-11-23 23:26:32 -06:00
firestar5683 07331b33e8 Keep Kona handoff compliant with native safety lint 2026-11-23 23:19:22 -06:00
natehuby76 951beb26be Merge pull request #347 from natehuby76/smooth-nav-braking 2026-11-24 00:15:40 -05:00
firestar5683 683435ac68 Cover Kona handoff and Subaru sibling alerts in safety CI 2026-11-23 23:11:17 -06:00
firestar5683 241e0a43d4 Fix Galaxy local pairing with a new password 2026-11-23 22:59:05 -06:00
natehuby76 fad5a9faaf keep nav turns from canceling lane changes 2026-11-23 23:58:46 -05:00
firestar5683 19b7edf344 Keep stock MQB AOL armed through the first Panda acknowledgment 2026-11-23 22:54:38 -06:00
natehuby76 ab02d5a44c smooth navigation braking between gps fixes 2026-11-23 23:46:51 -05:00
firestar5683 8a9f7a084c Revert second-Panda Hyundai HDA2 stock cruise fallback 2026-11-23 22:46:29 -06:00
firestar5683 e59fa4930a Keep second-Panda Hyundai HDA2 on stock cruise at startup 2026-11-23 22:42:06 -06:00
firestar5683 855dfb3a17 Smooth tight-curve steering on Ioniq 5 HDA II 2026-11-23 22:33:32 -06:00
firestar5683 026ce00b72 Add device restart to Galaxy 2026-11-23 22:30:31 -06:00
firestar5683 3728cea591 Fix switching software branches in Galaxy 2026-11-23 22:14:35 -06:00
firestar5683 bc1edc500d Restore Save Me cleanup in Galaxy 2026-11-23 21:48:54 -06:00
firestar5683 330a302aa1 Keep stock Prius CAN healthy when the gap button signal is absent 2026-11-23 21:46:54 -06:00
firestar5683 6e879b55da Remove Galaxy reset that erases Wi-Fi settings 2026-11-23 21:39:06 -06:00
firestar5683 059612c13a Retain Subaru AOL when Panda sees the paddle shift first 2026-11-23 21:37:53 -06:00
firestar5683 bbe680c127 Allow remote Galaxy factory reset requests 2026-11-23 21:34:06 -06:00
firestar5683 ceb0bea247 Add the native factory reset to Galaxy 2026-11-23 20:22:45 -06:00
AngusBell97 35c80054d3 Add Tesla Model 3/Y wheel controls and comma-set dashboard speed 2026-11-23 20:15:03 -06:00
firestar5683 6cfa8b9f25 Restore Honda Fit steering after extended EPS pauses 2026-11-23 20:10:22 -06:00
firestar5683 919363f4fa Keep classic Ford discovery on the normal CAN harness 2026-11-23 20:09:55 -06:00
firestar5683 131ad10d63 Allow on-road startup without cloud registration 2026-11-23 19:54:30 -06:00
firestarsdog 47346ad98b Jetlink +tici support in controller 2026-11-23 20:11:19 -05:00
firestar5683 9c5a5e5b86 Preserve Mazda AOL intent at a complete stop 2026-11-23 18:16:19 -06:00
firestar5683 ce47ff1da3 Set a minimum width for automatic lane changes 2026-11-23 18:15:00 -06:00
firestar5683 55269d0856 Port Frogger900’s 2025 Subaru HUD and AVH features 2026-11-23 17:04:41 -06:00
firestar5683 0da55d93ae Ramp Honda Fit steering torque after EPS pauses 2026-11-23 17:01:30 -06:00
firestar5683 6f73fad098 Port Frogger900’s 2025 Subaru HUD and AVH features 2026-11-23 16:58:09 -06:00
firestar5683 9da91c24af Apply Coast Downhills changes during the drive 2026-11-23 16:56:49 -06:00
firestar5683 bd2e523bfe Default second-generation Niro EV to StarPilot steering 2026-11-23 16:37:53 -06:00
firestar5683 70de2df8f2 Refine Palisade HDA2 camera timing and highway response 2026-11-23 16:32:15 -06:00
firestar5683 d461cad223 Soften Sonata low-speed center corrections 2026-11-23 16:25:26 -06:00
firestar5683 a8d1dd1d91 Confirm manual MQB startup steering within its deadline 2026-11-23 16:18:57 -06:00
firestar5683 2151b3c77b Fix model selection on the large device UI 2026-11-23 16:13:32 -06:00
dirwin31 e555faacc1 Merge pull request #345 from dirwin31/StarPortAdapterCarLogging
StarPort: Add Logging
2026-11-23 14:09:50 -08:00
Danny e7f5d5fd4e StarPort: Log why an adapter has no car and name the car that tried to connect 2026-11-23 14:08:52 -08:00
Claude 9a32c18941 Regenerate cereal's C++ files for the Tesla schema additions
custom.capnp gained stepUnits, sourceTeslaGesture, the TeslaGesture struct
and the cruiseStep action, but the generated files kept beside it were not
updated. The build rewrote them, so the complete custom pytest catalog job
saw built trees that differed from the commit and rejected all 32 passing
shards. These are the files the build's own capnpc command writes
(Cap'n Proto 1.0.1, the version that reproduces stable's copies exactly).

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-23 22:07:39 +00:00
firestar5683 aafa97df61 Stabilize Palisade HDA2 steering and camera status 2026-11-23 15:51:25 -06:00
firestar5683 4f07a1ea4a Dampen longitudinal oscillation on four-byte filter Sienna 2026-11-23 15:49:30 -06:00
firestar5683 cf26c720f0 Restore the proven Kona steering handoff 2026-11-23 15:48:36 -06:00
firestar5683 ef38e75164 Preserve armed AOL through the speed ceiling 2026-11-23 15:48:29 -06:00
firestar5683 0ecbad2a41 Time out Connect registration during startup 2026-11-23 15:26:59 -06:00
firestar5683 ff9f0f0b33 Restore Kona factory steering while StarPilot is idle 2026-11-23 15:20:16 -06:00
firestar5683 d24bfcd0f3 Match Camry SE radar filter idle cruise messages 2026-11-23 15:18:23 -06:00
firestar5683 17ea1c3c3e Add independent TEMP gauge units to Galaxy 2026-11-23 15:11:39 -06:00
firestar5683 4ef3b1c2b4 Auto-detect the 2018 SASCM Volt CAN layout 2026-11-23 15:09:27 -06:00
firestar5683 f9bc75a3fd Clear stale Honda Fit steering integral after driver override 2026-11-23 15:05:38 -06:00
Claude f67edb6529 Tesla Model 3/Y: controls work with nothing saved, and three recovery fixes
- The input worker never parsed its settings on an install where CarControlAssignments had never been saved, so no
  scroll, stalk press or nudge reached the comma until a Wheel Controls row was changed. It now starts from the
  defaults.
- Saved assignments are used on either model: a Model 3 and a Model Y have the same controls. Before, a document
  saved on the other model gave no controls and locked every Wheel Controls row.
- Speed sync no longer waits for the Tesla's own speed to change after unanswered requests once the comma's speed is
  on the other side of the Tesla's (the Tesla had been at its own lowest or highest set speed).
- The UI restarts a stopped input worker after a wait that grows from 2 s to 30 s, instead of at most three times a
  drive. A first start that fails is retried on the same wait, not every frame.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-23 20:12:29 +00:00
firestar5683 fa66e9baac Show StarPilot release versions in update prompts 2026-11-23 12:57:37 -06:00
firestar5683 6dea0ec66c Allow downhill coasting from 1 percent grade 2026-11-23 12:37:02 -06:00
firestar5683 3fa425f769 Add Coast Downhills to Long Planner 2026-11-23 12:33:37 -06:00
Claude 7dbbb43c3b Add Tesla Model 3/Y wheel controls and comma-set dashboard speed
Everything here is limited to Tesla Model 3 and Model Y; other cars are unchanged. Most of it needs the Tesla CAN
add-on cable (Vehicle CAN).

Wheel Controls
- Right scroll wheel nudge left / right and holding either, right stalk half and full press while engaged, and a
  three-finger tap on the Tesla screen as assignable actions. Scroll up / down and stalk Down / Up are shown grayed,
  the scroll rows with their step (1, or to the next 5 for a fast scroll).
  Nudge right starts on Cycle Driving Personality.
- The three-finger tap's Always On Lateral on/off is chosen on its own row here: the Three-Finger AOL Tap row leaves
  Vehicle Settings, and TeslaAOLScreenTap is saved on by default.
- The Short press and Hold step rows are left out on a Model 3/Y, where StarPilot never steps the set speed from
  cruise buttons.
- A receive-only worker reads the wheel, stalk and screen frames. It only runs on a Model 3/Y with the cable.

Vehicle Settings
- Tesla CAN add-on cable row: detected or not, with buy and install links.
- Comma can set speed on Tesla dashboard (TeslaSpeedSync): off by default, experimental, needs the cable and Alpha
  Longitudinal, not offered on release builds. Takes effect within a second, without a restart.

With the switch on
- StarPilot keeps its own set speed; the right scroll wheel changes it by 1, or to the next multiple of 5.
- The Tesla's set speed is scrolled to match with right-scroll-wheel frames on Vehicle CAN, and scrolled back if the
  Tesla changes it.
- Speed Limit Controller writes the limit plus offset into the set speed instead of capping beneath it. Adopt limits
  early writes it early, and back again if the Maps preview is withdrawn. After an accelerator override: with Hold the
  speed you reached, lifting off above the limit makes the speed reached the set speed until the limit changes.

With the switch off, Speed Limit Controller and the set speed behave as before.

Also adds the Tesla dashboard speed limit (DAS_fusedSpeedLimit) as a Speed Limit Controller Dashboard source.

Panda: adds opendbc/safety/modes/tesla_speed_sync.h and safety-param bit 4096 (debug builds only), with tests. The bit
is set at startup on every eligible Model 3/Y so the switch works without a restart, so the images need rebuilding.
Always On Lateral's two exact-word checks accept the new bit. test_screen_recovery_callers.py and
test_tesla_screen_integration.py expect the bit on a car with the cable and StarPilot longitudinal.

Schema: SlcAction.ControllerCruiseAction gains stepUnits @13 and sourceTeslaGesture @14 (new TeslaGesture struct),
SlcAction.Kind gains cruiseStep @13. Settings keys: TeslaSpeedSync, CarControlAssignments.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-23 18:32:41 +00:00
firestar5683 777df8f6d8 Keep MQB AOL through a held-brake source handoff 2026-11-23 12:32:41 -06:00
firestar5683 f29ab3c676 Preserve Mazda lateral authority through Cancel deadline overlap 2026-11-23 12:31:11 -06:00
firestar5683 d197e09d3b Preserve Honda Fit AOL intent through EPS feedback reordering 2026-11-23 12:22:39 -06:00
firestar5683 24f65c6feb Recognize official StarPilot startup channels 2026-11-23 12:12:06 -06:00
firestar5683 cf2ddc0734 Complete verified FLM curve quieting trials 2026-11-23 11:55:09 -06:00
firestar5683 3693294b10 Show live thermal readings in Galaxy 2026-11-23 11:30:12 -06:00
firestar5683 0ea99a0128 Add Toggle Screen Off to Wheel Controls 2026-11-23 11:21:05 -06:00
firestar5683 981455ecc6 Keep parked FLM reads waiting for fresh status 2026-11-23 11:18:20 -06:00
firestar5683 2c53700269 Add a navigation turn slowdown distance slider 2026-11-23 11:14:41 -06:00
firestar5683 3393b7d698 Smooth Model Y manual cruise speed changes 2026-11-23 11:12:13 -06:00
firestar5683 ec4c158e20 Record Safe Mode in the route settings snapshot 2026-11-23 11:06:35 -06:00
firestar5683 1c087154ae Show detected stoplights while armed AOL is stationary 2026-11-23 11:01:37 -06:00
firestar5683 a46f9941e7 Keep Honda Fit AOL armed through delayed EPS feedback 2026-11-23 11:01:37 -06:00
firestar5683 47bbc2e1bf Show manual and learned FLM settings together 2026-11-23 10:51:54 -06:00
dirwin31 c0d7eeb09c Merge pull request #341 from dirwin31/HondaStarportToggles
Add Honda Starport Toggles
2026-11-23 07:44:03 -08:00
Danny 16786b6517 Build 2026-11-23 07:23:21 -08:00
Danny 00be4586e2 StarPort: Add wired hands-free toggle for cars that need it, and remove the Fit fix 2026-11-23 07:22:32 -08:00
firestar5683 0b0f216dff Rebalance lifecycle CI using current hosted timings 2026-11-23 02:15:32 -06:00
firestar5683 404ef33a96 Rebalance lifecycle CI using current hosted timings 2026-11-23 01:51:06 -06:00
firestar5683 b119731ad2 Recognize factory Camry radar and mirrored startup traffic for AOL 2026-11-22 23:58:51 -06:00
Sam Yau e71059b2d1 Subaru AOL: manual-mode ratio gears pause output, not intent 2026-11-22 23:54:37 -06:00
firestar5683 288027a08d Clarify Toyota factory ACC setting 2026-11-22 23:20:57 -06:00
firestar5683 0b5e75d9c5 Set StarPilot testing version to 7.0.2 2026-11-22 22:47:02 -06:00
firestar5683 9b25c7c0cc Share early Subaru steering and Cruise MAIN AOL 2026-11-22 22:33:21 -06:00
firestar5683 6ccf23ddb6 Share early Subaru steering and Cruise MAIN AOL 2026-11-22 22:31:35 -06:00
firestar5683 bb4840ab89 Restore early Crosstrek steering and Cruise MAIN AOL 2026-11-22 22:23:25 -06:00
firestar5683 7848780457 Restore early Crosstrek steering and Cruise MAIN AOL 2026-11-22 22:21:42 -06:00
firestar5683 b5931c365d Restore Toyota factory cruise selection in Vehicle Settings 2026-11-22 22:14:27 -06:00
firestar5683 6c2f6fc048 Show early Subaru Crosstrek in vehicle selection 2026-11-22 22:10:44 -06:00
firestar5683 3f5068a19b Retain Honda Fit AOL through brief EPS torque refusals 2026-11-22 22:04:12 -06:00
firestar5683 f7ef9b117c Capture parked status when an FLM read is interrupted 2026-11-22 22:03:37 -06:00
firestar5683 0972ef0d44 Keep Ford AOL armed through the Cancel safety echo 2026-11-22 22:02:26 -06:00
Sam Yau 459d2e6b94 Subaru AOL: manual-mode ratio gears pause output, not intent
In paddle/manual mode the Subaru transmission reports the simulated
ratio instead of D, which parses as GearShifter.unknown. The generic
disarming_fault() treated the resulting soft wrongGear event as a
disarming fault and cleared the AOL latch; with no fresh MAIN edge on
the return to Drive, AOL never resumed (pre-7.0 it resumed
automatically).

Add a Subaru-scoped intent_disarming_fault() that filters the soft
wrongGear event for qualified cars at unknown gear, dispatched like
the existing Volkswagen/Chrysler overrides. Output stays paused in
manual mode through the normal runtime and panda gates; only the
intent revocation is removed. Generic classification is unchanged.

Tests: openpilot/starpilot/car/subaru/tests/test_aol_manual_gear.py
2026-11-22 19:45:56 -08: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
900 changed files with 68381 additions and 5412 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
+4
View File
@@ -49,3 +49,7 @@ The explicit StarPilot [jacobw Subaru adapter](opendbc_repo/opendbc/car/subaru/J
The previous optional StarPilot Controller, formerly in `openpilot/starpilot/car/ford/starpilot_tuning.py`, restored demand tuning from StarPilot `8da0c9d916^`, descended from BluePilot bp-7.0 `e1d051d7ba270261b4455068bd68f1a58db15a4a` through StarPilot `2efe6017bfe14cee4807833e05f9a7f6ba255cdb`. Contributors to that lineage include Alan Polk, John Christman, Jacob Neulight, tonesto7 and Haibin Wen. The current protocol adapter is maintained by StarPilot separately from the pinned BluePilot library; this attribution does not imply BluePilot maintains or endorses the adapted tune.
The current StarPilot Controller replaces that historical curvature-primary tune with a separately maintained adaptation of BluePilot v0.2.1's angle strategy (`2b9dc6cc784faac47a1885d0bda0561f7b76f74d`, `core/lateral_angle_ext.py`). Alan Polk is the principal controller author; John Christman contributed angle-mode anti-stall work, Jacob Neulight the pinion/shadow measurement, Nathan Ingraham and Praeuner high-speed damping, and other contributors are retained in the pinned library's `CREDITS.md`. StarPilot adds bounded small-signal conditioning ahead of the unchanged angle limit chain. This adaptation is not maintained or endorsed by BluePilot; the pinned library and its imported hooks are unchanged.
## Uniden radar detector link
The Uniden detector link builds on **inauner's** earlier Uniden R4/R8/R9 work in [inauner/StarPilot, uniden](https://github.com/inauner/StarPilot/tree/c4b694b2ac8742ddec44123d53f1f84d2990b47e) (`uniden_protocol.py`, `uniden_r4.py`, `uniden_radar_d.py`, the Galaxy Uniden panel and the radar alert banner), which established the detector's BLE alert flow and the Galaxy/UI integration approach. This branch's monitor, transport, widgets and tests are a separate implementation on the current StarPilot Bluetooth owner; the experimental settings and speed-limit slowdown logic are not included. The alert parser and command framing are based on AegisX86/UnidenR8wlink (see THIRD_PARTY_NOTICES.md).
+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.
+4
View File
@@ -154,3 +154,7 @@ The Subaru angle implementation includes work from Jacob Waller's `jul-angle-bas
The historical tuning formerly in `openpilot/starpilot/car/ford/starpilot_tuning.py` included the BluePilot bp-7.0-derived work identified in [CREDITS.md](CREDITS.md#starpilot-ford-demand-tuning). The published upstream license notices retained above and in the pinned BluePilot library remain applicable to the adapted source. StarPilot's separate protocol adapter does not modify those notices or resolve their scope.
The angle-primary adaptation in `openpilot/starpilot/car/ford/starpilot_controller.py` is derived from BluePilot v0.2.1. It retains the complete MIT copyright and permission notice in `opendbc_repo/opendbc/bluepilot_lateral/LICENSE`, including Comma.ai, BluePilot and StarPilot contributors. See the contributor attribution in `CREDITS.md`.
## Uniden detector protocol
The detector alert parser and command framing in `openpilot/starpilot/uniden/` are based on [AegisX86/UnidenR8wlink](https://github.com/AegisX86/UnidenR8wlink)'s MIT-licensed protocol documentation, copyright (c) 2026 Aegis "P.R Aigis". The complete notice is retained in [UPSTREAM-LICENSE](openpilot/starpilot/uniden/UPSTREAM-LICENSE).
+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.
+45 -8
View File
@@ -10,12 +10,16 @@ from opendbc.car.fw_versions import (ObdCallback, get_fw_versions, get_fw_versio
get_present_ecus, match_fw_to_car)
from opendbc.car.mock.values import CAR as MOCK
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.gm.discovery import (automatic_trax_candidate, automatic_volt_ascm_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 (eps_needs_obd as honda_eps_needs_obd, 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
@@ -94,6 +98,7 @@ def can_fingerprint(can_recv: CanRecvCallable, *, vin: str = VIN_UNKNOWN,
frame += 1
car_fingerprint = automatic_volt_candidate(car_fingerprint, finger, candidate_cars)
car_fingerprint = automatic_volt_ascm_candidate(car_fingerprint, finger, candidate_cars, vin)
car_fingerprint = automatic_trax_candidate(car_fingerprint, finger, candidate_cars, vin)
return automatic_bolt_candidate(car_fingerprint, finger, camera_cruise_messages, vin), finger
@@ -143,6 +148,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 +192,40 @@ 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)
if normal_brand == 'honda' and honda_eps_needs_obd(match_fw_to_car(car_fw, vin)[1], car_fw):
# Read this car's VIN and EPS through the OBD port, as the generic path below does. Without the VIN
# the result is never cached, so every start would repeat the query.
set_obd_multiplexing(True)
vin_rx_addr, vin_rx_bus, vin = get_vin(can_recv, can_send, (0, 1))
car_fw = get_fw_versions(can_recv, can_send, set_obd_multiplexing, query_brand='honda')
ecu_rx_addrs = {(fw.responseAddress, fw.subAddress or None, fw.bus) for fw in car_fw if fw.responseAddress > 0}
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)
@@ -238,6 +270,11 @@ def fingerprint(can_recv: CanRecvCallable, can_send: CanSendCallable, set_obd_mu
# Refine after both automatic sources, before the explicit override below.
if not fixed_fingerprint:
car_fingerprint = automatic_bolt_candidate(car_fingerprint, finger, camera_cruise_messages, vin)
if car_fingerprint == 'SUBARU_IMPREZA' and source == CarParams.FingerprintSource.fw and exact_match:
# Subaru's early GT Crosstrek and Impreza share a firmware bucket.
# NHTSA vPIC identifies JF2GT with model-year codes J and K as Crosstrek.
if is_valid_vin(vin) and vin.startswith('JF2GT') and vin[9] in ('J', 'K'):
car_fingerprint = 'SUBARU_CROSSTREK_2018'
if fixed_fingerprint:
car_fingerprint = fixed_fingerprint
@@ -375,6 +375,7 @@ FW_VERSIONS = {
b'68402704AB',
b'68402707AB',
b'68402708AB',
b'68402710AB',
b'68402714AB',
b'68402736AB',
b'68402971AD',
@@ -421,6 +422,7 @@ FW_VERSIONS = {
b'68412635AH ',
b'68412660AD ',
b'68412660AF ',
b'68422857AD',
b'68422860AB',
b'68449435AE ',
b'68496223AA ',
@@ -435,6 +437,7 @@ FW_VERSIONS = {
b'68419675AC',
b'68419678AB',
b'68423905AB',
b'68423907AB',
b'68449258AC',
b'68495807AA',
b'68495807AB',
@@ -0,0 +1,57 @@
"""Recorded ECU identity for the EU 2019 Grand Cherokee, opendbc issue 4101."""
import pytest
from opendbc.car import structs
from opendbc.car.chrysler.interface import CarInterface
from opendbc.car.chrysler.values import CAR, ChryslerFlags
from opendbc.car.fingerprints import FW_VERSIONS
from opendbc.car.fw_versions import match_fw_to_car
Ecu = structs.CarParams.Ecu
RECORDED = (
(Ecu.combinationMeter, 0x742, b'68402710AB'),
(Ecu.srs, 0x744, b'68355363AB'),
(Ecu.abs, 0x747, b'68408639AC'),
(Ecu.fwdRadar, 0x753, b'04672788AA'),
(Ecu.eps, 0x75a, b'68417281AA'),
(Ecu.engine, 0x7e0, b'68422857AD'),
(Ecu.transmission, 0x7e1, b'68423907AB'),
)
ADDED = {b'68402710AB', b'68422857AD', b'68423907AB'}
def firmware():
return [structs.CarParams.CarFw(ecu=ecu, address=address, fwVersion=version, brand='chrysler', bus=0)
for ecu, address, version in RECORDED]
def test_recorded_eu_diesel_is_a_unique_exact_match():
fw = firmware()
assert match_fw_to_car(fw, '', allow_fuzzy=False, log=False) == (True, {CAR.JEEP_GRAND_CHEROKEE_2019})
# The route also contains unrelated cross-brand responses at the engine's neighbor.
fw.append(structs.CarParams.CarFw(ecu=Ecu.transmission, address=0x7e1, fwVersion=b'\xf1\0\0E\x01\x01', brand='hyundai', bus=1))
assert match_fw_to_car(fw, '', allow_fuzzy=False, log=False) == (True, {CAR.JEEP_GRAND_CHEROKEE_2019})
@pytest.mark.parametrize('index', range(len(RECORDED)))
def test_unknown_firmware_still_refuses_exact_match(index):
fw = firmware()
fw[index].fwVersion = b'UNRECOGNIZED'
assert match_fw_to_car(fw, '', allow_fuzzy=False, log=False) == (True, set())
def test_additions_are_scoped_to_the_existing_2019_jeep():
for identity, ecus in FW_VERSIONS.items():
found = {version for versions in ecus.values() for version in versions} & ADDED
assert found == (ADDED if identity == CAR.JEEP_GRAND_CHEROKEE_2019 else set())
@pytest.mark.parametrize('alpha_long', (False, True))
def test_diesel_retains_stock_acc_pid_and_native_limits(alpha_long):
cp = CarInterface.get_params(CAR.JEEP_GRAND_CHEROKEE_2019, {b: {} for b in range(8)}, firmware(), alpha_long, False, False)
assert cp.pcmCruise and not cp.openpilotLongitudinalControl
assert cp.safetyConfigs[0].safetyModel == structs.CarParams.SafetyModel.chrysler
assert cp.safetyConfigs[0].safetyParam == 0
assert cp.minSteerSpeed == 17.5 and cp.lateralTuning.which() == 'pid'
assert cp.flags & ChryslerFlags.HIGHER_MIN_STEERING_SPEED
assert not cp.flags & ChryslerFlags.STEERING_SPEED_BYPASS
@@ -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.
+11 -6
View File
@@ -1,4 +1,4 @@
"""Normal-bus discovery for explicitly selected Ford CAN-FD vehicles."""
"""Normal-bus discovery for Ford vehicles."""
import time
from opendbc.car.ford.values import CAR, FordFlags
@@ -42,7 +42,8 @@ def normal_bus0_selection(candidate):
# diagnostic query family; live VIN, ECU responses and fingerprinting still
# determine the vehicle and its control configuration.
NORMAL_BUS0_LAYOUT = {(0, 0x82): 8, (0, 0x165): 8, (0, 0x204): 8,
(0, 0x217): 8, (2, 0x3CA): 8, (2, 0x3D6): 8}
(0, 0x217): 8, (2, 0x3CA): 8}
CAMERA_STEERING_LAYOUT = {(2, 0x3D3): 8, (2, 0x3D6): 8}
def normal_bus_query_brand(can_recv, hyundai_probe, *, gm_probe=None, volvo_probe=None, tesla_probe=None, clock=time.monotonic):
@@ -55,6 +56,10 @@ def normal_bus_query_brand(can_recv, hyundai_probe, *, gm_probe=None, volvo_prob
reads = 0
deadline = clock() + .12
def complete():
return (not malformed and NORMAL_BUS0_LAYOUT.items() <= received.items() and
any(key in received for key in CAMERA_STEERING_LAYOUT))
def observe(**kwargs):
nonlocal malformed, gm_malformed, reads
reads += 1
@@ -67,9 +72,9 @@ def normal_bus_query_brand(can_recv, hyundai_probe, *, gm_probe=None, volvo_prob
length = len(frame.dat)
gm_malformed |= frame.address in bus and bus[frame.address] != length
bus[frame.address] = length
if key in NORMAL_BUS0_LAYOUT:
if (expected := NORMAL_BUS0_LAYOUT.get(key) or CAMERA_STEERING_LAYOUT.get(key)) is not None:
length = len(frame.dat)
malformed |= length != NORMAL_BUS0_LAYOUT[key]
malformed |= length != expected
received[key] = length
return packets
@@ -77,11 +82,11 @@ def normal_bus_query_brand(can_recv, hyundai_probe, *, gm_probe=None, volvo_prob
return 'hyundai'
# Rejecting HKG or Ford does not reject GM. Finish the shared passive window
# within its original budget even when an early frame excludes Ford.
while not (not malformed and received == NORMAL_BUS0_LAYOUT) and reads < 24 and clock() < deadline:
while not complete() and reads < 24 and clock() < deadline:
if malformed and ((gm_probe is None and volvo_probe is None and tesla_probe is None) or gm_malformed):
break
observe(wait_for_one=True)
if not malformed and received == NORMAL_BUS0_LAYOUT and normal_bus0_queries():
if complete() and normal_bus0_queries():
return 'ford'
if gm_probe is not None and not gm_malformed and gm_probe(gm_received):
return 'gm'
@@ -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):
+1 -1
View File
@@ -50,7 +50,7 @@ def migrate_assignments(params, cp):
('LongDistanceButtonControl', 'LongCancelButtonControl', 5),
('VeryLongDistanceButtonControl', 'VeryLongCancelButtonControl', 6))
pending = []
valid = tuple(str(value).encode() for value in range(15))
valid = tuple(str(value).encode() for value in range(16))
for source, target, default in pairs:
raw, readable = read_saved(params, target, 8)
previous, source_readable = read_saved(params, source, 8)
+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
+19
View File
@@ -46,6 +46,25 @@ def automatic_volt_candidate(candidate, fingerprint, candidates):
return CAR.CHEVROLET_VOLT_CC
def automatic_volt_ascm_candidate(candidate, fingerprint, candidates, vin):
# The recorded 2018 SASCM Volt falls out of both legacy CAN candidate lists.
if (candidate is not None or any(candidates.values()) or not isinstance(vin, str) or not is_valid_vin(vin) or
not vin.startswith('1G1RD6S5') or vin[9] != 'J'):
return candidate
pt = fingerprint.get(CanBus.POWERTRAIN, {})
camera = fingerprint.get(CanBus.CAMERA, {})
radar = fingerprint.get(CanBus.OBSTACLE, {})
required = {0xC9: 8, 0x180: 4, 0x184: 8, 0x1C4: 8, 0x1E1: 7,
0x2FF: 4, 0x348: 5, 0x34A: 5, 0x370: 6}
if (pt != camera or any(pt.get(address) != size for address, size in required.items()) or
radar.get(0x460) != 8 or radar.get(0x474) != 8 or
any(address in pt for address in (0xBE, 0x201)) or pt.get(0x320) not in (None, 3) or
any(messages for bus, messages in fingerprint.items() if bus not in (CanBus.POWERTRAIN, CanBus.OBSTACLE, CanBus.CAMERA))):
return candidate
return CAR.CHEVROLET_VOLT_ASCM
# Frequent normal-bus frames observed on mirrored pedal installations. This is
# only diagnostic query-family evidence, never a vehicle/control fingerprint.
PEDAL_NORMAL_BUS_LAYOUT = {0xD3: 2, 0xBE: 6, 0xC9: 8, 0x1C4: 8,
@@ -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)])])
@@ -0,0 +1,58 @@
import json
from pathlib import Path
from types import SimpleNamespace
from unittest.mock import patch
import pytest
from opendbc.car import car_helpers, structs
from opendbc.car.can_definitions import CanData
from opendbc.car.gm.values import CAR
VIN = '1G1RD6S50JU000001'
RECORDED = Path(__file__).parent / 'testdata/volt_2018_ascm_fingerprint.json'
@pytest.fixture
def fingerprint():
return {int(bus): {int(address): size for address, size in messages.items()}
for bus, messages in json.loads(RECORDED.read_text()).items()}
def receive(fingerprint):
packets = [CanData(address, bytes(size), bus)
for bus, messages in fingerprint.items() for address, size in messages.items()]
return lambda **kwargs: [packets]
def test_recorded_startup_selects_ascm_and_preserves_manual_override(fingerprint):
fw = structs.CarParams.CarFw.new_message(brand='gm', logging=True)
cache = SimpleNamespace(carFingerprint='MOCK', carVin=VIN, carFw=[fw], brand='mock')
with patch.dict(car_helpers.os.environ, {'FINGERPRINT': '', 'SKIP_FW_QUERY': '', 'DISABLE_FW_CACHE': ''}), \
patch.object(car_helpers, 'get_vin', return_value=(0x64B, 0, VIN)), \
patch.object(car_helpers, 'get_fw_versions', return_value=[fw]):
args = (receive(fingerprint), lambda _: None, lambda _: None, False, True)
auto = car_helpers.get_car(*args, cached_params=cache).CP
manual = car_helpers.get_car(*args, forced_candidate=CAR.CHEVROLET_VOLT).CP
assert auto.carFingerprint == CAR.CHEVROLET_VOLT_ASCM
assert auto.fingerprintSource == structs.CarParams.FingerprintSource.can
assert auto.pcmCruise and not auto.openpilotLongitudinalControl and not auto.dashcamOnly
assert auto.safetyConfigs[0].safetyParam == 0xE05
assert manual.carFingerprint == CAR.CHEVROLET_VOLT
assert manual.fingerprintSource == structs.CarParams.FingerprintSource.fixed
@pytest.mark.parametrize('vin', ['0' * 17, '1G1RD6S50KU000001', '1G1FX6S50JU000001'])
def test_layout_alone_does_not_match(fingerprint, vin):
assert car_helpers.can_fingerprint(receive(fingerprint), vin=vin)[0] is None
@pytest.mark.parametrize('bus,address,size', [(0, 0x2FF, 8), (0, 0x201, 6), (0, 0x320, 6),
(2, 0x180, None), (1, 0x474, None)])
def test_other_harness_or_control_sources_do_not_match(fingerprint, bus, address, size):
for target in (0, 2) if bus == 0 else (bus,):
if size is None:
fingerprint[target].pop(address)
else:
fingerprint[target][address] = size
assert car_helpers.can_fingerprint(receive(fingerprint), vin=VIN)[0] != CAR.CHEVROLET_VOLT_ASCM
@@ -0,0 +1,5 @@
{
"0": {"189": 7, "193": 8, "197": 8, "201": 8, "209": 7, "211": 2, "241": 6, "298": 8, "304": 1, "308": 4, "309": 8, "311": 8, "313": 8, "320": 3, "328": 1, "352": 5, "381": 6, "384": 4, "386": 8, "388": 8, "451": 8, "452": 8, "453": 6, "479": 3, "481": 7, "485": 8, "489": 8, "493": 8, "497": 8, "500": 6, "501": 8, "528": 4, "532": 6, "560": 8, "562": 8, "563": 5, "565": 5, "566": 5, "608": 8, "609": 6, "610": 6, "611": 6, "612": 8, "613": 8, "707": 8, "715": 8, "717": 5, "761": 7, "767": 4, "810": 8, "840": 5, "842": 5, "844": 8, "869": 4, "880": 6, "977": 8, "1001": 8, "1017": 8, "1020": 8, "1033": 7, "1034": 7, "1217": 8, "1221": 5, "1233": 8, "1249": 8, "1265": 8, "1267": 1, "1280": 4, "1296": 4, "1300": 8, "1922": 7, "1930": 7},
"1": {"161": 7, "262": 5, "309": 1, "768": 8, "771": 2, "774": 8, "776": 7, "784": 6, "848": 8, "849": 8, "850": 8, "851": 8, "852": 8, "853": 8, "854": 3, "1033": 7, "1034": 7, "1056": 6, "1057": 8, "1058": 8, "1059": 8, "1060": 8, "1061": 8, "1062": 8, "1063": 8, "1064": 8, "1065": 8, "1066": 8, "1067": 8, "1068": 8, "1088": 8, "1089": 8, "1090": 8, "1091": 8, "1092": 8, "1093": 8, "1094": 8, "1095": 8, "1096": 8, "1097": 8, "1098": 8, "1099": 8, "1100": 8, "1120": 8, "1121": 8, "1122": 8, "1123": 8, "1124": 8, "1125": 8, "1126": 8, "1127": 8, "1128": 8, "1129": 8, "1130": 8, "1131": 8, "1132": 8, "1133": 8, "1134": 8, "1135": 8, "1136": 8, "1137": 8, "1138": 8, "1139": 8, "1140": 8, "1141": 8, "1142": 8, "1143": 8, "1146": 8, "1147": 8, "1148": 8, "1149": 8, "1150": 8, "1151": 8, "1362": 8, "1857": 8, "1859": 8, "1920": 7},
"2": {"189": 7, "193": 8, "197": 8, "201": 8, "209": 7, "211": 2, "241": 6, "298": 8, "304": 1, "308": 4, "309": 8, "311": 8, "313": 8, "320": 3, "328": 1, "352": 5, "381": 6, "384": 4, "386": 8, "388": 8, "451": 8, "452": 8, "453": 6, "479": 3, "481": 7, "485": 8, "489": 8, "493": 8, "497": 8, "500": 6, "501": 8, "528": 4, "532": 6, "560": 8, "562": 8, "563": 5, "565": 5, "566": 5, "608": 8, "609": 6, "610": 6, "611": 6, "612": 8, "613": 8, "707": 8, "715": 8, "717": 5, "761": 7, "767": 4, "810": 8, "840": 5, "842": 5, "844": 8, "869": 4, "880": 6, "977": 8, "1001": 8, "1017": 8, "1020": 8, "1033": 7, "1034": 7, "1217": 8, "1221": 5, "1233": 8, "1249": 8, "1265": 8, "1267": 1, "1280": 4, "1296": 4, "1300": 8, "1922": 7, "1930": 7}
}
+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."""
@@ -1,3 +1,5 @@
import math
import numpy as np
from opendbc.car import ACCEL_MAX_TAKEOFF
@@ -10,9 +12,12 @@ from opendbc.car.honda.nidec_interceptor import NidecInterceptor, create_command
from opendbc.car.honda.bosch_longitudinal import BoschLongitudinal, qualified as bosch_long_qualified
from opendbc.car.honda.values import CAR, CruiseButtons, HondaFlags, CarControllerParams
from opendbc.car.interfaces import CarControllerBase
from opendbc.car.lateral import apply_steer_angle_limits_vm, get_max_angle_delta_vm
from opendbc.car.vehicle_model import VehicleModel
VisualAlert = structs.CarControl.HUDControl.VisualAlert
LongCtrlState = structs.CarControl.Actuators.LongControlState
SteerControlType = structs.CarParams.SteerControlType
def compute_gb_honda_bosch(accel, speed):
@@ -120,6 +125,54 @@ class CarController(CarControllerBase):
self.brake = 0.0
self.last_torque = 0.0
# Accord angle-loop EPS (interface.py sets steerControlType = angle)
self.angle_mode = CP.steerControlType == SteerControlType.angle
self.VM = VehicleModel(CP) if self.angle_mode else None
self.apply_angle_last = None # None until the first frame seeds the limiter from the wheel
self.angle_steer_req = False # STEER_TORQUE_REQUEST of the last angle frame
def _angle_hold_allowed(self, CC, CS) -> bool:
# The panda blocks a nonzero 0xE4 field unless lateral_controls_allowed(). Without an AOL policy that is
# controls_allowed (needs ACC main on and engagement); with one it is a session-acknowledged axis permission the
# carcontroller cannot see, so the hold is sent only in the subset every policy allows: enabled with main on.
return bool(CS.out.cruiseState.available) and bool(CC.enabled)
def _update_angle(self, CC, CS) -> tuple[float, int]:
"""Angle setpoint (deg) and the 0xE4 STEER_TORQUE field."""
p = self.params
steering_angle = float(CS.out.steeringAngleDeg)
angle_last = steering_angle if self.apply_angle_last is None else self.apply_angle_last
desired = float(CC.actuators.steeringAngleDeg)
if CC.latActive:
# error clip first: it shapes the request, bounding the P torque the setpoint asks of the EPS
error_max = float(np.interp(CS.out.vEgoRaw, p.ANGLE_ERROR_MAX_BP, p.ANGLE_ERROR_MAX_V))
desired = float(np.clip(desired, steering_angle - error_max, steering_angle + error_max))
# The lateral accel and jerk limits (3.589) are the last adjustment: applied to exactly what is sent and seeded
# from the last value sent. The panda runs the same check on the frame (honda.h) and blocks one that exceeds it,
# so nothing may change the setpoint after this line.
apply_angle = apply_steer_angle_limits_vm(desired, angle_last, CS.out.vEgoRaw, steering_angle, CC.latActive, p, self.VM)
self.angle_steer_req = bool(CC.latActive)
if CC.latActive:
v = max(float(CS.out.vEgoRaw), 1.0)
max_delta = min(get_max_angle_delta_vm(v, self.VM, p), p.ANGLE_LIMITS.MAX_ANGLE_RATE)
if abs(apply_angle - angle_last) > max_delta + 1e-6:
# The accel limit is further from the last value sent than the jerk limit lets one frame move: the wheel is
# past the limit as the request starts. No setpoint satisfies both, and the panda would drop the frame, so
# the request waits at the wheel until the wheel is back inside.
apply_angle = steering_angle
self.angle_steer_req = False
self.apply_angle_last = apply_angle
# raw = round(-10 * deg), half-up; left-positive degrees are negative raw
if CC.latActive:
raw = math.floor(-10.0 * apply_angle + 0.5)
elif self._angle_hold_allowed(CC, CS):
# idle hold: keep the setpoint at the wheel so engagement starts without a step
raw = math.floor(-10.0 * steering_angle + 0.5)
else:
raw = 0 # the panda blocks a nonzero field here
return apply_angle, int(np.clip(raw, -p.ANGLE_RAW_MAX, p.ANGLE_RAW_MAX))
def update(self, CC, CS, now_nanos):
_projection = self.learning_projection_observer
if _projection is not None:
@@ -176,7 +229,12 @@ class CarController(CarControllerBase):
can_sends.append(make_tester_present_msg(0x18DAB0F1, 1, suppress_response=True))
# Send steering command.
can_sends.append(hondacan.create_steering_control(self.packer, self.CAN, apply_torque, CC.latActive, self.tja_control))
if self.angle_mode:
apply_angle, angle_raw = self._update_angle(CC, CS)
can_sends.append(hondacan.create_steering_control(self.packer, self.CAN, angle_raw, self.angle_steer_req,
self.tja_control, angle_arm=self.params.ANGLE_ARM))
else:
can_sends.append(hondacan.create_steering_control(self.packer, self.CAN, apply_torque, CC.latActive, self.tja_control))
if _projection is not None:
_projection.emit('honda.STEERING_CONTROL', apply_torque, CC.latActive, can_sends[-1])
@@ -286,6 +344,9 @@ class CarController(CarControllerBase):
new_actuators.brake = self.brake
new_actuators.torque = self.last_torque
new_actuators.torqueOutputCan = apply_torque
if self.angle_mode:
new_actuators.steeringAngleDeg = apply_angle
new_actuators.torqueOutputCan = angle_raw # the 0xE4 STEER_TORQUE field as sent (-10 x deg)
self.frame += 1
if _projection is not None:
@@ -13,6 +13,7 @@ from opendbc.car.dashboard_speed_limit import Tracker as LimitTracker, honda_sig
from opendbc.can.dbc import DBC as CANDBC
TransmissionType = structs.CarParams.TransmissionType
SteerControlType = structs.CarParams.SteerControlType
ButtonType = structs.CarState.ButtonEvent.Type
BUTTONS_DICT = {CruiseButtons.RES_ACCEL: ButtonType.accelCruise, CruiseButtons.DECEL_SET: ButtonType.decelCruise,
@@ -120,6 +121,16 @@ class CarState(CarStateBase):
ret.steerFaultPermanent = False
ret.steerFaultTemporary = False
if self.CP.flags & HondaFlags.EPS_FW_UNREAD:
ret.steerFaultPermanent = True
if self.CP.steerControlType == SteerControlType.angle and self.CP.flags & HondaFlags.EPS_ANGLE_LOOP_FW:
# the angle-loop EPS's angle is a valid absolute angle only while all three sensor status bits read 1; outside
# that the EPS would servo from a false angle, so do not steer
sensors = cp.vl["STEERING_SENSORS"]
if not all(sensors[f"STEER_SENSOR_STATUS_{i}"] == 1 for i in (1, 2, 3)):
ret.steerFaultTemporary = True
# All Honda EPS cut off slightly above standstill, some much higher
# Don't alert in the near-standstill range, but alert for per-vehicle configured minimums above that
if CarControllerParams.STEER_GLOBAL_MIN_SPEED < ret.vEgo < (self.CP.minSteerSpeed + 0.5):
+23 -4
View File
@@ -1,4 +1,5 @@
from opendbc.car.honda.hondacan import honda_checksum
from opendbc.car.honda.values import CAR
# Classic Bosch: PT on bus 1 and the stock ACC camera on bus 2. This selects
@@ -7,14 +8,32 @@ 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)
def eps_needs_obd(candidates, car_fw) -> bool:
"""The Accord's EPS answers only through the OBD port (never on the normal bus 1 wiring), and its firmware
family decides between angle and torque steering. A normal-bus read that names the Accord is not complete."""
return CAR.HONDA_ACCORD in candidates and not any(fw.ecu == "eps" and not fw.logging for fw in car_fw)
+6 -2
View File
@@ -117,11 +117,15 @@ def create_acc_commands(packer, CAN, enabled, active, accel, gas, stopping_count
return commands
def create_steering_control(packer, CAN, apply_torque, lkas_active, tja_control):
def create_steering_control(packer, CAN, apply_torque, lkas_active, tja_control, angle_arm=None):
# angle_arm (Accord angle-loop EPS only): STEER_TORQUE is the angle setpoint, sent with the request off too, and
# STEER_CONTROL_ARM carries the arm the EPS lane requires. None = the torque frame, unchanged.
values = {
"STEER_TORQUE": apply_torque if lkas_active else 0,
"STEER_TORQUE": apply_torque if (lkas_active or angle_arm is not None) else 0,
"STEER_TORQUE_REQUEST": lkas_active,
}
if angle_arm is not None:
values["STEER_CONTROL_ARM"] = angle_arm
if tja_control:
values["STEER_DOWN_TO_ZERO"] = lkas_active
+24 -2
View File
@@ -7,7 +7,9 @@ from opendbc.car import Bus, get_safety_config, structs, uds
from opendbc.car.common.conversions import Conversions as CV
from opendbc.car.disable_ecu import disable_ecu
from opendbc.car.honda.hondacan import CanBus
from opendbc.car.honda.values import CarControllerParams, HondaFlags, CAR, HondaSafetyFlags, MANUAL_TRANS_CARS, MODIFIED_EPS_FW, DBC
from opendbc.car.honda.values import CarControllerParams, HondaFlags, CAR, HondaSafetyFlags, MANUAL_TRANS_CARS, MODIFIED_EPS_FW, DBC, \
is_accord_eps_angle_loop_fw
from opendbc.car.lateral import MAX_LATERAL_ACCEL
from opendbc.car.honda.carcontroller import CarController
from opendbc.car.honda.carstate import CarState
from opendbc.car.honda.radar_interface import RadarInterface
@@ -100,7 +102,12 @@ class CarInterface(CarInterfaceBase):
ret.longitudinalTuning.kiV = [1.2, 0.8, 0.5]
eps_observations = [fw for fw in car_fw if fw.ecu == "eps" and not fw.logging]
modified_eps = any(b"," in fw.fwVersion for fw in eps_observations)
# Accord angle-loop EPS firmware (39990-TVA,A16<letter>): the EPS closes the angle loop and openpilot sends the
# setpoint. Not a torque-modified EPS, so it is kept out of the MODIFIED_EPS_FW allow-list check below (which would
# otherwise make the car dashcam-only). Every EPS response must be the family; a mixed read falls through to it.
eps_angle_loop_fw = (candidate == CAR.HONDA_ACCORD and len(eps_observations) > 0 and
all(is_accord_eps_angle_loop_fw(fw.fwVersion) for fw in eps_observations))
modified_eps = not eps_angle_loop_fw and any(b"," in fw.fwVersion for fw in eps_observations)
eps_modified = bool(modified_eps) and all(
fw.address == 0x18DA30F1 and fw.subAddress == 0 and
fw.fwVersion in MODIFIED_EPS_FW.get(candidate, ()) for fw in eps_observations)
@@ -121,6 +128,21 @@ class CarInterface(CarInterfaceBase):
elif candidate == CAR.HONDA_ACCORD:
ret.lateralTuning.pid.kpV, ret.lateralTuning.pid.kiV = ([[0.3], [0.09]] if eps_modified else [[0.6], [0.18]])
if eps_angle_loop_fw:
# angle-loop EPS firmware: the EPS closes the angle loop, openpilot sends the setpoint
ret.flags |= HondaFlags.EPS_ANGLE_LOOP_FW.value
ret.safetyConfigs[-1].safetyParam |= HondaSafetyFlags.ACCORD_ANGLE.value
ret.steerControlType = structs.CarParams.SteerControlType.angle
ret.steerActuatorDelay = CarControllerParams.ANGLE_STEER_ACTUATOR_DELAY
# The torque fit's MAX_LAT_ACCEL_MEASURED (0.32 m/s^2) means nothing to an angle setpoint; the onroad torque
# bar divides by this, so normalise it by the angle limit instead (3.589 m/s^2, where the setpoint clamp binds).
# Measured engaged hands-off over 35 routes: p99.9 3.46 m/s^2, per-route maxima 3.4-4.1. Only the bar and the
# car docs read maxLateralAccel; no controller or torque tune does.
ret.maxLateralAccel = MAX_LATERAL_ACCEL
elif not docs and not eps_observations:
# EPS fw unread: an angle-loop EPS would ignore torque frames (engaged, no steering, no alert), so fault instead.
# Note: upstream lists this EPS as non-essential (lost without comma power); such an Accord faults here too.
ret.flags |= HondaFlags.EPS_FW_UNREAD.value
elif candidate == CAR.HONDA_ACCORD_11G:
ret.longitudinalActuatorDelay = 0.05
+6 -1
View File
@@ -37,8 +37,11 @@ MANUAL_SELECTION_PORTS = CLASSIC_BOSCH | NIDEC | RADARLESS | CANFD_STOCK | ALT_R
# qualified() runs several times per 100 Hz frame in card and selfdrived, so
# everything that depends only on this module is computed once, and its flag
# tests use plain ints: IntFlag operators cost microseconds each in Python.
# EPS_ANGLE_LOOP_FW / EPS_FW_UNREAD: Accord-only EPS-firmware detections (interface.py); the angle car keeps AOL, and
# an unread EPS is already a permanent steer fault in carstate, so neither may drop the car out of these owners.
_DETECTED = int(HondaFlags.BOSCH_EXT_HUD | HondaFlags.BOSCH_ALT_BRAKE | HondaFlags.HAS_BSM |
HondaFlags.EPS_MODIFIED | HondaFlags.HYBRID | HondaFlags.GAS_INTERCEPTOR)
HondaFlags.EPS_MODIFIED | HondaFlags.HYBRID | HondaFlags.GAS_INTERCEPTOR |
HondaFlags.EPS_ANGLE_LOOP_FW | HondaFlags.EPS_FW_UNREAD)
_ALLOWED_FLAGS = {str(car): int(car.config.flags) | _DETECTED
for car in CLASSIC_BOSCH | NIDEC | RADARLESS | CANFD_STOCK | ALT_RADAR_STOCK | {CAR.HONDA_ACCORD_11G}}
_BOSCH, _BOSCH_RADARLESS, _BOSCH_ALT_BRAKE = int(HondaFlags.BOSCH), int(HondaFlags.BOSCH_RADARLESS), int(HondaFlags.BOSCH_ALT_BRAKE)
@@ -102,6 +105,8 @@ def qualified(cp, *, marked_only=False):
safety.safetyModel == _HONDA_NIDEC and safety.safetyParam == expected)
if fingerprint in CLASSIC_BOSCH and flags & _BOSCH and not flags & _BOSCH_RADARLESS:
expected = int(bool(flags & _BOSCH_ALT_BRAKE))
if fingerprint == CAR.HONDA_ACCORD and flags & int(HondaFlags.EPS_ANGLE_LOOP_FW):
expected |= int(HondaSafetyFlags.ACCORD_ANGLE)
if cp.openpilotLongitudinalControl:
expected |= int(HondaSafetyFlags.BOSCH_LONG)
if fingerprint == CAR.ACURA_RDX_3G:
@@ -39,9 +39,11 @@ def test_mixed_nonlogging_eps_still_refuses_modified_profile(other):
assert not cp.flags & HondaFlags.EPS_MODIFIED
def test_recorded_custom_angle_eps_remains_unsupported_in_mainline():
def test_recorded_custom_angle_eps_steers_by_angle():
cp = params(CAR.HONDA_ACCORD, [eps(ANGLE), eps(SERIAL, logging=True)])
assert cp.dashcamOnly
assert not cp.dashcamOnly
assert cp.flags & HondaFlags.EPS_ANGLE_LOOP_FW
assert cp.steerControlType == structs.CarParams.SteerControlType.angle
assert not cp.flags & HondaFlags.EPS_MODIFIED
@@ -0,0 +1,364 @@
"""Accord on the angle-loop EPS firmware (39990-TVA,A16<letter>): detection, the 0xE4 frame, the setpoint limits."""
import math
from types import SimpleNamespace
import numpy as np
import pytest
from opendbc import get_generated_dbcs
from opendbc.can import CANPacker
from opendbc.car import Bus, gen_empty_fingerprint
from opendbc.car.honda.carcontroller import CarController
from opendbc.car.honda.carstate import CarState
from opendbc.car.honda.hondacan import CanBus, create_steering_control
from opendbc.car.honda.interface import CarInterface
from opendbc.car.honda.values import CAR, DBC, CarControllerParams, HondaFlags, HondaSafetyFlags, is_accord_eps_angle_loop_fw, \
accord_angle_steer_ratio, ACCORD_ANGLE_SR_BP, ACCORD_ANGLE_SR_V
from opendbc.car.interfaces import get_torque_params
from opendbc.car.lateral import MAX_LATERAL_ACCEL, apply_steer_angle_limits_vm, get_max_angle_delta_vm, get_max_angle_vm
from opendbc.car.toyota.interface import CarInterface as ToyotaInterface
from opendbc.car.toyota.values import CAR as TOYOTA
from opendbc.car.structs import CarParams
P = CarControllerParams
STEERING_CONTROL = 0xE4
def _eps_fw(fw: bytes):
return [CarParams.CarFw(ecu=CarParams.Ecu.eps, fwVersion=fw, address=0x18DA30F1, subAddress=0)]
def accord_cp(eps_fw: bytes | None):
car_fw = [] if eps_fw is None else _eps_fw(eps_fw)
return CarInterface.get_params(CAR.HONDA_ACCORD, gen_empty_fingerprint(), car_fw, False, False, False)
@pytest.mark.parametrize("fw, expected", [
(b"39990-TVA,A16A\x00\x00", True), # V298, NUL-padded as the car reports it
(b"39990-TVA,A16B\x00\x00", True), # V299
(b"39990-TVA,A16C", True), # the release
(b"39990-TVA,A160\x00\x00", False), # torque-map images
(b"39990-TVA-A160\x00\x00", False), # stock
(b"39990-TVA,A16", False),
(b"39990-TVA,A16AB", False),
(b"39990-TVA,A16a", False),
(b"39990-TVB,A16A", False),
])
def test_fw_detection(fw, expected):
assert is_accord_eps_angle_loop_fw(fw) is expected
@pytest.mark.parametrize("fw", [b"39990-TVA,A16A\x00\x00", b"39990-TVA,A16B\x00\x00", b"39990-TVA,A16C\x00\x00"])
def test_angle_fw_selects_angle_control(fw):
CP = accord_cp(fw)
assert CP.steerControlType == CarParams.SteerControlType.angle
assert CP.flags & HondaFlags.EPS_ANGLE_LOOP_FW
assert CP.safetyConfigs[0].safetyParam & HondaSafetyFlags.ACCORD_ANGLE
assert CP.steerActuatorDelay == pytest.approx(P.ANGLE_STEER_ACTUATOR_DELAY)
# the angle fw carries a ',' but is not a torque-modified EPS: it must not hit the MODIFIED_EPS_FW dashcam fallback
assert not CP.dashcamOnly
assert not CP.flags & HondaFlags.EPS_MODIFIED
assert not CP.flags & HondaFlags.EPS_FW_UNREAD
def test_angle_fw_on_another_honda_is_not_angle_control():
# the family is Accord-only; on any other platform the ',' read is the upstream modified-EPS path
CP = CarInterface.get_params(CAR.HONDA_CIVIC_BOSCH, gen_empty_fingerprint(), _eps_fw(b"39990-TVA,A16C\x00\x00"),
False, False, False)
assert CP.steerControlType == CarParams.SteerControlType.torque
assert not CP.flags & HondaFlags.EPS_ANGLE_LOOP_FW
assert not CP.safetyConfigs[0].safetyParam & HondaSafetyFlags.ACCORD_ANGLE
def test_mixed_eps_read_is_not_angle_control():
car_fw = _eps_fw(b"39990-TVA,A16C\x00\x00") + _eps_fw(b"39990-TVA-A160\x00\x00")
CP = CarInterface.get_params(CAR.HONDA_ACCORD, gen_empty_fingerprint(), car_fw, False, False, False)
assert CP.steerControlType == CarParams.SteerControlType.torque
assert not CP.flags & HondaFlags.EPS_ANGLE_LOOP_FW
assert not CP.safetyConfigs[0].safetyParam & HondaSafetyFlags.ACCORD_ANGLE
assert CP.dashcamOnly # upstream: a ',' EPS outside MODIFIED_EPS_FW
def test_angle_control_needs_no_params():
"""A fresh install selects angle control from the EPS fw alone and keeps the pid tuning block untouched.
Old tree (83fa2e68c8) also pinned this against stale torque-era toggles (ForceTorqueController, NNFF, NNFF Lite)
passed into get_params; this tree's get_params takes no toggles and has no ForceTorqueController conversion at all,
so only the fw-alone half of that test still has an API to exercise."""
CP = CarInterface.get_params(CAR.HONDA_ACCORD, gen_empty_fingerprint(), _eps_fw(b"39990-TVA,A16C"), False, False, False)
assert CP.steerControlType == CarParams.SteerControlType.angle
assert CP.lateralTuning.which() == "pid"
assert CarController({Bus.pt: DBC[CAR.HONDA_ACCORD][Bus.pt]}, CP).angle_mode
@pytest.mark.parametrize("fw", [None, b"39990-TVA-A160\x00\x00", b"39990-TVA,A160\x00\x00"])
def test_other_fw_keeps_torque_control(fw):
CP = accord_cp(fw)
assert CP.steerControlType == CarParams.SteerControlType.torque
assert not CP.flags & HondaFlags.EPS_ANGLE_LOOP_FW
assert not CP.safetyConfigs[0].safetyParam & HondaSafetyFlags.ACCORD_ANGLE
assert not CarController({Bus.pt: DBC[CAR.HONDA_ACCORD][Bus.pt]}, CP).angle_mode
def test_max_lateral_accel_is_the_angle_limit_only_on_the_angle_fw():
# the onroad torque bar divides by CP.maxLateralAccel; the torque fit's 0.32 m/s^2 pegged it on every turn
torque_fit = get_torque_params()[CAR.HONDA_ACCORD]['MAX_LAT_ACCEL_MEASURED']
assert torque_fit == pytest.approx(0.3247, abs=1e-4)
assert accord_cp(b"39990-TVA,A16C").maxLateralAccel == pytest.approx(MAX_LATERAL_ACCEL)
assert MAX_LATERAL_ACCEL == pytest.approx(3.589, abs=1e-3)
for fw in (None, b"39990-TVA-A160\x00\x00", b"39990-TVA,A160\x00\x00"):
assert accord_cp(fw).maxLateralAccel == pytest.approx(torque_fit)
angle_fw = _eps_fw(b"39990-TVA,A16C")
for car in (CAR.HONDA_CIVIC_BOSCH, CAR.HONDA_CRV_5G):
CP = CarInterface.get_params(car, gen_empty_fingerprint(), angle_fw, False, False, False)
assert CP.maxLateralAccel == pytest.approx(get_torque_params()[car]['MAX_LAT_ACCEL_MEASURED'])
CP = ToyotaInterface.get_params(TOYOTA.TOYOTA_RAV4_TSS2, gen_empty_fingerprint(), [], False, False, False)
assert CP.maxLateralAccel == pytest.approx(get_torque_params()[TOYOTA.TOYOTA_RAV4_TSS2]['MAX_LAT_ACCEL_MEASURED'])
def _steer_faults(CP):
# an unfed parser set: only the fault logic, not the bus contents, is under test
CS = CarState(CP)
ret = CS.update(CS.get_can_parsers(CP))
return ret.steerFaultPermanent
@pytest.mark.parametrize("fw, angle, unread", [
(b"39990-TVA,A16C\x00\x00", True, False), # angle EPS read -> angle mode
(b"39990-TVA-A160\x00\x00", False, False), # stock EPS read -> torque mode, no fault
(b"39990-TVA,A160\x00\x00", False, False), # torque-map EPS read -> torque mode, no fault
(None, False, True), # no EPS fw at all -> permanent fault
])
def test_eps_fw_unread_faults(fw, angle, unread):
CP = accord_cp(fw)
assert (CP.steerControlType == CarParams.SteerControlType.angle) == angle
assert bool(CP.flags & HondaFlags.EPS_FW_UNREAD) == unread
if not angle:
# same unfed bus for every case, so the fault is decided by the flag alone (the read cases are the control)
assert _steer_faults(CP) == unread
def test_docs_params_do_not_fault():
CP = CarInterface.get_params(CAR.HONDA_ACCORD, gen_empty_fingerprint(), [], False, False, True)
assert not CP.flags & HondaFlags.EPS_FW_UNREAD
def _upstream_dbc(tmp_path):
# the Accord DBC without STEER_CONTROL_ARM, i.e. as it was before the signal was added. The *_generated DBCs are
# built in memory in this tree (opendbc.get_generated_dbcs), so the stripped copy is written out from that content.
name = DBC[CAR.HONDA_ACCORD][Bus.pt]
content = get_generated_dbcs()[name]
assert "STEER_CONTROL_ARM" in content
lines = [ln for ln in content.splitlines(keepends=True) if "STEER_CONTROL_ARM" not in ln]
path = tmp_path / f"{name}.dbc"
path.write_text("".join(lines), encoding="utf-8")
return str(path)
def test_torque_frame_unchanged_by_the_dbc_signal(tmp_path):
CP = accord_cp(None)
new = CANPacker(DBC[CAR.HONDA_ACCORD][Bus.pt])
old = CANPacker(_upstream_dbc(tmp_path))
can = CanBus(CP)
for torque in range(-4096, 4097, 37):
for active in (False, True):
for tja in (False, True):
assert create_steering_control(new, can, torque, active, tja) == create_steering_control(old, can, torque, active, tja)
@pytest.mark.parametrize("active", [False, True])
def test_angle_frame_carries_the_arm_and_a_valid_checksum(active):
packer = CANPacker(DBC[CAR.HONDA_ACCORD][Bus.pt])
can = CanBus(accord_cp(b"39990-TVA,A16C"))
for raw in (-4000, -1234, -1, 0, 1, 987, 4000):
addr, dat, _ = create_steering_control(packer, can, raw, active, False, angle_arm=P.ANGLE_ARM)
assert addr == STEERING_CONTROL
assert (dat[2] >> 2) & 0x3 == P.ANGLE_ARM # byte 2 bits 3:2
assert int.from_bytes(dat[0:2], "big", signed=True) == raw # setpoint sent with the request off too
assert bool(dat[2] & 0x80) == active # STEER_TORQUE_REQUEST
sig = packer.dbc.addr_to_msg[addr].sigs["CHECKSUM"]
zeroed = bytearray(dat)
zeroed[4] &= 0xF0
assert sig.calc_checksum(addr, sig, zeroed) == dat[4] & 0xF # CHECKSUM 35|4 = byte 4 low nibble
def _controller(aol=False):
CP = accord_cp(b"39990-TVA,A16C")
if aol:
CP.alternativeExperience |= 32 # always-on lateral: the hold must NOT depend on it (the 7.0 panda predicate is a session grant)
return CarController({Bus.pt: DBC[CAR.HONDA_ACCORD][Bus.pt]}, CP)
def _cc_cs(desired, measured, v, lat_active, enabled=True, main_on=True):
CC = SimpleNamespace(actuators=SimpleNamespace(steeringAngleDeg=desired), latActive=lat_active, enabled=enabled)
CS = SimpleNamespace(out=SimpleNamespace(steeringAngleDeg=measured, vEgoRaw=v, cruiseState=SimpleNamespace(available=main_on)))
return CC, CS
def test_error_clip_then_the_accel_and_jerk_limits():
# the error clip shapes the request, the accel/jerk limiter runs last on it, and what is sent is the limiter's output
cc = _controller()
assert cc.angle_mode
v, measured = 20.0, 0.0
err = float(np.interp(v, P.ANGLE_ERROR_MAX_BP, P.ANGLE_ERROR_MAX_V))
state = measured
for _ in range(400):
state = apply_steer_angle_limits_vm(min(90.0, measured + err), state, v, measured, True, cc.params, cc.VM)
apply_angle, raw = cc._update_angle(*_cc_cs(90.0, measured, v, True))
assert apply_angle == cc.apply_angle_last == state
assert raw == math.floor(-10.0 * apply_angle + 0.5)
assert apply_angle == pytest.approx(measured + err) # the wheel never moved: the send settles on the clip
@pytest.mark.parametrize("v", [1.0, 5.0, 10.0, 17.5, 26.9, 35.0])
def test_what_is_sent_never_exceeds_the_accel_and_jerk_limits(v):
# whatever the wheel does (a driver holding it far past the limit, or yanking it), every frame sent stays inside
# the 3.589 lateral accel angle and steps no further than the 3.589 jerk limit from the previous frame sent
rng = np.random.default_rng(int(v * 10))
cc = _controller()
max_angle = get_max_angle_vm(v, cc.VM, cc.params)
max_delta = min(get_max_angle_delta_vm(v, cc.VM, cc.params), P.ANGLE_LIMITS.MAX_ANGLE_RATE)
err = float(np.interp(v, P.ANGLE_ERROR_MAX_BP, P.ANGLE_ERROR_MAX_V))
wheel = min(max_angle + err + 10.0, 390.0) # held past the limit: the case the old order got wrong
prev, _ = cc._update_angle(*_cc_cs(0.0, 0.0, v, True))
for i in range(600):
if i > 200:
wheel = float(np.clip(wheel + rng.normal(0.0, 3.0), -390.0, 390.0)) # then moving up to several hundred deg/s
sent, raw = cc._update_angle(*_cc_cs(float(rng.uniform(-400.0, 400.0)), wheel, v, True))
assert abs(sent) <= min(max_angle, P.ANGLE_LIMITS.STEER_ANGLE_MAX) + 1e-9
assert abs(sent - prev) <= max_delta + 1e-9
assert raw == math.floor(-10.0 * sent + 0.5)
prev = sent
def test_wheel_motion_inside_the_error_clip_does_not_feed_the_setpoint():
# same command, different wheel paths that stay inside the clip: the setpoint must not depend on the wheel
rng = np.random.default_rng(0)
a, b = _controller(), _controller()
a.apply_angle_last = b.apply_angle_last = 0.0
err = float(np.interp(12.0, P.ANGLE_ERROR_MAX_BP, P.ANGLE_ERROR_MAX_V))
for i in range(300):
desired = 20.0 * math.sin(i / 20.0)
wheel = float(np.clip(rng.normal(0.0, 10.0), -(err - 21.0), err - 21.0))
a._update_angle(*_cc_cs(desired, 0.0, 12.0, True))
b._update_angle(*_cc_cs(desired, wheel, 12.0, True))
assert a.apply_angle_last == b.apply_angle_last
def test_setpoint_returns_to_the_request_at_the_jerk_limit_after_the_clip_releases():
# wheel pushed away (clip binds), then let go: the setpoint walks back, it does not jump
cc = _controller()
v = 20.0
err = float(np.interp(v, P.ANGLE_ERROR_MAX_BP, P.ANGLE_ERROR_MAX_V))
max_delta = get_max_angle_delta_vm(v, cc.VM, cc.params)
cc.apply_angle_last = 0.0
for _ in range(300):
pushed, _ = cc._update_angle(*_cc_cs(0.0, err + 5.0, v, True))
assert pushed == pytest.approx(5.0) # held at the clip edge, wheel - err
back, _ = cc._update_angle(*_cc_cs(0.0, 0.0, v, True))
assert back == pytest.approx(5.0 - max_delta)
def test_request_waits_at_the_wheel_while_the_wheel_is_past_the_accel_limit():
# lateral goes active with the wheel past the accel-limit angle: the limit is more than one jerk step away, so no
# setpoint is legal. The frame holds the wheel with the request off, and the request starts once the wheel is inside.
cc = _controller()
v = 26.9
max_angle = get_max_angle_vm(v, cc.VM, cc.params)
max_delta = get_max_angle_delta_vm(v, cc.VM, cc.params)
for wheel in (max_angle + 20.0, max_angle + 5.0, max_angle + max_delta + 0.1):
sent, raw = cc._update_angle(*_cc_cs(0.0, wheel, v, True))
assert not cc.angle_steer_req
assert sent == wheel and raw == math.floor(-10.0 * wheel + 0.5)
wheel = max_angle + 0.5 * max_delta
cc._update_angle(*_cc_cs(0.0, wheel, v, True)) # the last value sent was the wheel further out: one more frame waits
assert not cc.angle_steer_req
sent, raw = cc._update_angle(*_cc_cs(0.0, wheel, v, True))
assert cc.angle_steer_req
assert sent == pytest.approx(wheel - max_delta) # one jerk step in from the wheel, inside the accel limit
for _ in range(50): # and it stays on from there
prev = sent
sent, _ = cc._update_angle(*_cc_cs(0.0, wheel, v, True))
assert cc.angle_steer_req and abs(sent - prev) <= max_delta + 1e-9 and abs(sent) <= max_angle + 1e-9
def test_request_bit_follows_lat_active_otherwise():
cc = _controller()
cc._update_angle(*_cc_cs(3.0, 1.0, 20.0, True))
assert cc.angle_steer_req
cc._update_angle(*_cc_cs(3.0, 1.0, 20.0, False))
assert not cc.angle_steer_req
def test_each_step_is_bounded_by_the_rate_limit():
# MAX_ANGLE_RATE = 2.5 deg/frame (250 deg/s): no frame may step further than that
cc = _controller()
prev = 0.0
for _ in range(5):
a, _ = cc._update_angle(*_cc_cs(90.0, 0.0, 3.0, True))
assert abs(a - prev) <= P.ANGLE_LIMITS.MAX_ANGLE_RATE + 1e-9
prev = a
def test_first_frame_seeds_from_the_wheel():
cc = _controller()
a, _ = cc._update_angle(*_cc_cs(30.0, 25.0, 10.0, True))
assert abs(a - 25.0) <= P.ANGLE_LIMITS.MAX_ANGLE_RATE + 1e-9
@pytest.mark.parametrize("enabled, main_on, aol, holds", [
(True, True, False, True),
(False, True, True, False), # always-on lateral with ACC main on: the panda's grant is not visible here, so no hold
(True, True, True, True),
(False, True, False, False),
(True, False, False, False), # the panda drops controls_allowed with main off
(False, False, True, False),
])
def test_idle_hold(enabled, main_on, aol, holds):
cc = _controller(aol)
measured = -12.34
apply_angle, raw = cc._update_angle(*_cc_cs(50.0, measured, 15.0, False, enabled, main_on))
assert apply_angle == measured # lateral off: the limiter follows the wheel
assert raw == (math.floor(-10.0 * measured + 0.5) if holds else 0)
def test_raw_is_clipped():
cc = _controller()
cc.apply_angle_last = 399.0
_, raw = cc._update_angle(*_cc_cs(400.0, 399.0, 1.0, True))
assert raw == -P.ANGLE_RAW_MAX
def test_steer_ratio_map_level():
assert accord_angle_steer_ratio(0.0) == pytest.approx(16.84)
for deg in (0.0, 45.0, 120.0, -200.0, 500.0):
expected = float(np.interp(abs(deg), ACCORD_ANGLE_SR_BP, ACCORD_ANGLE_SR_V)) * 16.84 / 16.88
assert accord_angle_steer_ratio(deg) == pytest.approx(expected)
def test_error_clip_is_the_p_room_under_the_firmware_sum_clamp():
# Operator rule (2026-10-21): the clip is the angle error where the V300 firmware's P term alone equals
# Kmax - Imax (sum clamp 15360 after the 254/256 taper, so 15481 before it; I cap 4096 / 6144 / 8192 by
# speed). Integer mirror of the image: E = 16 * 10 * deg, E' = (E * G(v)) >> 8, P = (E' * 112) >> 8.
g_v = {3.1: 1178, 8.0: 1465, 10.0: 760, 11.75: 560, 17.5: 1068, 26.9: 2188}
for v, clip in zip(P.ANGLE_ERROR_MAX_BP, P.ANGLE_ERROR_MAX_V, strict=True):
imax = 4096 if v <= 6.0 else (6144 if v <= 12.5 else 8192)
p_of = lambda deg, v=v: (((16 * round(10 * deg) * g_v[v]) >> 8) * 112) >> 8 # noqa: E731
assert p_of(clip) >= 15481 - imax > p_of(clip - 0.1)
def test_angle_frame_is_sent_by_the_controller():
# the full update(): angle mode packs the setpoint with the arm; the projection observer is never installed on angle
CP = accord_cp(b"39990-TVA,A16C")
ci = CarInterface(CP)
from opendbc.car import structs
CC = structs.CarControl(enabled=True, latActive=True)
CC.actuators.steeringAngleDeg = 5.0
ci.update([])
out, sends = ci.apply(CC.as_reader(), 1_000_000_000)
steer = [s for s in sends if s[0] == STEERING_CONTROL]
assert len(steer) == 1
dat = steer[0][1]
assert (dat[2] >> 2) & 0x3 == P.ANGLE_ARM
assert int.from_bytes(dat[0:2], "big", signed=True) == out.torqueOutputCan
assert out.steeringAngleDeg == pytest.approx(-out.torqueOutputCan / 10.0, abs=0.05)
@@ -1,5 +1,6 @@
import json
from pathlib import Path
from types import SimpleNamespace
import unittest
from unittest.mock import patch
@@ -33,6 +34,32 @@ class TestHondaNormalDiscovery(unittest.TestCase):
generic_query.assert_not_called()
self.assertIsNone(actual[0])
def _accord_discovery(self, normal_read, obd_read):
from opendbc.car.honda.values import CAR
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', side_effect=[normal_read, obd_read]) as query, \
patch('opendbc.car.car_helpers.match_fw_to_car', return_value=(True, {CAR.HONDA_ACCORD})), \
patch('opendbc.car.car_helpers.can_fingerprint', return_value=(None, {})):
actual = fingerprint(lambda wait_for_one=False: [recorded_frames()], lambda frames: None, switches.append, None)
return switches, vin, query, actual
def test_accord_without_an_eps_read_queries_the_obd_port(self):
radar = SimpleNamespace(ecu="fwdRadar", logging=False, responseAddress=0, subAddress=0, bus=1)
eps = SimpleNamespace(ecu="eps", logging=False, responseAddress=0, subAddress=0, bus=1)
switches, vin, query, actual = self._accord_discovery([radar], [radar, eps])
self.assertEqual(switches, [False, True, False])
self.assertEqual(vin.call_count, 2)
self.assertEqual([call.kwargs for call in query.call_args_list],
[{'query_brand': 'honda', 'normal_bus_only': True}, {'query_brand': 'honda'}])
self.assertEqual(actual[3], [radar, eps])
def test_accord_with_an_eps_read_stays_on_normal_wiring(self):
eps = SimpleNamespace(ecu="eps", logging=False, responseAddress=0, subAddress=0, bus=1)
switches, vin, query, _ = self._accord_discovery([eps], AssertionError("no second query"))
self.assertFalse(any(switches))
query.assert_called_once()
def test_incomplete_or_invalid_traffic_cannot_select_honda(self):
from opendbc.car.honda.discovery import normal_bus_topology
frames = recorded_frames()
+74
View File
@@ -1,11 +1,14 @@
from dataclasses import dataclass, field
from enum import Enum, IntFlag
import numpy as np
from opendbc.car import Bus, CarSpecs, DbcDict, PlatformConfig, Platforms, structs, uds
from opendbc.car.common.conversions import Conversions as CV
from opendbc.car.docs_definitions import CarFootnote, CarHarness, CarDocs, CarParts, Column
from opendbc.car.fw_query_definitions import FwQueryConfig, Request, StdQueries, p16
from opendbc.car.honda.firmware_validation import validate_fw_match
from opendbc.car.lateral import AngleSteeringLimitsVM, MAX_LATERAL_ACCEL, MAX_LATERAL_JERK
Ecu = structs.CarParams.Ecu
VisualAlert = structs.CarControl.HUDControl.VisualAlert
@@ -41,6 +44,27 @@ class CarControllerParams:
STEER_DELTA_DOWN = 3
STEER_GLOBAL_MIN_SPEED = 3 * CV.MPH_TO_MS
# ---- Accord on the angle-loop EPS firmware (HondaFlags.EPS_ANGLE_LOOP_FW). 0xE4 STEER_TORQUE carries an angle
# setpoint, raw = round(-10 * deg) in carState.steeringAngleDeg's frame, and the EPS closes a 1 kHz angle loop on it.
# The panda checks every such frame (STEER_CONTROL_ARM == 2) against the same lateral accel and jerk limits with
# the same vehicle model (honda.h, HONDA_ACCORD_ANGLE_PARAMS), and blocks one that exceeds them.
ANGLE_LIMITS: AngleSteeringLimitsVM = AngleSteeringLimitsVM(
400, # deg; the EPS clamps its setpoint at raw +-4096
MAX_LATERAL_ACCEL=MAX_LATERAL_ACCEL, # 3.589 m/s^2
MAX_LATERAL_JERK=MAX_LATERAL_JERK, # 3.589 m/s^3
MAX_ANGLE_RATE=2.5, # deg/frame = 250 deg/s (V299 drives ran 250; Tesla and Rivian run 250 deg/s too)
)
# Error clip |setpoint - measured angle| <= ANGLE_ERROR_MAX(v): bounds the P torque the setpoint can demand. Each
# knot = the error at which the firmware's P term alone fills the room left under the PID sum clamp when the
# integral sits at its cap (operator rule, 2026-10-21): P = Kmax - Imax, read from the V300 image:
# P = ((16*10*deg * G(v)) >> 8) * 112 >> 8, Kmax = 15360 after the 254/256 taper (15481 before it),
# Imax = 4096 (<= 6 m/s), 6144 (6-12.5 m/s), 8192 (above, the ICL), G(v) = 1178/1465/760/560/1068/2188 at the knots.
ANGLE_ERROR_MAX_BP = [3.1, 8.0, 10.0, 11.75, 17.5, 26.9] # m/s, the firmware gain-table knots
ANGLE_ERROR_MAX_V = [35.4, 23.4, 45.0, 61.0, 25.0, 12.2] # deg (was 17.0, 15.5, 19.5, 17.0, 8.5, 4.5, model-sized)
ANGLE_RAW_MAX = 4000 # raw clip before packing
ANGLE_ARM = 2 # 0xE4 STEER_CONTROL_ARM: the EPS lane runs only while it reads 2; sent on every frame
ANGLE_STEER_ACTUATOR_DELAY = 0.15 # s, the inner angle loop's lag (model value; lagd learns the rest)
def __init__(self, CP):
self.BOSCH_GAS_LOOKUP_BP = list(type(self).BOSCH_GAS_LOOKUP_BP)
gas_max = {CAR.HONDA_CIVIC_BOSCH: 750, CAR.HONDA_ODYSSEY_5G_MMR: 2000,
@@ -92,6 +116,7 @@ class HondaSafetyFlags(IntFlag):
RADARLESS = 8
BOSCH_CANFD = 16
BOSCH_CANFD_MVL = 64
ACCORD_ANGLE = 4096
CLASSIC_LONG_AOL = 2048 # Exact marked DEBUG classic Bosch alpha owner.
ALT_RADAR_AOL = 1024 # Exact marked DEBUG alpha owner; physical EPS/gear token.
NIDEC_PEDAL_AOL = 512 # Model1 only; distinct from model20 STOCK_TJA.
@@ -121,6 +146,55 @@ class HondaFlags(IntFlag):
BOSCH_TJA_CONTROL = 4096
EPS_MODIFIED = 8192
GAS_INTERCEPTOR = 16384
EPS_ANGLE_LOOP_FW = 32768 # the Accord EPS reports the angle-loop firmware (is_accord_eps_angle_loop_fw)
EPS_FW_UNREAD = 65536 # Accord with no EPS fw response: the firmware family is unknown, so do not steer
# Accord EPS angle-loop firmware family: 39990-TVA,A16 + exactly one capital letter (A16A, A16B, A16C ...). Torque
# images read 39990-TVA,A160 (a digit) and stock 39990-TVA-A1x0, so neither matches.
ACCORD_EPS_ANGLE_LOOP_FW_FAMILY = b"39990-TVA,A16"
def is_accord_eps_angle_loop_fw(fw_version: bytes) -> bool:
v = bytes(fw_version).rstrip(b"\x00") # the EPS pads fwVersion with NULs
family = ACCORD_EPS_ANGLE_LOOP_FW_FAMILY
return len(v) == len(family) + 1 and v.startswith(family) and ord("A") <= v[-1] <= ord("Z")
# ---- Accord, angle mode only (steerControlType == angle): the variable-ratio rack map.
# In angle mode sR turns the model's curvature 1:1 into the angle setpoint, so the ratio is a tune here and the learner
# is ignored. SHAPE: absolute ratios measured over 82 routes, V[0] = the on-centre nominal. Not measurements:
# 0-23 deg (pinned by convention, not identified), 31-61 deg (interpolated across two bins that failed the lag test),
# 236+ deg (frozen; above 303 deg the data is parking speed). A compensation curve for calc_curvature's k = d/L,
# not the rack's true geometry. Bands: shape +/-0.12, level +/-0.57.
ACCORD_ANGLE_SR_BP = [0.0, 23.0, 31.0, 61.0, 76.0, 95.0, 116.0, 151.0, 178.0, 227.0, 236.0, 303.0, 380.0] # deg
ACCORD_ANGLE_SR_V = [16.88, 16.88, 16.88, 16.25, 15.97, 15.45, 15.03, 14.68, 14.45, 14.09, 14.25, 12.98, 12.31] # :1
# LEVEL: the served on-centre ratio; the whole shape is scaled by LEVEL / V[0]. 16.84 = the SteerRatio every angle
# drive ran (V298/V299 configs).
ACCORD_ANGLE_SR_LEVEL = 16.84
def accord_angle_steer_ratio(steer_angle_deg: float) -> float:
"""Local ratio of the Accord's rack at this wheel angle (deg, offset removed)."""
ratio = float(np.interp(abs(steer_angle_deg), ACCORD_ANGLE_SR_BP, ACCORD_ANGLE_SR_V))
return ratio * ACCORD_ANGLE_SR_LEVEL / ACCORD_ANGLE_SR_V[0]
def accord_angle_at_own_ratio(angle_vm_deg: float, sr_vm: float, max_passes: int = 10) -> float:
"""The angle setpoint with the map evaluated at the DESIRED angle instead of the measured one.
controlsd sets VM.sR = map(measured angle) and get_steer_from_curvature is linear in sR, so the consistent setpoint
is the fixed point theta = angle_vm_deg * map(theta) / sr_vm. Each pass shrinks the error by <= 0.44 (worst on the
236-303 deg knot); stops within 0.01 deg, a tenth of the EPS setpoint quantum.
"""
theta = float(angle_vm_deg)
for _ in range(max_passes):
nxt = float(angle_vm_deg) * accord_angle_steer_ratio(theta) / sr_vm
done = abs(nxt - theta) < 0.01
theta = nxt
if done:
break
return theta
# Car button codes
@@ -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,16 +115,47 @@ 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,
KONA_IDLE_AOL_WORD = 0x1C0C
LONG_AOL_WORDS |= CCNC_LONG_AOL_WORDS | {KONA_IDLE_AOL_WORD}
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,
}
def kona_idle_handoff_profile(cp):
return (cp.carFingerprint == CAR.HYUNDAI_KONA_2ND_GEN and len(cp.safetyConfigs) == 1 and
cp.alphaLongitudinalAvailable and cp.openpilotLongitudinalControl and not cp.pcmCruise and
_base_word(cp, experiences=(0, 32)) == 0x408)
def qualified_long(cp, *, marked_only=False):
if cp.carFingerprint == CAR.KIA_EV6 and int(cp.flags) & _FLAG_CANFD_LKA_STEER_MSG:
from opendbc.car.hyundai.ev6_aol import qualified as ev6_qualified
@@ -139,15 +170,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)
@@ -155,6 +196,8 @@ def qualified_long(cp, *, marked_only=False):
if not raw & 0x2000:
return False
raw &= ~0x2000
if raw == KONA_IDLE_AOL_WORD:
return cp.alternativeExperience == 32 and kona_idle_handoff_profile(cp)
return (raw == (word | 0x804) and cp.alternativeExperience == 32) or (
not marked_only and raw == (word | 4) and cp.alternativeExperience == 0
)
@@ -31,6 +31,7 @@ from opendbc.car.hyundai.canfd_lfa_status import preserves_stock_lfa
from opendbc.car.hyundai.classic_scc_aol import qualified as qualified_classic_stock_aol
from opendbc.car.hyundai.classic_long_aol import AOL_EXPERIENCE, qualified as qualified_classic_long_aol
from opendbc.car.hyundai.canfd_stock_aol import qualified as qualified_canfd_stock_aol, qualified_long as qualified_canfd_long_aol
from opendbc.car.hyundai.canfd_stock_aol import KONA_IDLE_AOL_WORD
from opendbc.car.hyundai.g90_longitudinal import G90LongitudinalPolicy
from opendbc.car.hyundai.gv70_longitudinal import is_gv70, scc_request, suppress_stock_cancel
from opendbc.car.hyundai.g90_lead import G90LeadState, eligible as g90_lead_eligible
@@ -123,6 +124,7 @@ class CarController(CarControllerBase):
self.apply_angle_last = 0.0
self.angle_gain_last = 0.0
self.angle_fault_driver_override = False
self.stock_angle_lka_active = False
self.angle_tx_recovery = (AngleTxRecovery(0xCB, self.CAN.ECAN)
if pe_long_qualified(CP) or ev9_long_qualified(CP) else AngleTxRecovery(0x110, self.CAN.ACAN)
if CP.carFingerprint in (CAR.HYUNDAI_IONIQ_5_PE, CAR.KIA_EV9) and
@@ -132,10 +134,16 @@ 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
self.blended_disengage_frame = None
self.blended_camera_sent_frame = -5
self.blended_camera_sent_counter = None
self.last_ccnc_161_ts_ns = 0
self.last_ccnc_162_ts_ns = 0
self.last_ccnc_now_ns = 0
@@ -170,6 +178,7 @@ class CarController(CarControllerBase):
int(CP.safetyConfigs[-1].safetyParam) in (0x0811, 0x0891))
self.canfd_torque_aol_status = (qualified_canfd_stock_aol(CP) or qualified_canfd_long_aol(CP))
self.ccnc_fault_ownership_required = preserves_stock_lfa(CP)
self.kona_last_lfa_counter = None
self.canfd_dash_icons = CanFDDashIcons() if ioniq6_status or self.canfd_torque_aol_status else None
self.classic_dash_icons = CanFDDashIcons() if classic_aol_dash_enabled(CP) else None
self.classic_lfa_icon = None
@@ -294,6 +303,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
@@ -338,9 +357,15 @@ class CarController(CarControllerBase):
sys_warning, sys_state, CC.enabled, hud_control.leftLaneVisible, hud_control.rightLaneVisible,
left_lane_warning, right_lane_warning, {}, include_alerts=False, counter_mod=0xF,
fcw_opt_usm=2 if apply_steer_req or icon == 3 else 1))
if (self.frame % 5 == 0 and CS.out.canValid and not CS.out.canTimeout and
CS.blended_camera_current):
can_sends.append(hyundaicanfd.create_suppress_lfa(self.packer, self.CAN, CS.lfa_block_msg, False))
if CS.out.canValid and not CS.out.canTimeout and CS.blended_camera_current:
camera_counter = CS.lfa_block_msg["COUNTER"]
if (self.frame - self.blended_camera_sent_frame >= 5 and camera_counter != self.blended_camera_sent_counter and
(not CC.latActive or CS.blended_camera_updated)):
can_sends.append(hyundaicanfd.create_suppress_lfa(self.packer, self.CAN, CS.lfa_block_msg, False))
self.blended_camera_sent_frame = self.frame
self.blended_camera_sent_counter = camera_counter
else:
self.blended_camera_sent_counter = None
else:
_projection_packet_index = len(can_sends) if _projection is not None else 0
can_sends.extend(hyundaican.create_lkas11_can_canfd_blended(
@@ -520,7 +545,9 @@ class CarController(CarControllerBase):
angle_active, self.params, self.angle_vm)
self.angle_gain_last = angle_torque_reduction_gain(CS.out.steeringTorque, CS.out.vEgoRaw,
angle_active, self.angle_gain_last)
if not ccnc_ev_stock or ccnc_ev_replacement:
stock_angle_handoff = angle_aol and lka_steering and not ccnc_ev_stock
if ((not ccnc_ev_stock or ccnc_ev_replacement) and
(not stock_angle_handoff or angle_active or self.stock_angle_lka_active)):
can_sends.extend(
hyundaicanfd.create_angle_steering_messages(
self.packer,
@@ -534,6 +561,7 @@ class CarController(CarControllerBase):
CS.out.steeringAngleDeg,
)
)
self.stock_angle_lka_active = stock_angle_handoff and angle_active
else:
steering_status_active = CC.enabled
if ((self.CP.carFingerprint == CAR.KIA_CARNIVAL_2025 and self.CP.safetyConfigs[-1].safetyParam == 0x28B4) or
@@ -552,17 +580,29 @@ 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,
stock_lfa=stock_lfa, stock_lfa_faults=stock_faults,
stock_lfa_owned_status=stock_owned_status,
stock_lkas_damping=(damping_source.current_damping(clock_boot_ns())
if damping_source is not None else None)))
if _projection is not None:
_projection.emit('hyundai.CANFD_TORQUE', apply_torque, apply_steer_req, can_sends[-1])
kona_handoff = (self.CP.carFingerprint == CAR.HYUNDAI_KONA_2ND_GEN and
self.CP.safetyConfigs[-1].safetyParam == KONA_IDLE_AOL_WORD)
lfa_counter = None
if kona_handoff:
if (CC.enabled or CC.latActive) and stock_lfa is not None:
if stock_lfa[2] != self.kona_last_lfa_counter:
lfa_counter = stock_lfa[2]
self.kona_last_lfa_counter = lfa_counter
else:
self.kona_last_lfa_counter = None
if not kona_handoff or lfa_counter is not None:
can_sends.extend(hyundaicanfd.create_steering_messages(self.packer, self.CP, self.CAN,
steering_status_active, apply_steer_req, apply_torque,
stock_lfa=stock_lfa, stock_lfa_faults=stock_faults,
stock_lfa_owned_status=stock_owned_status,
stock_lkas_damping=(damping_source.current_damping(clock_boot_ns())
if damping_source is not None else None),
lfa_counter=lfa_counter))
if _projection is not None:
_projection.emit('hyundai.CANFD_TORQUE', apply_torque, apply_steer_req, can_sends[-1])
# prevent LFA from activating on LKA steering cars by sending "no lane lines detected" to ADAS ECU
if (
@@ -150,6 +150,7 @@ class CarState(CarStateBase):
self.params = CarControllerParams(CP)
self.blended_camera_current = False
self.blended_camera_updated = False
self.ray_pedal_valid = False
self.ray_pedal_state = 5
@@ -347,6 +348,7 @@ class CarState(CarStateBase):
self.lfa_block_msg = copy.copy(cp_cam.vl["CAM_0x2a4"])
from opendbc.car.hyundai.blended_stock_aol import camera_current
self.blended_camera_current = camera_current(cp_cam)
self.blended_camera_updated = bool(cp_cam.vl_all["CAM_0x2a4"]["COUNTER"])
self.lkas11 = {}
else:
self.msg_364 = copy.copy(cp_cam.vl["ALERTS_364"])
+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,
@@ -45,7 +45,7 @@ LFA_FAULT_MASK = bytes.fromhex("00000000c001c0f00000000000000000")
def create_steering_messages(packer, CP, CAN, enabled, lat_active, apply_torque, *, stock_lfa=None, stock_lfa_faults=None,
stock_lkas_damping=None, stock_lfa_owned_status=False):
stock_lkas_damping=None, stock_lfa_owned_status=False, lfa_counter=None):
values = {
"LKA_OptUsmSta": 2,
"LKA_SysIndReq": 2 if enabled else 1,
@@ -73,6 +73,8 @@ def create_steering_messages(packer, CP, CAN, enabled, lat_active, apply_torque,
lkas_values = {**values, "Damping_Gain": damping}
ret.append(packer.make_can_msg(lkas_msg, CAN.ACAN, lkas_values))
else:
if lfa_counter is not None:
values["COUNTER"] = lfa_counter
message = packer.make_can_msg("LFA", CAN.ECAN, values)
source = stock_lfa if stock_lfa is not None else stock_lfa_faults
if source is not None:
@@ -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
@@ -67,7 +67,10 @@ class TestBlendedSender(unittest.TestCase):
command.actuators.longControlState = structs.CarControl.Actuators.LongControlState.pid
command.hudControl.setSpeed = 25.0
for frame in range(32):
actuators, messages = ci.apply(command.as_reader(), 2_000_000_000 + frame * 10_000_000)
tick = 16 + frame
camera = 16 + frame // 5 if frame % 5 == 0 else False
feed(ci, tick, camera=camera)
actuators, messages = ci.apply(command.as_reader(), 1_000_000_000 + tick * 10_000_000)
wanted = []
if frame % 100 == 0:
wanted.append((0x730 if hdaii else 0x7D0, int(hdaii)))
@@ -90,6 +93,8 @@ class TestBlendedSender(unittest.TestCase):
wanted.append((0x485, 1))
self.assertEqual([(address, bus) for address, _, bus in messages], wanted)
packets = {address: data for address, data, _ in messages}
if hdaii and frame % 5 == 0:
self.assertEqual(decode(ci, 0x2A4, packets[0x2A4], 'COUNTER'), camera)
for address, data, _ in messages:
if address not in (0x730, 0x7D0, 0x50, 0x51, 0x2A4):
self.assertEqual(data[0], hyundai_checksum(data[1:8]), hex(address))
@@ -256,7 +256,7 @@ def test_ae0_physical_tracker_is_inactive_until_final_ae32(hda2):
@pytest.mark.parametrize('hda2', (False, True))
@pytest.mark.parametrize('corruption', ('crc', 'replay', 'wrong_bus', 'inactive'))
def test_real_controller_invalid_replacement_does_not_acquire_forwarding(hda2, corruption):
def test_real_controller_forwarding_requires_valid_replacement(hda2, corruption):
cp = params(hda2)
cp.alternativeExperience = 32
ci = CarInterface(cp)
@@ -295,7 +295,14 @@ def test_real_controller_invalid_replacement_does_not_acquire_forwarding(hda2, c
elif corruption == 'wrong_bus':
assert not safety.safety_tx_hook(libsafety_py.make_CANPacket(addr, 1, data))
else:
assert safety.safety_fwd_hook(2, addr) == 0
if hda2:
assert ((data[6] & 0x1F) << 7 | data[5] >> 1) == 1024
assert safety.safety_tx_hook(libsafety_py.make_CANPacket(addr, bus, data))
if hda2:
assert safety.safety_fwd_hook(2, addr) == -1
assert safety.safety_fwd_hook(2, 0x2A4) == 0
safety.set_timer(((now // 1000) + 200_001) & 0xFFFFFFFF)
assert safety.safety_fwd_hook(2, addr) == 0
@@ -347,7 +354,11 @@ def test_real_controller_crc_fault_revokes_token_then_fresh_gesture_recovers(hda
assert permission == 0 and not accepted
assert safety.safety_fwd_hook(2, addr) == 0
if 80 <= tick < 100:
assert permission == 0 and safety.safety_fwd_hook(2, addr) == 0
assert permission == 0
if hda2:
assert accepted and ((data[6] & 0x1F) << 7 | data[5] >> 1) == 1024
assert safety.safety_fwd_hook(2, 0x2A4) == 0
assert safety.safety_fwd_hook(2, addr) == (-1 if hda2 else 0)
if tick >= 115:
assert permission == 1 and accepted
assert safety.safety_fwd_hook(2, addr) == -1
@@ -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
@@ -1,5 +1,6 @@
import os
from unittest.mock import Mock, patch
from types import SimpleNamespace
import pytest
@@ -8,7 +9,7 @@ from opendbc.car.hyundai.canfd_owner import config_index
from opendbc.car.hyundai.canfd_stock_aol import qualified_long
from opendbc.car.hyundai.interface import CarInterface
from opendbc.car.hyundai.values import CAR, HyundaiFlags
from openpilot.starpilot.car.hyundai.aol import independent_cruise_buttons_supported, native_accepts_cp, policy_for
from openpilot.starpilot.car.hyundai.aol import configure_kona_factory_handoff, independent_cruise_buttons_supported, native_accepts_cp, policy_for
CARS = (CAR.HYUNDAI_KONA_2ND_GEN, CAR.HYUNDAI_KONA_HEV_2ND_GEN)
@@ -37,9 +38,10 @@ def test_factory_ccnc_alpha_admits_only_matching_owner(car, alternate, offset):
assert qualified_long(cp) and independent_cruise_buttons_supported(cp)
policy = policy_for(cp)
assert policy.intent_supported and policy.runtime_supported and policy.explicit_latch
assert policy.safety_param_addition == 0x800 and policy.alternative_experience_addition == 32
expected = 0x800
assert policy.safety_param_addition == expected and policy.alternative_experience_addition == 32
assert cp.to_dict() == original
word = int(cp.safetyConfigs[-1].safetyParam) | 0x800
word = int(cp.safetyConfigs[-1].safetyParam) | expected
cp.safetyConfigs[-1].safetyParam = word
cp.alternativeExperience = 32
assert qualified_long(cp, marked_only=True)
@@ -199,3 +201,38 @@ def test_wheel_choices_keep_aol_with_either_longitudinal_owner(car, alternate, a
feature = WheelFeature(Owner())
assert 'Toggle AOL' in feature.choices('LKASButtonControl')
assert 'Toggle AOL' in feature.choices('MainCruiseButtonControl')
def test_idle_handoff_omits_only_kona_steering_packet():
reference_cp = kona_params(CARS[0])
handoff_cp = kona_params(CARS[0])
for cp, word in ((reference_cp, 0x0C0C), (handoff_cp, 0x1C0C)):
cp.safetyConfigs[0].safetyParam = word
cp.alternativeExperience = 32
reference, candidate = CarInterface(reference_cp), CarInterface(handoff_cp)
source = Mock()
source.owns_display_status.return_value = False
candidate.CS.stock_lfa_status = source
states = ((False, False, 10), (True, True, 11), (False, True, 11), (True, False, 12),
(True, True, None), (False, False, 13), (True, True, 14))
expected_counters = (None, 11, None, 12, None, None, 14)
for (enabled, lateral, camera_counter), expected in zip(states, expected_counters, strict=True):
if camera_counter is None:
source.current.return_value = None
else:
source.current.return_value = bytes([0, 0, camera_counter] + [0] * 13)
ctrl = structs.CarControl(enabled=enabled, latActive=lateral).as_reader()
_, before = reference.apply(ctrl, 1_000_000_000)
_, after = candidate.apply(ctrl, 1_000_000_000)
assert [frame for frame in after if frame[0] != 0x12A] == [frame for frame in before if frame[0] != 0x12A]
assert any(frame[0] == 0x12A for frame in before)
assert [data[2] for addr, data, _ in after if addr == 0x12A] == ([] if expected is None else [expected])
@pytest.mark.parametrize('panda_type,faults,expected', [('cuatro', [], 0x1C0C), ('redPanda', [], 0x0C0C), ('cuatro', ['fault'], 0x0C0C)])
def test_kona_factory_handoff_is_limited_to_healthy_internal_c4(panda_type, faults, expected):
cp = kona_params(CARS[0])
cp.alternativeExperience = 32
cp.safetyConfigs[0].safetyParam = 0x0C0C
panda = SimpleNamespace(pandaType=panda_type, faults=faults, ignitionLine=True, ignitionCan=False, controlsAllowed=False)
configure_kona_factory_handoff(cp, [panda])
assert cp.safetyConfigs[0].safetyParam == expected
@@ -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()
@@ -23,13 +23,17 @@ def params(topology='hdai', *, adas=False, alpha=False, release=False):
return CarInterface.get_params(CAR.HYUNDAI_PALISADE_2023, fp, fw, alpha, release, False)
def feed(ci, tick, *, main=True, cruise=1, display=0, gas=False, brake=False, torque=0):
def feed(ci, tick, *, main=True, cruise=1, display=0, gas=False, brake=False, torque=0, camera=True):
packer = CANPacker(DBC[ci.CP.carFingerprint][Bus.pt])
messages = []
for parser in ci.can_parsers.values():
for address in parser.addresses:
if address == 0x2A4 and camera is False:
continue
message = parser.dbc.addr_to_msg[address]
values = {'COUNTER': tick % 16} if 'COUNTER' in message.sigs else {}
if address == 0x2A4 and type(camera) is int:
values['COUNTER'] = camera
if message.name == 'SCC12':
values.update(MainMode_ACC=int(main), ACCMode=cruise, SCCInfoDisplay=display, VSetDis=90)
elif message.name == 'EMS16':
@@ -100,13 +104,14 @@ class TestPalisade2023(unittest.TestCase):
command.hudControl.setSpeed = 25.
previous = 0
for tick in range(20):
feed(ci, tick + 12, camera=12 + (tick + 3) // 5 if tick == 0 or tick % 5 == 2 else False)
actuators, messages = ci.apply(command.as_reader(), 1_200_000_000 + tick * 10_000_000)
self.assertEqual(actuators.torqueOutputCan - previous, 3 if topology == 'hdaii' else 2)
previous = actuators.torqueOutputCan
addresses = {a for a, _, _ in messages}
self.assertFalse(addresses & {0x420, 0x421, 0x389, 0x7D0, 0x730})
if topology == 'hdaii':
self.assertEqual(addresses, {0x50, 0x2A4} if tick % 5 == 0 else {0x50})
self.assertEqual(addresses, {0x50, 0x2A4} if tick in (0, 7, 12, 17) else {0x50})
self.assertTrue(all(bus == 0 for _, _, bus in messages))
else:
self.assertEqual(addresses, {0x340, 0x364})
@@ -123,6 +128,37 @@ class TestPalisade2023(unittest.TestCase):
actuators, _ = ci.apply(command.as_reader(), 1_500_000_000)
self.assertEqual(actuators.torqueOutputCan, 0)
def test_hda2_camera_copy_skips_samples_that_miss_the_send_slot(self):
ci = CarInterface(params('hdaii'))
for tick in range(12):
feed(ci, tick)
command = structs.CarControl(enabled=True, latActive=True)
copied = []
for frame in range(20):
tick = frame + 12
feed(ci, tick, camera={0: 12, 4: 13, 9: 14, 14: 15, 19: 16}.get(frame, False))
_, messages = ci.apply(command.as_reader(), 1_000_000_000 + tick * 10_000_000)
copied.extend((frame, data[2]) for address, data, _ in messages if address == 0x2A4)
self.assertEqual(copied, [(0, 12), (9, 14), (14, 15), (19, 16)])
def test_hda2_alpha_long_keeps_primary_steering_payload(self):
from opendbc.car.hyundai.blended_longitudinal import candidate_from_stock
stock = params('hdaii')
alpha = candidate_from_stock(stock, alpha_requested=True, native_qualified=True)
self.assertTrue(alpha.openpilotLongitudinalControl)
interfaces = [CarInterface(cp) for cp in (stock, alpha)]
command = structs.CarControl(enabled=True, latActive=True)
command.actuators.torque = .25
for tick in range(12):
steering = []
for ci in interfaces:
feed(ci, tick)
_, messages = ci.apply(command.as_reader(), 1_000_000_000 + tick * 10_000_000)
steering.append(next((data, bus) for address, data, bus in messages if address == 0x50))
self.assertEqual(steering[0], steering[1])
self.assertEqual(steering[0][0][8], 0)
def test_cancel_resume_route_to_exact_pt_bus_and_sibling_params_unchanged(self):
for topology in ('hdai', 'hdaii'):
ci = CarInterface(params(topology))
@@ -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
+25 -11
View File
@@ -1,4 +1,4 @@
"""One bounded Legacy AVH ON request; 0x32B is status, never a TX command."""
"""One bounded Subaru AVH ON request; 0x32B is status, never a TX command."""
AVH_REQUEST = 0x6BB
AVH_STATUS = 0x32B
@@ -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,31 +109,37 @@ 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)]
def eligible(cp):
from opendbc.car.subaru.startup import supported
return bool(supported(cp) and cp.carFingerprint == 'SUBARU_LEGACY_2025')
from opendbc.car.subaru.stock_aol import qualified
from opendbc.car.subaru.values import CAR, FROGGER_ANGLE_SIBLINGS
return bool(qualified(cp) and cp.carFingerprint in FROGGER_ANGLE_SIBLINGS | {CAR.SUBARU_LEGACY_2025})
def selected(cp):
from opendbc.car.subaru.values import SubaruFlags
return bool(eligible(cp) and cp.flags & SubaruFlags.AVH_STARTUP and cp.safetyConfigs[0].safetyParam in (1169, 1425))
return bool(eligible(cp) and cp.flags & SubaruFlags.AVH_STARTUP and cp.safetyConfigs[0].safetyParam in (1041, 1169, 1425, 3089))
def prepare(cp, enabled):
@@ -143,6 +154,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 +175,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):
+164 -26
View File
@@ -8,7 +8,7 @@ from opendbc.car.interfaces import CarControllerBase
from opendbc.car.subaru import subarucan
from opendbc.car.subaru.jacobw_angle import MAX_ANGLE as JACOBW_MAX_ANGLE, filter_angle as jacobw_filter_angle, limit_angle as jacobw_limit_angle
from opendbc.car.subaru.stock_aol import qualified as subaru_aol_qualified
from opendbc.car.subaru.values import CAR, DBC, GLOBAL_ES_ADDR, CanBus, CarControllerParams, SubaruFlags
from opendbc.car.subaru.values import CAR, FROGGER_ANGLE_SIBLINGS, DBC, GLOBAL_ES_ADDR, CanBus, CarControllerParams, SubaruFlags
from opendbc.car.vehicle_model import VehicleModel
# FIXME: These limits aren't exact. The real limit is more than likely over a larger time period and
@@ -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,73 @@ 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 FROGGER_ANGLE_SIBLINGS | {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)
frogger_hud = self.CP.carFingerprint != CAR.SUBARU_ASCENT_2023
lateral_active = self.angle_was_active and CC.latActive and (
CC.enabled or subaru_aol_qualified(self.CP, marked_only=True)
)
if frogger_hud:
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 +193,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 in FROGGER_ANGLE_SIBLINGS | {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 +307,20 @@ class CarController(CarControllerBase):
can_sends.extend(send_sng(self, CC, CS, now_nanos))
# *** alerts and pcm cancel ***
frogger_hud = self.CP.carFingerprint in FROGGER_ANGLE_SIBLINGS | {CAR.SUBARU_LEGACY_2025}
enabled_for_dash_2025 = self.angle_was_active
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 +343,54 @@ 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 frogger_hud:
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))
if self.CP.carFingerprint in FROGGER_ANGLE_SIBLINGS:
aol_enabled = aol_enabled and subaru_aol_qualified(self.CP, marked_only=True)
wheel_ready = bool(cruise_available and aol_enabled)
lanes_visible = hud_control.lanesVisible or (
self.CP.carFingerprint in FROGGER_ANGLE_SIBLINGS and self.angle_was_active)
if not (in_drive and cruise_available) or lateral_off or not lanes_visible:
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 frogger_hud:
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 +404,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
+83 -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,14 @@ 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_IMPREZA_2020 and self.shifter_values.get(can_gear) in ("1", "2", "3", "4", "5", "6"):
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 +139,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 +155,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 +188,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 +258,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"])
+9 -4
View File
@@ -5,7 +5,7 @@ from opendbc.car.disable_ecu import disable_ecu
from opendbc.car.interfaces import CarInterfaceBase
from opendbc.car.subaru.carcontroller import CarController
from opendbc.car.subaru.carstate import CarState
from opendbc.car.subaru.values import CAR, GLOBAL_ES_ADDR, CanBus, SubaruFlags, SubaruSafetyFlags
from opendbc.car.subaru.values import CAR, FROGGER_ANGLE_SIBLINGS, EARLY_GLOBAL_TORQUE_CARS, GLOBAL_ES_ADDR, CanBus, SubaruFlags, SubaruSafetyFlags
GEN2_ANGLE_PORTS = frozenset((CAR.SUBARU_CROSSTREK_2025, CAR.SUBARU_IMPREZA_2025, CAR.SUBARU_LEGACY_2025,
CAR.SUBARU_ASCENT_2023, CAR.SUBARU_FORESTER_2022, CAR.SUBARU_OUTBACK_2023))
@@ -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 FROGGER_ANGLE_SIBLINGS | {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:
@@ -75,6 +76,8 @@ class CarInterface(CarInterfaceBase):
ret.safetyConfigs[0].safetyParam |= SubaruSafetyFlags.LKAS_ANGLE.value
if candidate in (CAR.SUBARU_LEGACY_2025, CAR.SUBARU_ASCENT_2023, CAR.SUBARU_OUTBACK_2023):
ret.safetyConfigs[0].safetyParam |= SubaruSafetyFlags.FIXED_ANGLE_LIMITS.value
if candidate in FROGGER_ANGLE_SIBLINGS and ret.flags & SubaruFlags.ASCENT_LKAS_ALERT:
ret.safetyConfigs[0].safetyParam |= SubaruSafetyFlags.ASCENT_LKAS_ALERT.value
if candidate == CAR.SUBARU_OUTBACK_2023:
ret.safetyConfigs[0].safetyParam |= SubaruSafetyFlags.D_PLATFORM.value
if candidate == CAR.SUBARU_ASCENT_2023:
@@ -98,7 +101,8 @@ class CarInterface(CarInterfaceBase):
ret.lateralTuning.pid.kiBP, ret.lateralTuning.pid.kpBP = [[0., 20.], [0., 20.]]
ret.lateralTuning.pid.kpV, ret.lateralTuning.pid.kiV = [[0.0025, 0.1], [0.00025, 0.01]]
elif candidate == CAR.SUBARU_IMPREZA:
elif candidate in EARLY_GLOBAL_TORQUE_CARS:
ret.safetyConfigs[0].safetyParam = SubaruSafetyFlags.EARLY_GLOBAL_TORQUE.value
ret.steerActuatorDelay = 0.4 # end-to-end angle controller
ret.lateralTuning.init('pid')
ret.lateralTuning.pid.kf = 0.00005
@@ -131,7 +135,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}")
+4 -2
View File
@@ -2,10 +2,10 @@
from opendbc.car import structs
from opendbc.car.subaru.stock_aol import IMPREZA_MAIN_AOL
from opendbc.car.subaru.values import CAR, SubaruFlags
from opendbc.car.subaru.values import CAR, EARLY_GLOBAL_TORQUE_CARS, SubaruFlags, SubaruSafetyFlags
STOP_AND_GO = 8
SUPPORTED = frozenset((CAR.SUBARU_ASCENT, CAR.SUBARU_IMPREZA, CAR.SUBARU_IMPREZA_2020, CAR.SUBARU_FORESTER))
SUPPORTED = EARLY_GLOBAL_TORQUE_CARS | {CAR.SUBARU_ASCENT, CAR.SUBARU_IMPREZA_2020, CAR.SUBARU_FORESTER}
def eligible(cp):
@@ -16,6 +16,8 @@ def eligible(cp):
return False
word &= ~IMPREZA_MAIN_AOL
words = (0, 8, 512, 520) if cp.carFingerprint == CAR.SUBARU_IMPREZA_2020 else (0, 8)
if cp.carFingerprint in EARLY_GLOBAL_TORQUE_CARS:
words = (SubaruSafetyFlags.EARLY_GLOBAL_TORQUE, SubaruSafetyFlags.EARLY_GLOBAL_TORQUE | STOP_AND_GO)
return bool(
cp.brand == 'subaru'
and cp.carFingerprint in SUPPORTED
+18 -5
View File
@@ -1,11 +1,11 @@
"""Exact stock-cruise Subaru independent-lateral configuration contract."""
from opendbc.car import structs
from opendbc.car.subaru.values import CAR, SubaruFlags, SubaruSafetyFlags
from opendbc.car.subaru.values import CAR, FROGGER_ANGLE_SIBLINGS, EARLY_GLOBAL_TORQUE_CARS, SubaruFlags, SubaruSafetyFlags
AOL_EXPERIENCE = 32
IMPREZA_MAIN_AOL = 4096
TORQUE_CARS = frozenset((CAR.SUBARU_ASCENT, CAR.SUBARU_OUTBACK, CAR.SUBARU_LEGACY,
CAR.SUBARU_IMPREZA, CAR.SUBARU_IMPREZA_2020, CAR.SUBARU_FORESTER))
CAR.SUBARU_IMPREZA, CAR.SUBARU_IMPREZA_2020, CAR.SUBARU_FORESTER, CAR.SUBARU_CROSSTREK_2018))
ANGLE_CARS = frozenset((CAR.SUBARU_CROSSTREK_2025, CAR.SUBARU_IMPREZA_2025, CAR.SUBARU_LEGACY_2025,
CAR.SUBARU_ASCENT_2023, CAR.SUBARU_FORESTER_2022, CAR.SUBARU_OUTBACK_2023))
@@ -24,17 +24,25 @@ def qualified(cp, *, marked_only=False):
static = int(CAR[cp.carFingerprint].config.flags)
allowed = int(SubaruFlags.HAS_BSM | SubaruFlags.SEND_INFOTAINMENT | SubaruFlags.SMOOTHING_BOUND)
expected = int(SubaruSafetyFlags.GEN2) if static & SubaruFlags.GLOBAL_GEN2 else 0
if cp.carFingerprint in EARLY_GLOBAL_TORQUE_CARS:
expected |= int(SubaruSafetyFlags.EARLY_GLOBAL_TORQUE) | (word & 8)
if cp.carFingerprint == CAR.SUBARU_OUTBACK_2023:
expected |= int(SubaruSafetyFlags.D_PLATFORM)
allowed |= int(SubaruFlags.STOP_START_OFF)
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:
expected |= int(SubaruSafetyFlags.STOP_START_BUTTON)
if cp.carFingerprint in FROGGER_ANGLE_SIBLINGS:
allowed |= int(SubaruFlags.AVH_STARTUP | SubaruFlags.ASCENT_LKAS_ALERT)
if cp.flags & SubaruFlags.AVH_STARTUP:
expected |= int(SubaruSafetyFlags.AVH_STARTUP)
if cp.flags & SubaruFlags.ASCENT_LKAS_ALERT:
expected |= int(SubaruSafetyFlags.ASCENT_LKAS_ALERT)
angle = cp.carFingerprint in ANGLE_CARS
if angle:
expected |= int(SubaruSafetyFlags.LKAS_ANGLE)
@@ -50,7 +58,7 @@ def qualified(cp, *, marked_only=False):
return False
if cp.carFingerprint == CAR.SUBARU_IMPREZA_2020 and word == 512:
expected |= 512
if cp.carFingerprint in (CAR.SUBARU_ASCENT, CAR.SUBARU_IMPREZA, CAR.SUBARU_IMPREZA_2020, CAR.SUBARU_FORESTER) and word in (8, 520):
if cp.carFingerprint in (CAR.SUBARU_ASCENT, CAR.SUBARU_IMPREZA_2020, CAR.SUBARU_FORESTER) and word in (8, 520):
expected |= 8
if cp.carFingerprint == CAR.SUBARU_IMPREZA_2020:
expected |= word & 512
@@ -59,6 +67,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)
@@ -4,7 +4,7 @@ from opendbc.car import structs
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.values import CAR, DBC, SubaruFlags, SubaruSafetyFlags
from opendbc.car.subaru.values import CAR, DBC, FROGGER_ANGLE_SIBLINGS, SubaruFlags, SubaruSafetyFlags
from opendbc.car.subaru import subarucan
from opendbc.safety.tests.test_subaru_gen2_angle_pair import TestSubaruGen2AnglePair
@@ -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.safetyConfigs[0].safetyParam & SubaruSafetyFlags.ASCENT_LKAS_ALERT), car == CAR.SUBARU_ASCENT_2023)
self.assertEqual(bool(cp.flags & SubaruFlags.ASCENT_LKAS_ALERT), car in FROGGER_ANGLE_SIBLINGS | {CAR.SUBARU_ASCENT_2023, CAR.SUBARU_LEGACY_2025})
self.assertEqual(bool(cp.safetyConfigs[0].safetyParam & SubaruSafetyFlags.ASCENT_LKAS_ALERT), car in FROGGER_ANGLE_SIBLINGS | {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
@@ -145,9 +145,10 @@ def test_hackathon_filter_updates_at_control_rate(speed, tau):
assert not any(frame[0] == 0x124 for frame in odd_sends)
assert controller.angle_filter.x == pytest.approx(.1 * (1. - (1. - alpha) ** 2))
command.latActive = False
state.out.steeringAngleDeg = .3
command.actuators.steeringAngleDeg = -.2
controller.update(command.as_reader(), state, 1_020_000_000)
assert controller.angle_filter.x == command.actuators.steeringAngleDeg
assert controller.angle_filter.x == state.out.steeringAngleDeg
def test_hackathon_geometry_is_scoped_and_native_bound_remains_strict():
@@ -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()
@@ -7,7 +7,7 @@ from opendbc.car import Bus, structs
from opendbc.car.subaru import subarucan
from opendbc.car.subaru.stock_aol import ANGLE_CARS, TORQUE_CARS
from opendbc.car.subaru.tests.test_ascent_angle import setup_controller, step
from opendbc.car.subaru.values import CAR, DBC, SubaruSafetyFlags
from opendbc.car.subaru.values import CAR, DBC, FROGGER_ANGLE_SIBLINGS, SubaruSafetyFlags
from opendbc.safety.tests import test_subaru_gen2_angle_pair as pair
from opendbc.safety.tests.libsafety import libsafety_py
@@ -71,9 +71,16 @@ 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))
elif car in FROGGER_ANGLE_SIBLINGS:
assert bool(dash['LKAS_ACTIVE'])
assert dash['LKAS_Dash_State'] == (2 if expected else (1 if marked and 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
@@ -69,6 +69,19 @@ class TestSupportedSubaruFirmware(unittest.TestCase):
self.assertTrue(cp.pcmCruise)
self.assertEqual(cp.safetyConfigs[0].safetyParam, word)
def test_early_crosstrek_shares_firmware_but_has_distinct_vehicle_params(self):
platform = CAR.SUBARU_CROSSTREK_2018
self.assertNotIn(platform, FW_VERSIONS)
shared = FW_VERSIONS[CAR.SUBARU_IMPREZA]
live = {(address, sub): {versions[0]} for (_, address, sub), versions in shared.items()}
self.assertEqual(match_fw_to_car_exact(live, match_brand='subaru', log=False), {CAR.SUBARU_IMPREZA})
for release in (False, True):
cp = CarInterface.get_params(platform, {0: {}, 1: {}, 2: {}}, [], False, release, False)
self.assertEqual(cp.carFingerprint, platform)
self.assertFalse(cp.dashcamOnly)
self.assertTrue(cp.pcmCruise)
self.assertFalse(cp.openpilotLongitudinalControl or cp.alphaLongitudinalAvailable)
def test_three_byte_diagnostic_response_is_not_a_camera_identity(self):
for platform in (CAR.SUBARU_ASCENT_2023, CAR.SUBARU_LEGACY_2025):
for versions in FW_VERSIONS[platform].values():
+15
View File
@@ -37,6 +37,8 @@ class CarControllerParams:
self.STEER_MAX = 1000
self.STEER_DELTA_UP = 40
self.STEER_DELTA_DOWN = 40
elif CP.carFingerprint in EARLY_GLOBAL_TORQUE_CARS:
self.STEER_MAX = 3071
elif CP.carFingerprint == CAR.SUBARU_IMPREZA_2020:
self.STEER_DELTA_UP = 35
self.STEER_MAX = 1439
@@ -71,6 +73,8 @@ class SubaruSafetyFlags(IntFlag):
GEN2 = 1
LONG = 2
PREGLOBAL_REVERSED_DRIVER_TORQUE = 4
EARLY_GLOBAL_TORQUE = 8192
PREGLOBAL_OUTBACK_STOCK_ACC = 8
LKAS_ANGLE = 16
D_PLATFORM = 64
FIXED_ANGLE_LIMITS = 128
@@ -167,6 +171,11 @@ class CAR(Platforms):
SUBARU_IMPREZA = SubaruPlatformConfig(
[
SubaruCarDocs("Subaru Impreza 2017-19"),
],
CarSpecs(mass=1568, wheelbase=2.67, steerRatio=15),
)
SUBARU_CROSSTREK_2018 = SubaruPlatformConfig(
[
SubaruCarDocs("Subaru Crosstrek 2018-19", video="https://youtu.be/Agww7oE1k-s?t=26"),
SubaruCarDocs("Subaru XV 2018-19", video="https://youtu.be/Agww7oE1k-s?t=26"),
],
@@ -268,6 +277,12 @@ SUBARU_ALT_VERSION_REQUEST = bytes([uds.SERVICE_TYPE.READ_DATA_BY_IDENTIFIER]) +
SUBARU_ALT_VERSION_RESPONSE = bytes([uds.SERVICE_TYPE.READ_DATA_BY_IDENTIFIER + 0x40]) + \
p16(0xf100)
EARLY_GLOBAL_TORQUE_CARS = frozenset((CAR.SUBARU_IMPREZA, CAR.SUBARU_CROSSTREK_2018))
FROGGER_ANGLE_SIBLINGS = frozenset((CAR.SUBARU_IMPREZA_2025, CAR.SUBARU_CROSSTREK_2025))
FW_QUERY_CONFIG = FwQueryConfig(
validate_fw_match=validate_fw_match,
fw_version_regex=br"(?:[\x00-\xff]{4,5}|[\x00-\xff]{8}|[\x00-\xff]{10})",
@@ -1,3 +1,4 @@
import time
import numpy as np
from opendbc.car import ACCEL_MAX_TAKEOFF
from opendbc.can import CANPacker
@@ -10,6 +11,7 @@ from opendbc.car.tesla.hw1 import HW1CarController
from opendbc.car.tesla.values import CAR, CarControllerParams, TeslaSafetyFlags
from opendbc.car.tesla.coop_steering import CooperativeSteeringController
from opendbc.car.vehicle_model import VehicleModel
from opendbc.car.tesla.speed_sync import SpeedSynchronizer, selected as speed_sync_selected, sync_controller
def get_safety_CP():
@@ -22,6 +24,7 @@ def get_safety_CP():
class CarController(CarControllerBase):
def __init__(self, dbc_names, CP):
super().__init__(dbc_names, CP)
self.speed_sync = SpeedSynchronizer() if speed_sync_selected(CP) else None
if CP.carFingerprint == CAR.TESLA_MODEL_S_PREAP:
self.preap = PreAPStockCarController(dbc_names, CP)
return
@@ -91,6 +94,10 @@ class CarController(CarControllerBase):
cntr = (CS.das_control["DAS_controlCounter"] + 1) % 8
can_sends.append(self.tesla_can.create_longitudinal_command(13, 0, cntr, CS.out.vEgo, False))
# Speed sync: append-only mirror; never changes the selected target or actuators.
if self.speed_sync is not None:
can_sends.extend(sync_controller(self, CC, CS, time.clock_gettime_ns(time.CLOCK_BOOTTIME)))
# TODO: HUD control
new_actuators = actuators.as_builder()
new_actuators.steeringAngleDeg = getattr(self, "command_angle", self.apply_angle_last)
@@ -1,4 +1,6 @@
import copy
from opendbc.car.dashboard_speed_limit import Tracker as LimitTracker
from opendbc.car.tesla.speed_limit import update_dashboard_limit
from opendbc.can import CANDefine, CANParser
from opendbc.car import Bus, create_button_events, structs
from opendbc.car.common.conversions import Conversions as CV
@@ -32,6 +34,7 @@ class CarState(CarStateBase):
self.hands_on_level = 0
self.das_control = {}
return
self.dashboard_limit = LimitTracker()
self.cooperative_steering = (CP.carFingerprint in (CAR.TESLA_MODEL_3, CAR.TESLA_MODEL_Y) and
bool(CP.safetyConfigs[0].safetyParam & TeslaSafetyFlags.COOP_STEERING))
self.can_define = CANDefine(DBC[CP.carFingerprint][Bus.party])
@@ -160,6 +163,9 @@ class CarState(CarStateBase):
# Buttons # ToDo: add Gap adjust button
if self.CP.carFingerprint in (CAR.TESLA_MODEL_3, CAR.TESLA_MODEL_Y):
update_dashboard_limit(self.dashboard_limit, cp_party, cp_ap_party, speed_units)
# Messages needed by carcontroller
self.das_control = copy.copy(cp_ap_party.vl["DAS_control"])
@@ -13,6 +13,11 @@ class CarInterface(CarInterfaceBase):
CarController = CarController
RadarInterface = RadarInterface
def update(self, can_packets):
if self.CC is not None and self.CC.speed_sync is not None:
self.CC.speed_sync.observe(can_packets)
return super().update(can_packets)
@staticmethod
def _get_params(ret: structs.CarParams, candidate, fingerprint, car_fw, alpha_long, is_release, docs) -> structs.CarParams:
ret.brand = "tesla"
@@ -1,10 +1,20 @@
"""Exact modern Tesla screen harness capability and frozen safety selection."""
from opendbc.car.tesla.values import CAR, TeslaFlags
from opendbc.car.tesla.values import CAR, TeslaFlags, TeslaSafetyFlags
SCREEN_WORDS = frozenset((512, 513, 1536, 1537, 768, 769, 1792, 1793))
BASE_WORDS = frozenset((0, 1, 256, 257))
ORDINARY_WORDS = frozenset((2048, 2049, 2304, 2305, 3072, 3073, 3328, 3329))
AOL_WORDS = SCREEN_WORDS | ORDINARY_WORDS
SPEED_SYNC = int(TeslaSafetyFlags.SCROLL_SPEED_SYNC)
# Exact native tesla_sync_param_valid words: scroll speed sync (4096) on a word that carries LONG_CONTROL.
SYNC_WORDS = frozenset(SPEED_SYNC | word for word in (1, 257, 513, 769, 1537, 1793, 2049, 2305, 3073, 3329))
KNOWN_FLAGS = int(TeslaFlags.MISSING_DAS_SETTINGS | TeslaFlags.HAS_VEHICLE_BUS | TeslaFlags.AOL_SCREEN_BUTTON)
def speed_sync_allowed(cp, word):
return bool(word in SYNC_WORDS and cp.carFingerprint in (CAR.TESLA_MODEL_3, CAR.TESLA_MODEL_Y) and cp.openpilotLongitudinalControl and
cp.flags & TeslaFlags.HAS_VEHICLE_BUS and not cp.flags & ~KNOWN_FLAGS and
bool(word & 512) == bool(cp.flags & TeslaFlags.AOL_SCREEN_BUTTON))
def modern_aol_supported(cp):
@@ -12,9 +22,13 @@ def modern_aol_supported(cp):
if (cp.brand != 'tesla' or cp.carFingerprint not in (CAR.TESLA_MODEL_3, CAR.TESLA_MODEL_Y) or
cp.passive or cp.dashcamOnly or cp.notCar or cp.alternativeExperience not in (0, 32) or len(cp.safetyConfigs) != 1 or
int(cp.safetyConfigs[0].safetyModel.raw) != 10 or
cp.flags & ~int(TeslaFlags.MISSING_DAS_SETTINGS | TeslaFlags.HAS_VEHICLE_BUS | TeslaFlags.AOL_SCREEN_BUTTON)):
cp.flags & ~KNOWN_FLAGS):
return False
word = int(cp.safetyConfigs[0].safetyParam)
if word & SPEED_SYNC:
if not speed_sync_allowed(cp, word):
return False
word &= ~SPEED_SYNC
return (word in BASE_WORDS | AOL_WORDS and
bool(word & 1) == bool(cp.openpilotLongitudinalControl) and
bool(word & 512) == bool(cp.flags & TeslaFlags.AOL_SCREEN_BUTTON) and
@@ -31,12 +45,12 @@ modern_screen_supported = screen_tap_supported
def screen_qualified(cp, *, marked_only=False):
return bool(screen_tap_supported(cp) and int(cp.safetyConfigs[0].safetyParam) in SCREEN_WORDS and
return bool(screen_tap_supported(cp) and (int(cp.safetyConfigs[0].safetyParam) & ~SPEED_SYNC) in SCREEN_WORDS and
cp.alternativeExperience in ((32,) if marked_only else (0, 32)))
def modern_aol_qualified(cp, *, marked_only=False):
return bool(modern_aol_supported(cp) and int(cp.safetyConfigs[0].safetyParam) in AOL_WORDS and
return bool(modern_aol_supported(cp) and (int(cp.safetyConfigs[0].safetyParam) & ~SPEED_SYNC) in AOL_WORDS and
cp.alternativeExperience in ((32,) if marked_only else (0, 32)))
@@ -44,7 +58,7 @@ def apply_modern_aol(cp, requested, screen, brake_disengage):
if not modern_aol_supported(cp):
return
use_screen = requested and screen and screen_tap_supported(cp)
base = int(cp.safetyConfigs[0].safetyParam) & 257
base = int(cp.safetyConfigs[0].safetyParam) & (257 | SPEED_SYNC) # scroll speed sync rides on top of any AOL word
cp.flags &= ~int(TeslaFlags.AOL_SCREEN_BUTTON)
cp.safetyConfigs[0].safetyParam = base
if requested:
@@ -56,7 +70,7 @@ def apply_modern_aol(cp, requested, screen, brake_disengage):
def apply_screen_button(cp, requested, brake_disengage):
if not screen_tap_supported(cp):
return
base = int(cp.safetyConfigs[0].safetyParam) & 257
base = int(cp.safetyConfigs[0].safetyParam) & (257 | SPEED_SYNC)
cp.flags &= ~int(TeslaFlags.AOL_SCREEN_BUTTON)
cp.safetyConfigs[0].safetyParam = base
if requested:
@@ -0,0 +1,22 @@
"""Tesla fused road-limit evidence for the 7.0 Dashboard producer."""
import math
from opendbc.car.dashboard_speed_limit import Status, parser_expiry
def update_dashboard_limit(tracker, party, autopilot, speed_units):
limit_ns, limit_expiry = parser_expiry(autopilot, 'DAS_status', 'DAS_fusedSpeedLimit')
units_ns, units_expiry = parser_expiry(party, 'DI_state', 'DI_speedUnits')
stamp = max(limit_ns, units_ns)
if stamp <= tracker.observation.observed_ns:
return
status, speed = Status.UNKNOWN, 0.0
expiry = min(limit_expiry, units_expiry)
if (limit_ns > 0 and units_ns > 0 and expiry > stamp and party.can_valid and autopilot.can_valid
and speed_units in ('MPH', 'KPH')):
value = float(autopilot.vl['DAS_status']['DAS_fusedSpeedLimit'])
# The DBC scales raw31/NONE to155; raw0 is UNKNOWN, never zero mph.
if math.isfinite(value) and 0 < value <= 150:
status, speed = Status.VALID, value * (0.44704 if speed_units == 'MPH' else 1 / 3.6)
elif value == 155:
status = Status.ABSENT
tracker.update(stamp, status, speed, valid_until_ns=expiry)
@@ -0,0 +1,730 @@
"""Speed sync: one-way native selected-speed mirror for the Tesla Model 3/Y. Experimental.
No speed-control state is written here. Normal control packets are owned by the
existing controller. Only a bounded relative wheel request can be returned.
Each request is one right-wheel frame: a single click (+-1 mph), or a fast flick
(+-5 clicks) that moves the Tesla to the next multiple of 5. The Tesla only treats
a flick as fast when it starts a new gesture: a scroll soon after the previous one
moves the speed by 1. So fast steps are spaced, and the spacing
is learned. The panda decides what may be sent. A request the panda does not transmit (no bus-129 return, or a
bus-193 rejection) never reached the car, so it is cleared and retried later.
"""
from dataclasses import dataclass
from collections import deque
import math
from opendbc.car.tesla.values import TeslaFlags, TeslaSafetyFlags
SYNC_FLAG = int(TeslaSafetyFlags.SCROLL_SPEED_SYNC)
MODELS = ("TESLA_MODEL_3", "TESLA_MODEL_Y")
def eligible(cp):
"""A Model 3/Y with StarPilot longitudinal control, its own cruise and the CAN add-on cable (Vehicle CAN)."""
try:
return bool(cp.brand == "tesla" and cp.carFingerprint in MODELS and cp.openpilotLongitudinalControl and cp.pcmCruise and
not cp.passive and not cp.dashcamOnly and not cp.notCar and cp.flags & TeslaFlags.HAS_VEHICLE_BUS and
len(cp.safetyConfigs) == 1 and cp.safetyConfigs[0].safetyParam & TeslaSafetyFlags.LONG_CONTROL)
except (AttributeError, TypeError, ValueError, IndexError):
return False
def selected(cp):
"""The car started with the scroll frame admitted, so the comma may own the set speed and scroll the Tesla's to match.
Whether it does follows the saved switch (openpilot/starpilot/car/tesla/set_speed.py)."""
try:
return bool(eligible(cp) and cp.safetyConfigs[0].safetyParam & SYNC_FLAG)
except (AttributeError, TypeError, ValueError, IndexError):
return False
def prepare(cp, requested):
"""Admit the scroll frame in the car's parameters at startup (the panda sends it only with this bit)."""
if eligible(cp):
cp.safetyConfigs[0].safetyParam &= ~SYNC_FLAG
if requested:
cp.safetyConfigs[0].safetyParam |= SYNC_FLAG
return cp
NS = 1_000_000_000
FRESH_NS = 250_000_000
# No Tesla change by SETTLE_NS: the request went unanswered (the updated panda frees its own request after 0.8 s).
SETTLE_NS = 1_000_000_000
TOKENS_MAX = 30 # panda rate limit: burst of 30 requests...
TOKEN_REFILL_NS = 1_050_000_000 # ...then one per second (a little slower here so the panda never refuses)
FAST_PAUSE_NS = 2 * NS # after a refused fast step, single clicks for this long
MANUAL_COMPLETION_NS = 2 * NS
HANDOVER_NS = 100_000_000
TEMPLATE_SEND_NS = 100_000_000 # one wheel-frame period (panda allows 250 ms)
RETURN_NS = 100_000_000 # panda echoes a transmitted frame on bus 129 within ~5 ms
BACKOFF_NS = 300_000_000 # wait after a request the panda refused,
BACKOFF_MAX_NS = 2 * NS # doubling on each refusal in a row
MANUAL_SETTLE_NS = 600_000_000 # let the Tesla apply the driver's own scroll first
FAST_TICKS = 5
# Fast-step spacing. Measured: a flick 0.1-0.24 s after the previous scroll moved
# the Tesla by 1; the driver's own flicks 0.4 s apart all jumped 5. Start short and
# lengthen on each fast step that lands as a single click; shorten again after a
# run of good ones. Nothing here ever stops the sync.
FAST_GAP_NS = 280_000_000
FAST_GAP_STEP_NS = 100_000_000
FAST_GAP_MAX_NS = 800_000_000
FAST_GAP_RELAX = 30 # good fast steps in a row before trying a shorter gap
FAST_RESPONSE_NS = 250_000_000 # Tesla applies a new gesture after ~0.23 s
STREAM_STEP_NS = 100_000_000 # a click inside a gesture shows up at the next DI frame
ENGAGE_DELAY_NS = 150_000_000 # pandad tells the panda about engagement at 10 Hz
MAX_RETRIES = 3 # unanswered clicks retried at one speed before waiting
def neutral_wheel(data):
if len(data) != 8 or data[0] & 3 != 1:
return False
bits = int.from_bytes(data, "little")
return (all((bits >> shift) & 3 == 1 for shift in (3, 5, 8, 10, 12, 14)) and
data[2] & 63 == 0 and data[3] & 63 == 0 and data[4] & 15 == 0)
def scroll_request(template, ticks):
"""Copy a physical neutral frame and set only the right-wheel scroll count."""
if not neutral_wheel(template) or ticks not in (-FAST_TICKS, -1, 1, FAST_TICKS):
return None
data = bytearray(template)
data[3] = (data[3] & 0xC0) | (ticks & 0x3F)
return (0x3C2, bytes(data), 1)
def plan_step(native, target, allow_fast):
"""Return (ticks, expected native) for the next step from native toward target.
A fast flick lands on the next multiple of 5 in that direction (measured: nearly
every flick of 3+ clicks did this in one change). Use it only
when that multiple does not pass the target and saves at least one click.
"""
sign = 1 if target > native else -1
if allow_fast:
nxt = (native // 5 + 1) * 5 if sign > 0 else ((native - 1) // 5) * 5
if abs(nxt - native) >= 2 and (target - nxt) * sign >= 0:
return sign * FAST_TICKS, nxt
return sign, native + sign
@dataclass(frozen=True)
class SyncAuthority:
observed_boot_ns: int
target_kph: float
is_metric: bool
configuration_id: str
software_owned: bool
document_hash: str = ""
vehicle_hash: str = ""
drive_start_ns: int = 0
manual_receipts: tuple = ()
@dataclass(frozen=True)
class ManualReceipt:
boot_ns: int
frame_index: int
name: str
fast: bool
worker_session: str
sequence: int
document_hash: str
vehicle_hash: str
drive_start_ns: int
processed_boot_ns: int
target_kph: float
@dataclass
class Pending:
before: float
direction: int
units: int
sent_ns: int
data: bytes
ticks: int = 0
retry: bool = False
returned: bool = False
expected: int = 0
gap_ns: int = 0 # time since the previous scroll when sent
class SpeedSynchronizer:
def __init__(self):
self.template = None
self.template_ns = 0
self.driver_ns = 0
self.native_ns = 0
self.native = None
self.units = None
self.cruise_state = None
self.autopark = None
self.counter = None
self.di_valid = False
self.di_key = (0, -1)
self.wheel_stamp = 0
self.pending = None
self.unanswered = None
self.unanswered_count = 0
self.last_sent = 0
self.last_template_sent = 0
self.last_update = 0
self.backoff_until = 0
self.target = None
self.steps = 0
self.blocked = None
self.status = "idle"
self.active = False
self.authority_id = None
self.manual_armed = False
self.manual_active = None
self.manual_queue = []
self.manual_receipts = {}
self.manual_receipt_acks = []
self.manual_ack_key = (0, -1)
self.wheel_key = (0, -1)
self.wheel_held = False # the last wheel frame was a tilt or press without a scroll
self.gas_was_pressed = False
self.handover_until = 0
self.response_ns = 0
self.history = deque(maxlen=32)
self.failure_logged = False
# Nothing is switched off for good: a refusal only pauses that feature.
self.fast_paused_until = 0
self.retry_refused = False
self.tokens = TOKENS_MAX
self.refill_ns = 0
self.last_scroll_ns = 0 # last scroll the Tesla saw: our sent request or the driver's
self.fast_gap_ns = FAST_GAP_NS
self.fast_streak = 0
self.engaged_ns = 0
self.refusals = 0
self.notices = []
self.noticed = set()
def observe(self, packets):
"""Use original arrival timestamps; cached values never refresh freshness."""
for stamp, frames in packets:
if type(stamp) is not int or stamp <= 0:
continue
for frame_index, (address, data, bus) in enumerate(frames):
if address == 0x3C2 and bus in (129, 193):
# Panda echo of a frame we asked it to send: 129 = transmitted,
# 193 = refused by safety. Exact bytes and clock must match.
p = self.pending
if p is not None and not p.returned and stamp >= p.sent_ns and bytes(data) == p.data:
if bus == 129:
p.returned = True
self.last_scroll_ns = max(self.last_scroll_ns, p.sent_ns)
self.refusals = 0
self.steps += 1
self.tokens = max(self.tokens - 1, 0)
else:
self._not_transmitted(p, "panda_rejected")
continue
if address == 0x3C2 and bus == 1:
key = (stamp, frame_index)
if key == self.wheel_key:
continue
if key < self.wheel_key:
self.template = None
self.blocked = "wheel_clock_reversal"
continue
self.wheel_key = key
self.wheel_stamp = stamp
if len(data) != 8:
self.template = None
if self.manual_active:
self._pause_manual("ambiguous_manual_input")
self.manual_armed = False
continue
mux = data[0] & 3
if mux == 0:
continue
if mux != 1:
self.template = None
if self.manual_active:
self._pause_manual("ambiguous_manual_input")
self.manual_armed = False
continue
self._observe_manual(data, stamp, frame_index)
if neutral_wheel(data):
self.template, self.template_ns = bytes(data), stamp
else:
self.template = None
self.driver_ns = stamp
self.last_scroll_ns = max(self.last_scroll_ns, stamp)
# Genuine controls take priority. The request stays outstanding
# until the Tesla's speed changes; direction is then recomputed
# from reality, so nothing is repeated blindly.
if self.pending is not None:
self._record("input_during_request", stamp)
elif address == 0x286 and bus == 0:
# Several DI frames can share one receive batch (same stamp), so
# order by (stamp, index) like the wheel frames above.
key = (stamp, frame_index)
if key <= self.di_key:
if key < self.di_key:
self.blocked = "feedback_clock_reversal"
self.native_ns = 0
continue
self.di_key = key
if len(data) != 8 or data[0] != ((0x86 + 2 + sum(data[1:])) & 0xFF):
self.di_valid = False
continue
counter = data[1] & 15
advancing = self.counter is None or (counter - self.counter) % 16 == 1
self.counter = counter
# Same rule as the panda: a frame after a counter gap is not used,
# and nothing may be sent until the next in-sequence frame.
self.di_valid = advancing
if not advancing:
continue
bits = int.from_bytes(data, "little")
self.native = ((bits >> 15) & 511) * .5
self.units = (bits >> 24) & 1 # 0 mph, 1 km/h
self.cruise_state = (bits >> 12) & 7
self.autopark = (bits >> 25) & 15
self.native_ns = stamp
def _observe_manual(self, data, stamp, frame_index):
right = data[3] & 63
right = right - 64 if right >= 32 else right
if right:
released = bytearray(data)
released[3] &= 0xC0
name = "right_wheel_up" if right > 0 else "right_wheel_down"
if self.manual_active is None and self.wheel_held and abs(right) == 1 and neutral_wheel(released):
# A wheel tilted or pressed often clicks once as it springs back. That click ends the nudge and is not a
# scroll: the comma does not act on it, so nothing waits for it, and the Tesla's change is corrected below.
self._record("nudge_release_click", stamp)
self.wheel_held = False
self.manual_armed = False
return
if (not neutral_wheel(released) or
self.manual_active is None and not (self.manual_armed and self.template is not None and
0 < self.template_ns <= stamp <= self.template_ns + FRESH_NS) or
self.manual_active is not None and self.manual_active[0] != name):
self._pause_manual("ambiguous_manual_input")
return
peak = max(abs(right), self.manual_active[1] if self.manual_active else 0)
self.manual_active = (name, peak)
self.manual_armed = False
self.wheel_held = False
elif neutral_wheel(data):
if self.manual_active:
if len(self.manual_queue) >= 16:
self._fail("manual_input_overflow")
else:
name, peak = self.manual_active
self.manual_queue.append((stamp, frame_index, name, peak >= 2))
self.manual_active = None
self.manual_armed = True
self.wheel_held = False
else:
if self.manual_active:
self._pause_manual("ambiguous_manual_input")
self.manual_active = None
self.manual_armed = False
self.wheel_held = True
def _pause_manual(self, reason):
"""Wheel input that cannot be read as one clean scroll. The comma's own input reader ignores the same gesture, so
nothing waits for it: sync carries on and, after the driver's settle time, puts the Tesla back on the comma's speed.
Logged once per engagement."""
self._notice(reason)
self._record(reason, self.last_update)
self.manual_active = None
self.manual_armed = False
def accept_manual_receipts(self, authority, now_ns):
# Metadata may arrive before Card sees the corresponding CAN batch. Cache
# only bounded, validated receipts; never infer a gesture from the receipt.
if type(authority.manual_receipts) is not tuple or len(authority.manual_receipts) > 16:
self._fail("invalid_manual_receipts")
return
for receipt in authority.manual_receipts:
if not isinstance(receipt, ManualReceipt):
continue
try:
good = (
type(receipt.boot_ns) is int and type(receipt.processed_boot_ns) is int and
0 < receipt.boot_ns <= receipt.processed_boot_ns <= now_ns and
type(receipt.frame_index) is int and 0 <= receipt.frame_index < 4096 and
receipt.name in ("right_wheel_up", "right_wheel_down") and type(receipt.fast) is bool and
type(receipt.worker_session) is str and len(receipt.worker_session) == 32 and
all(c in "0123456789abcdef" for c in receipt.worker_session) and
type(receipt.sequence) is int and receipt.sequence > 0 and
receipt.document_hash == authority.document_hash and len(authority.document_hash) == 64 and
receipt.vehicle_hash == authority.vehicle_hash and len(authority.vehicle_hash) == 64 and
type(receipt.drive_start_ns) is int and receipt.drive_start_ns == authority.drive_start_ns > 0 and
type(receipt.target_kph) in (int, float) and math.isfinite(receipt.target_kph) and
0 < receipt.target_kph < 255)
except (AttributeError, TypeError, ValueError):
good = False
if not good:
continue
if now_ns > receipt.boot_ns + MANUAL_COMPLETION_NS:
# Validated but expired metadata cannot complete a gesture. Dispose of
# it explicitly so it cannot occupy the producer queue indefinitely;
# update() independently faults any unconfirmed observed gesture.
self._ack_manual_receipt(receipt)
continue
key = (receipt.boot_ns, receipt.frame_index)
if key <= self.manual_ack_key:
self._ack_manual_receipt(receipt)
continue
if key not in self.manual_receipts and len(self.manual_receipts) >= 16:
self._fail("manual_receipt_overflow")
return
if key in self.manual_receipts and self.manual_receipts[key] != receipt:
self._fail("conflicting_manual_receipt")
return
self.manual_receipts[key] = receipt
self._ack_manual_receipt(receipt)
self.manual_receipts = {key: r for key, r in self.manual_receipts.items() if now_ns <= r.boot_ns + MANUAL_COMPLETION_NS}
while self.manual_queue:
stamp, index, name, fast = self.manual_queue[0]
receipt = self.manual_receipts.get((stamp, index))
if receipt is None:
break
if (receipt.name, receipt.fast) != (name, fast):
self._fail("manual_receipt_mismatch")
return
self.manual_queue.pop(0)
self.manual_receipts.pop((stamp, index))
self.manual_ack_key = (stamp, index)
self.target = None # Re-read the processed target; never write its owner.
def _ack_manual_receipt(self, receipt):
# Acknowledge metadata custody only; this never acknowledges or repeats a
# speed action. Card removes exactly these immutable receipts next frame.
if receipt not in self.manual_receipt_acks:
if len(self.manual_receipt_acks) >= 16:
self._fail("manual_receipt_ack_overflow")
else:
self.manual_receipt_acks.append(receipt)
def take_manual_receipt_acks(self):
result = tuple(self.manual_receipt_acks)
self.manual_receipt_acks.clear()
return result
def _fail(self, reason):
if not self.blocked:
self._record("fault", self.last_update, reason=reason)
self.blocked = reason
self.pending = None
self.unanswered = None
self._reset_handover()
self.status = reason
return None
def _notice(self, kind, **extra):
# One log line per kind per engagement; these are recoverable pauses.
if kind not in self.noticed:
self.noticed.add(kind)
self.notices.append(dict(kind=kind, native=self.native, target=self.target, **extra))
def _not_transmitted(self, p, reason):
"""The panda never put this frame on the bus, so the car never saw it."""
self.pending = None
if abs(p.ticks) > 1:
# Use single clicks for a while, then try fast steps again.
self.fast_paused_until = self.last_update + FAST_PAUSE_NS
self._notice("fast_step_refused", reason=reason)
elif p.retry:
# Wait for the Tesla's speed to change for this request only.
self.retry_refused = True
self._notice("retry_refused", reason=reason)
else:
self._notice("request_not_transmitted", reason=reason)
self.backoff_until = self.last_update + min(BACKOFF_NS << min(self.refusals, 3), BACKOFF_MAX_NS)
self.refusals += 1
self._record("not_transmitted", self.last_update, reason=reason, ticks=p.ticks)
def _learn_fast_gap(self, p):
landed = math.floor(self.native + .5)
before = math.floor(p.before + .5)
if landed == p.expected:
self.fast_streak += 1
if self.fast_streak >= FAST_GAP_RELAX and self.fast_gap_ns > FAST_GAP_NS:
self.fast_gap_ns = max(self.fast_gap_ns - FAST_GAP_STEP_NS, FAST_GAP_NS)
self.fast_streak = 0
elif abs(landed - before) == 1 and abs(p.expected - before) >= 2:
# The Tesla took it as part of the previous gesture: space them further.
self.fast_streak = 0
if p.gap_ns < FAST_GAP_MAX_NS:
self.fast_gap_ns = min(max(self.fast_gap_ns, p.gap_ns) + FAST_GAP_STEP_NS, FAST_GAP_MAX_NS)
self._notice("fast_step_landed_single", gap_ns=p.gap_ns, fast_gap_ns=self.fast_gap_ns)
self._record("fast_landed_single", self.last_update, gap_ns=p.gap_ns, fast_gap_ns=self.fast_gap_ns)
def _reset_handover(self):
self.gas_was_pressed = False
self.handover_until = 0
def _record(self, event, now_ns, **extra):
self.history.append(dict(event=event, boot_ns=now_ns, native=self.native,
target=self.target, native_ns=self.native_ns,
template_ns=self.template_ns, last_sent=self.last_sent,
units=self.units, cruise_state=self.cruise_state, **extra))
def _resolve_pending(self, now_ns):
"""Advance the outstanding request. Returns True while it still blocks sending."""
p = self.pending
if p is None:
return False
if self.units is not None and self.units != p.units:
self._fail("units_changed_during_request")
return True
if not p.returned and now_ns - p.sent_ns >= RETURN_NS:
self._not_transmitted(p, "no_bus_return")
return True
if self.native_ns > p.sent_ns and self.native != p.before:
# Fresh selected-speed feedback releases one outstanding request.
# This is not an acknowledgement of command delivery or input origin:
# Tesla may change its selection independently. Recompute from reality.
self.pending = None
self.unanswered = None
self.unanswered_count = 0
self.retry_refused = False
self.response_ns = self.native_ns
if abs(p.ticks) == FAST_TICKS:
self._learn_fast_gap(p)
self._record("native_response", now_ns, before=p.before, sent_ns=p.sent_ns, ticks=p.ticks)
self.status = "native_speed_changed"
return False
if now_ns - p.sent_ns >= SETTLE_NS:
# Unanswered. The panda keeps its own request open until the speed
# changes (or, with the updated firmware, until its 1 s timeout).
self.pending = None
self.unanswered = p
self.unanswered_count += 1
self._notice("no_native_response", before=p.before, ticks=p.ticks)
self._record("unanswered", now_ns, before=p.before, ticks=p.ticks)
return True
self.status = "waiting_for_response"
return True
def update(self, now_ns, *, target_kph, enabled, safe, longitudinal_active=True, gas_pressed=False):
if not enabled:
self.pending = None
self.unanswered = None
self.unanswered_count = 0
self.retry_refused = False
self.target = None
self.steps = 0
self.blocked = None
self.active = False
self.authority_id = None
self._reset_handover()
self.response_ns = 0
self.backoff_until = 0
self.engaged_ns = 0
self.failure_logged = False
self.noticed.clear()
self.history.clear()
self.manual_armed = bool(self.template is not None and
0 < self.template_ns <= now_ns <= self.template_ns + FRESH_NS)
self.manual_active = None
self.manual_queue.clear()
self.manual_receipts.clear()
self.manual_receipt_acks.clear()
self.manual_ack_key = self.wheel_key
self.status = "inactive"
self.last_update = now_ns
return None
if type(now_ns) is not int or now_ns <= 0 or (self.last_update and now_ns <= self.last_update):
return self._fail("controller_clock_reversal")
gap = bool(self.last_update and now_ns - self.last_update > FRESH_NS)
self.last_update = now_ns
self.active = True
if not self.engaged_ns:
self.engaged_ns = now_ns
if self.blocked:
self.status = self.blocked
return None
if self._resolve_pending(now_ns) and self.pending is not None:
return None
if self.blocked:
return None
if gap:
# A late controller frame only pauses this frame; a request is never
# sent on timing that has not been observed continuously.
self._reset_handover()
self.status = "controller_clock_gap"
return None
# Past this bound no matching receipt can pass accept_manual_receipts: the comma did not act on that scroll
# (it refused it, or never saw it). Drop it and carry on; the Tesla's change is then corrected like any other
# change of its own. Never infer completion or repeat the input.
if self.manual_queue and now_ns > self.manual_queue[0][0] + MANUAL_COMPLETION_NS:
dropped = [entry for entry in self.manual_queue if now_ns > entry[0] + MANUAL_COMPLETION_NS]
self.manual_queue = [entry for entry in self.manual_queue if entry not in dropped]
self.manual_ack_key = max(self.manual_ack_key, (dropped[-1][0], dropped[-1][1]))
self._notice("manual_action_unconfirmed", dropped=len(dropped))
self._record("manual_action_unconfirmed", now_ns, dropped=len(dropped))
self.target = None
if not safe:
self._reset_handover()
self.target = None
self.status = "inhibited"
return None
if not (0 < self.native_ns <= now_ns <= self.native_ns + FRESH_NS and self.di_valid and
self.native is not None and self.native > 0 and
self.cruise_state in (2, 4) and self.autopark not in (3, 4, 9)):
self._reset_handover()
self.status = "waiting_for_native_speed"
return None
if not math.isfinite(target_kph) or not 0 < target_kph < 255:
self._reset_handover()
self.status = "invalid_target"
return None
# Match the displayed selected speed in Tesla's units, not actual vehicle
# speed or a transient model/curve/lead slowdown.
target = math.floor((target_kph if self.units else target_kph / 1.609344) + .5)
if target <= 0:
self.status = "invalid_target"
return None
target_key = (target, self.units)
if self.target != target_key:
self.target = target_key
# Card and controls publish independently. A genuine pedal release may
# precede longActive by a frame; never transmit while neither current
# authority is present.
if self.gas_was_pressed and not gas_pressed:
self.handover_until = now_ns + HANDOVER_NS
self.gas_was_pressed = bool(gas_pressed)
authorized = bool(longitudinal_active or gas_pressed)
if authorized:
self.handover_until = 0
elif not (self.handover_until and now_ns < self.handover_until):
self._reset_handover()
self.status = "inhibited"
return None
if self.manual_active is not None or self.manual_queue:
self.status = "waiting_for_manual_processing"
return None
if not authorized:
if self.status != "waiting_for_handover":
self._record("handover_wait", now_ns, until_ns=self.handover_until)
self.status = "waiting_for_handover"
return None
native = math.floor(self.native + .5)
if native == target:
self.unanswered = None
self.unanswered_count = 0
self.status = "matched"
return None
# The driver's own scroll takes 0.18-0.4 s to reach the Tesla's selected
# speed (measured). A request in that window can cancel a fast flick, so
# let the Tesla act on it first.
if self.driver_ns and now_ns < self.driver_ns + MANUAL_SETTLE_NS:
self.status = "waiting_for_driver_scroll"
return None
retry = False
if self.unanswered is not None:
u = self.unanswered
# The Tesla moved, or the comma now wants the other way (the Tesla was at its own limit in the old direction):
# the unanswered request says nothing about this one.
if (self.native_ns > u.sent_ns and self.native != u.before) or u.direction != (1 if target > native else -1):
self.unanswered = None
self.unanswered_count = 0
self.retry_refused = False
elif self.retry_refused or self.unanswered_count > MAX_RETRIES:
# e.g. the Tesla is at its own speed limit; don't keep scrolling.
self.status = "waiting_for_native_change"
return None
else:
retry = True
if now_ns < self.backoff_until:
self.status = "backoff"
return None
# The panda only learns that comma engaged from pandad's next heartbeat.
if now_ns < self.engaged_ns + ENGAGE_DELAY_NS:
self.status = "waiting_for_panda_engage"
return None
# Mirror the panda's rate limit so it never has to refuse a request.
if self.refill_ns == 0:
self.refill_ns = now_ns
while self.tokens < TOKENS_MAX and now_ns - self.refill_ns >= TOKEN_REFILL_NS:
self.tokens += 1
self.refill_ns += TOKEN_REFILL_NS
if self.tokens >= TOKENS_MAX:
self.refill_ns = now_ns
if self.tokens <= 0:
self.status = "rate_limited"
return None
# Any physical neutral frame newer than the last one used, still current.
if not (self.template is not None and 0 < self.template_ns <= now_ns <= self.template_ns + TEMPLATE_SEND_NS and
self.template_ns > self.last_template_sent):
self.status = "waiting_for_neutral_wheel"
return None
ticks, expected = plan_step(native, target, allow_fast=now_ns >= self.fast_paused_until and self.units == 0)
gap_ns = now_ns - self.last_scroll_ns if self.last_scroll_ns else 10 * NS
if abs(ticks) == FAST_TICKS and gap_ns < self.fast_gap_ns:
# Too soon for the Tesla to start a new gesture. Clicks give 1 mph per
# 0.1 s and each one restarts the gap, so while fast steps are quicker
# overall (gap under 0.5 s) wait for them on any change of 5 or more.
# For a short change, wait only if that beats clicking there.
wait_ns = self.fast_gap_ns - gap_ns
if ((self.fast_gap_ns < FAST_TICKS * STREAM_STEP_NS and abs(target - native) >= FAST_TICKS) or
wait_ns + FAST_RESPONSE_NS <= abs(expected - native) * STREAM_STEP_NS):
self.status = "waiting_for_fast_gap"
return None
ticks, expected = plan_step(native, target, allow_fast=False)
message = scroll_request(self.template, ticks)
if message is None:
return self._fail("invalid_template")
direction = 1 if ticks > 0 else -1
self.pending = Pending(self.native, direction, self.units, now_ns, message[1], ticks=ticks, retry=retry,
expected=expected, gap_ns=gap_ns)
# A retry keeps the unanswered request on record until the speed changes,
# so a refused retry falls back to waiting rather than retrying forever.
self.last_sent = now_ns
self.last_template_sent = self.template_ns
self.status = "request_pending"
self._record("request", now_ns, direction=direction, ticks=ticks, retry=retry, gap_ns=gap_ns)
return message
def sync_controller(controller, CC, CS, now_ns):
"""Read-only mirror. now_ns is BOOTTIME, matching the CAN producer clock."""
from opendbc.car.structs import CarState
synchronizer = controller.speed_sync
out = CS.out
authority = getattr(controller, "speed_sync_authority", None)
authority_valid = bool(
isinstance(authority, SyncAuthority) and authority.software_owned is True and
type(authority.observed_boot_ns) is int and
0 < authority.observed_boot_ns <= now_ns <= authority.observed_boot_ns + 100_000_000 and
type(authority.is_metric) is bool and synchronizer.units == int(authority.is_metric) and
type(authority.target_kph) in (int, float) and math.isfinite(authority.target_kph) and authority.target_kph == float(out.vCruise) and
type(authority.configuration_id) is str and len(authority.configuration_id) == 64 and all(c in "0123456789abcdef" for c in authority.configuration_id))
if authority_valid and CC.enabled:
if synchronizer.authority_id not in (None, authority.configuration_id):
synchronizer._fail("configuration_changed")
synchronizer.authority_id = authority.configuration_id
synchronizer.accept_manual_receipts(authority, now_ns)
safe = (authority_valid and out.canValid and not out.canTimeout and out.cruiseState.enabled and
out.gearShifter == CarState.GearShifter.drive and
not (out.standstill or out.brakePressed or out.accFaulted or out.stockAeb or out.stockFcw or
out.espDisabled or out.espActive or out.vehicleSensorsInvalid or out.carNotReady or out.doorOpen or out.seatbeltUnlatched or
out.steerFaultPermanent or out.steerFaultTemporary or out.stockLkas or
out.invalidLkasSetting or CS.autopark))
message = synchronizer.update(now_ns, target_kph=float(out.vCruise),
enabled=bool(CC.enabled and not CC.cruiseControl.cancel), safe=bool(safe),
longitudinal_active=bool(CC.longActive), gas_pressed=bool(out.gasPressed))
if not authority_valid and CC.enabled and not synchronizer.blocked:
synchronizer.status = "owner_or_config_ineligible"
if synchronizer.notices or (synchronizer.blocked and not synchronizer.failure_logged):
from opendbc.car.carlog import carlog
for notice in synchronizer.notices:
carlog.warning("speed sync paused: %s", dict(notice, boot_ns=now_ns, history=list(synchronizer.history)[-8:]))
synchronizer.notices.clear()
if synchronizer.blocked and not synchronizer.failure_logged:
synchronizer.failure_logged = True
carlog.warning("speed sync stopped: %s", {"reason": synchronizer.blocked, "boot_ns": now_ns,
"native": synchronizer.native, "target": synchronizer.target, "history": list(synchronizer.history)})
return [] if message is None else [message]
@@ -0,0 +1,210 @@
"""Startup preferences keep the exact speed-sync safety words: co-op steering and Always On Lateral compose with it."""
from pathlib import Path
import re
import pytest
from opendbc.car import gen_empty_fingerprint
from opendbc.car.structs import car
from opendbc.car.tesla.interface import CarInterface
from opendbc.car.tesla.carcontroller import CarController
from opendbc.car.tesla.carstate import CarState
from opendbc.car.tesla.screen_button import (SYNC_WORDS, apply_modern_aol, apply_screen_button, modern_aol_qualified, modern_aol_supported,
screen_qualified, screen_tap_supported, speed_sync_allowed)
from opendbc.car.tesla.speed_sync import SYNC_FLAG, prepare as apply_speed_sync, selected
from opendbc.car.tesla.values import CAR, CANBUS, DBC, TeslaFlags
from openpilot.starpilot.car.tesla.coop_preferences import prepare as apply_cooperative, supported
MODERN = (CAR.TESLA_MODEL_3, CAR.TESLA_MODEL_Y)
# The words tesla_sync_param_valid accepts (safety/modes/tesla_speed_sync.h): 4096 on a word that carries LONG_CONTROL.
NATIVE_SYNC_WORDS = frozenset(4096 | word for word in (1, 257, 513, 769, 1537, 1793, 2049, 2305, 3073, 3329))
def sync_params(candidate=CAR.TESLA_MODEL_3, long=True):
"""A Model 3/Y with the add-on cable, as it leaves startup with Comma can set speed on Tesla dashboard requested."""
fingerprint = gen_empty_fingerprint()
fingerprint[CANBUS.vehicle][0x3DF] = 8
fingerprint[CANBUS.autopilot_party][0x489] = 8
return apply_speed_sync(CarInterface.get_params(candidate, fingerprint, [], long, False, False), True)
def raw(cp):
return cp.as_reader().as_builder().to_bytes()
def startup(cp, coop, screen=False, brake=False):
apply_screen_button(cp, screen, brake)
apply_cooperative(cp, coop)
return cp
def expected_word(coop, screen, brake):
return 4097 | (256 if coop else 0) | ((512 | (1024 if brake else 0)) if screen else 0)
def assert_rejected(cp):
before = raw(cp)
assert not supported(cp)
assert not screen_tap_supported(cp)
assert not screen_qualified(cp)
assert not modern_aol_supported(cp)
apply_cooperative(cp, True)
apply_screen_button(cp, True, True)
apply_modern_aol(cp, True, True, True)
assert raw(cp) == before
def test_python_words_mirror_the_native_list():
assert SYNC_WORDS == NATIVE_SYNC_WORDS
header = (Path(__file__).parents[3] / 'safety/modes/tesla_speed_sync.h').read_text()
body = header[header.index('static bool tesla_sync_param_valid'):]
assert frozenset(4096 | int(word) for word in re.findall(r'base == (\d+)U', body)) == SYNC_WORDS
assert 'GET_FLAG(param, 4096U)' in body
@pytest.mark.parametrize('candidate', MODERN)
def test_selected_word_precondition(candidate):
cp = sync_params(candidate)
assert cp.safetyConfigs[0].safetyParam == 4097 and selected(cp)
assert cp.openpilotLongitudinalControl
assert cp.flags & TeslaFlags.HAS_VEHICLE_BUS
assert speed_sync_allowed(cp, 4097)
assert supported(cp) and screen_tap_supported(cp) and modern_aol_supported(cp) and not screen_qualified(cp)
assert CarController(DBC[cp.carFingerprint], cp).speed_sync is not None
@pytest.mark.parametrize('candidate', MODERN)
@pytest.mark.parametrize('coop', (False, True))
def test_cooperative_on_off_keeps_sync(candidate, coop):
cp = startup(sync_params(candidate), coop)
assert cp.safetyConfigs[0].safetyParam == (4353 if coop else 4097)
apply_cooperative(cp, not coop)
assert cp.safetyConfigs[0].safetyParam == (4097 if coop else 4353)
assert selected(cp)
@pytest.mark.parametrize('candidate', MODERN)
@pytest.mark.parametrize('coop', (False, True))
@pytest.mark.parametrize('screen', (False, True))
@pytest.mark.parametrize('brake', (False, True))
def test_screen_brake_matrix_composes_native_words(candidate, coop, screen, brake):
cp = startup(sync_params(candidate), coop, screen, brake)
expected = expected_word(coop, screen, brake)
assert expected in NATIVE_SYNC_WORDS
assert cp.safetyConfigs[0].safetyParam == expected
assert supported(cp) and screen_tap_supported(cp) and selected(cp)
assert screen_qualified(cp) == screen
assert bool(cp.flags & TeslaFlags.AOL_SCREEN_BUTTON) == screen
apply_screen_button(cp, not screen, brake)
assert cp.safetyConfigs[0].safetyParam == expected_word(coop, not screen, brake)
assert screen_qualified(cp) == (not screen)
@pytest.mark.parametrize('candidate', MODERN)
@pytest.mark.parametrize('coop', (False, True))
@pytest.mark.parametrize('screen', (False, True))
@pytest.mark.parametrize('brake', (False, True))
def test_always_on_lateral_composes_native_words(candidate, coop, screen, brake):
# Ordinary Always On Lateral is 2048 and the screen tap 512; either one keeps speed sync on top.
cp = sync_params(candidate)
apply_modern_aol(cp, True, screen, brake)
apply_cooperative(cp, coop)
expected = 4097 | (512 if screen else 2048) | (1024 if brake else 0) | (256 if coop else 0)
assert cp.safetyConfigs[0].safetyParam == expected and expected in NATIVE_SYNC_WORDS
assert selected(cp) and supported(cp) and modern_aol_supported(cp) and modern_aol_qualified(cp)
apply_modern_aol(cp, False, screen, brake)
assert cp.safetyConfigs[0].safetyParam == 4097 | (256 if coop else 0)
assert selected(cp) and not modern_aol_qualified(cp)
@pytest.mark.parametrize('candidate', MODERN)
@pytest.mark.parametrize('order', ('sync last', 'sync first', 'sync between'))
@pytest.mark.parametrize('aol', (None, 'ordinary', 'screen'))
def test_any_startup_order_gives_the_same_word(candidate, order, aol):
cp = sync_params(candidate)
apply_speed_sync(cp, False)
steps = [lambda: apply_modern_aol(cp, aol is not None, aol == 'screen', True), lambda: apply_cooperative(cp, True)]
steps.insert({'sync first': 0, 'sync between': 1, 'sync last': 2}[order], lambda: apply_speed_sync(cp, True))
for _ in range(2): # prepare, then finalize on the same parameters
for step in steps:
step()
expected = 4097 | 256 | {None: 0, 'ordinary': 2048 | 1024, 'screen': 512 | 1024}[aol]
assert cp.safetyConfigs[0].safetyParam == expected and expected in NATIVE_SYNC_WORDS
@pytest.mark.parametrize('coop_first', (False, True))
@pytest.mark.parametrize('brake', (False, True))
def test_repeated_startup_ordering_preserves_sync(coop_first, brake):
cp = sync_params()
expected = expected_word(True, True, brake)
for _ in range(3):
if coop_first:
apply_cooperative(cp, True)
apply_screen_button(cp, True, brake)
else:
apply_screen_button(cp, True, brake)
apply_cooperative(cp, True)
assert cp.safetyConfigs[0].safetyParam == expected
assert screen_qualified(cp)
apply_cooperative(cp, False)
assert cp.safetyConfigs[0].safetyParam == expected & ~256
apply_screen_button(cp, False, brake)
assert cp.safetyConfigs[0].safetyParam == 4097
apply_cooperative(cp, True)
assert cp.safetyConfigs[0].safetyParam == 4353
def test_sync_longitudinal_off_rejected():
for word in (4096, 4097, 4352):
cp = sync_params(long=False)
assert not cp.safetyConfigs[0].safetyParam & SYNC_FLAG, 'never requested without longitudinal control'
cp.safetyConfigs[0].safetyParam = word
assert_rejected(cp)
cp = sync_params()
cp.openpilotLongitudinalControl = False
assert_rejected(cp)
def test_sync_without_vehicle_bus_or_with_unknown_flag_rejected():
cp = sync_params()
cp.flags &= ~int(TeslaFlags.HAS_VEHICLE_BUS)
assert_rejected(cp)
cp = sync_params()
cp.flags |= 64
assert_rejected(cp)
@pytest.mark.parametrize('word', (4097 | 2, 4097 | 4, 4097 | 16, 4097 | 8192, 4097 | 1024, 4353 | 8192, 4097 | 512 | 2048))
def test_sync_with_unknown_safety_bit_rejected(word):
cp = sync_params()
cp.safetyConfigs[0].safetyParam = word
assert_rejected(cp)
def test_screen_word_must_match_the_screen_flag():
cp = sync_params()
cp.safetyConfigs[0].safetyParam = 4097 | 512 # the screen word without the screen flag in CarParams
assert_rejected(cp)
@pytest.mark.parametrize('candidate', MODERN)
def test_real_controller_and_carstate_cooperate_after_sync_startup(candidate):
cp = startup(sync_params(candidate), True)
assert cp.safetyConfigs[0].safetyParam == 4353
cs = CarState(cp)
cs.hands_on_level = 0
cs.das_control = {'DAS_controlCounter': 0}
cs.out.vEgo = cs.out.vEgoRaw = 20.
cs.out.steeringAngleDeg = 0.
cs.out.gasPressed = False
controller = CarController(DBC[candidate], cp)
assert controller.coop_enabled and controller.speed_sync is not None
cc = car.CarControl.new_message(latActive=True)
for tick in range(10):
cs.out.steeringTorque, cs.out.steeringDisengage = 1., False
_, sends = controller.update(cc.as_reader(), cs, 1_000_000_000 + tick * 10_000_000)
assert not [message for message in sends if message[0] == 0x3C2], 'no scroll request without the comma set speed context'
assert controller.steering_limit_info.get('valid', False)
cs.out.steeringTorque, cs.out.steeringDisengage = 5.1, True
controller.update(cc.as_reader(), cs, 1_100_000_000)
assert not controller.steering_limit_info.get('valid', False)
assert cp.safetyConfigs[0].safetyParam == 4353
@@ -0,0 +1,138 @@
"""The Tesla longitudinal command and the dashboard speed limit: the real formatter, CAN parser and car state; no
vehicle output. The command is the stock one for every Tesla, pedal or not: nothing in it follows the set-speed work."""
import inspect
from types import SimpleNamespace
import pytest
from opendbc.can import CANPacker
from opendbc.car import gen_empty_fingerprint
from opendbc.car.structs import car
from opendbc.car.tesla.interface import CarInterface
from opendbc.car.tesla.carcontroller import CarController
from opendbc.car.tesla.carstate import CarState
from opendbc.car.tesla.speed_sync import prepare
from opendbc.car.tesla.teslacan import TeslaCAN
from opendbc.car.tesla.values import CAR, CANBUS, DBC, CarControllerParams
from opendbc.car.dashboard_speed_limit import Status
from openpilot.starpilot.speed_limits.runtime import dashboard_observation
from openpilot.starpilot.speed_limits.acceptance import ObservationKind
MODERN = (CAR.TESLA_MODEL_3, CAR.TESLA_MODEL_Y)
class Capture:
"""Stands in for the CAN packer: returns the values the formatter chose."""
def make_can_msg(self, name, bus, values):
return name, bus, dict(values)
def stock_command(acc_state, accel, counter, v_ego):
"""The longitudinal command as the stock formatter builds it."""
return {'DAS_setSpeed': min(max(v_ego + accel, 0) * 3.6, 400), 'DAS_accState': acc_state, 'DAS_aebEvent': 0,
'DAS_jerkMin': -4.9, 'DAS_jerkMax': 4.9, 'DAS_accelMin': accel, 'DAS_accelMax': max(accel, 0),
'DAS_controlCounter': counter}
def test_the_formatter_takes_the_stock_arguments_and_keeps_no_state():
parameters = list(inspect.signature(TeslaCAN.create_longitudinal_command).parameters.values())
assert [(p.name, p.kind, p.default) for p in parameters] == [
(name, inspect.Parameter.POSITIONAL_OR_KEYWORD, inspect.Parameter.empty)
for name in ('self', 'acc_state', 'accel', 'counter', 'v_ego', 'active')]
assert sorted(vars(TeslaCAN(None, Capture()))) == ['CP', 'packer']
assert (CarControllerParams.JERK_LIMIT_MIN, CarControllerParams.JERK_LIMIT_MAX) == (-4.9, 4.9)
@pytest.mark.parametrize('acc_state', [4, 13])
@pytest.mark.parametrize('accel', [-3.48, -.1, 0., .8, 2.])
@pytest.mark.parametrize('v_ego', [0., 1.5, 20., 45., 120.])
@pytest.mark.parametrize('active', [False, True])
def test_the_command_is_the_stock_one(acc_state, accel, v_ego, active):
codec = TeslaCAN(None, Capture())
for counter in range(16):
name, bus, values = codec.create_longitudinal_command(acc_state, accel, counter % 8, v_ego, active)
assert (name, bus) == ('DAS_control', CANBUS.party)
assert values == pytest.approx(stock_command(acc_state, accel, counter % 8, v_ego)), 'the same on every call'
assert set(values) == set(stock_command(acc_state, accel, 0, v_ego))
def controller(candidate, *, selected, long=True):
fingerprint = gen_empty_fingerprint()
fingerprint[CANBUS.autopilot_party][0x489] = 8
fingerprint[CANBUS.vehicle][0x3DF] = 8
cp = prepare(CarInterface.get_params(candidate, fingerprint, [], long, False, False), selected)
cs = CarState(cp)
cs.hands_on_level = 0
cs.das_control = {'DAS_controlCounter': 3}
cs.out = car.CarState.new_message(vEgo=20., vEgoRaw=20., canValid=True)
unit = CarController(DBC[candidate], cp)
unit.tesla_can = TeslaCAN(cp, Capture())
return unit, cs
def commands(sends):
return [message[2] for message in sends if message[0] == 'DAS_control']
@pytest.mark.parametrize('candidate', MODERN)
@pytest.mark.parametrize('selected', [False, True])
def test_the_real_controller_sends_the_stock_command_through_a_pedal_press_and_release(candidate, selected):
unit, cs = controller(candidate, selected=selected)
seen = []
for frame in range(400):
cs.out.gasPressed = 100 <= frame < 180
cc = car.CarControl.new_message(enabled=True, longActive=not cs.out.gasPressed, actuators={'accel': .8})
_, sends = unit.update(cc.as_reader(), cs, 1_000_000_000 + frame * 10_000_000)
for values in commands(sends):
assert values == pytest.approx(stock_command(4, .8, (frame // 4) % 8, 20.)), frame
seen.append(frame)
assert seen == list(range(0, 400, 4)), 'every fourth frame, pedal or not'
@pytest.mark.parametrize('candidate', MODERN)
def test_the_real_controller_cancels_with_the_stock_command_without_longitudinal_control(candidate):
unit, cs = controller(candidate, selected=False, long=False)
cc = car.CarControl.new_message(enabled=False, cruiseControl={'cancel': True})
_, sends = unit.update(cc.as_reader(), cs, 1_000_000_000)
assert commands(sends) == [pytest.approx(stock_command(13, 0, 4, 20.))], 'from the first frame, with the full jerk limits'
_, sends = unit.update(car.CarControl.new_message().as_reader(), cs, 1_010_000_000)
assert commands(sends) == []
@pytest.mark.parametrize('candidate', MODERN)
def test_the_car_state_and_controller_carry_nothing_for_a_pedal_hand_over(candidate):
unit, cs = controller(candidate, selected=True)
for holder in (unit, cs, unit.tesla_can):
assert not [name for name in vars(holder) if 'handover' in name or 'gas_release' in name]
with pytest.raises(ImportError):
__import__('opendbc.car.tesla.pedal_handover')
@pytest.mark.parametrize('candidate', [CAR.TESLA_MODEL_3, CAR.TESLA_MODEL_Y])
@pytest.mark.parametrize('units,limit,expected', [(0, 30, 13.4112), (1, 50, 50 / 3.6), (0, 155, 0), (0, 0, 0)])
def test_actual_carstate_publishes_fused_limit(candidate, units, limit, expected):
cp = CarInterface.get_non_essential_params(candidate)
state = CarState(cp)
parsers = state.get_can_parsers(cp)
state.update(parsers) # Register the production parser subscriptions.
packers = {bus: CANPacker(parser.dbc.name) for bus, parser in parsers.items()}
stamp = 0
for i in range(30):
stamp = 1_000_000_000 + i * 100_000_000
for bus, parser in parsers.items():
messages = []
for address in sorted(parser.addresses):
msg = parser.dbc.addr_to_msg[address].name
values = {'DI_speedUnits': units} if msg == 'DI_state' else {'DAS_fusedSpeedLimit': limit} if msg == 'DAS_status' else {}
messages.append(packers[bus].make_can_msg(msg, parser.bus, values))
parser.update([stamp, messages])
state.update(parsers)
obs = state.dashboard_limit.observation
assert obs.status == (Status.VALID if expected else Status.ABSENT if limit == 155 else Status.UNKNOWN)
assert obs.speed_mps == pytest.approx(expected)
evidence = SimpleNamespace(status=obs.status.value, speedMps=obs.speed_mps, observedMonoTime=obs.observed_ns,
validUntilMonoTime=obs.valid_until_ns, episode=obs.episode, producerSessionId='real-parser')
result = dashboard_observation(evidence, car_fingerprint=str(candidate), session_id='drive', now_ns=stamp)
assert result.kind == (ObservationKind.VALID if expected else ObservationKind.ABSENT if limit == 155 else ObservationKind.UNKNOWN)
if expected:
stale = dashboard_observation(evidence, car_fingerprint=str(candidate), session_id='drive', now_ns=obs.valid_until_ns + 1)
assert stale.kind is ObservationKind.STALE
@@ -0,0 +1,331 @@
"""Speed sync requests around the accelerator pedal, lost feedback and unanswered requests. Pure protocol: no device."""
import pytest
from opendbc.car.tesla.speed_sync import (ENGAGE_DELAY_NS, FAST_TICKS, FRESH_NS, HANDOVER_NS, MANUAL_COMPLETION_NS, MAX_RETRIES,
TEMPLATE_SEND_NS, SpeedSynchronizer, neutral_wheel, plan_step, scroll_request)
NEUTRAL = bytes.fromhex('2955000000000040')
def clicks(msg):
"""The signed scroll count of a request."""
ticks = msg[1][3] & 63
return ticks - 64 if ticks >= 32 else ticks
class Rig:
def __init__(self, *, engaged=True):
self.sync = SpeedSynchronizer()
self.now = 1_000_000_000
self.counter = 0
self.speed, self.target, self.units = 45, 50, 1
self.sent = []
self.echo = True # the panda transmits each request and echoes it on bus 129
self._echo = None
if engaged:
# Engaged without longitudinal authority for longer than the panda needs to hear about engagement.
for _ in range(ENGAGE_DELAY_NS // 10_000_000 + 1):
assert self.tick(long=False) is None
def tick(self, dt=10_000_000, *, long=True, gas=False, safe=True, enabled=True,
feedback=True, wheel=NEUTRAL, wheel_bus=1):
self.now += dt
frames = []
if self._echo is not None:
frames.append((0x3c2, self._echo, 129))
self._echo = None
if feedback:
self.counter = (self.counter + 1) % 16
bits = (self.counter << 8) | (2 << 12) | (round(self.speed * 2) << 15) | (self.units << 24)
di = bytearray(bits.to_bytes(8, 'little'))
di[0] = (0x88 + sum(di[1:])) & 255
frames.append((0x286, bytes(di), 0))
if wheel is not None:
frames.append((0x3c2, wheel, wheel_bus))
self.sync.observe([(self.now, frames)])
msg = self.sync.update(self.now, target_kph=self.target, enabled=enabled,
safe=safe, longitudinal_active=long, gas_pressed=gas)
if msg:
self.sent.append((self.now, msg))
if self.echo:
self._echo = msg[1]
return msg
@pytest.mark.parametrize('before', [False, True])
def test_pending_response_on_either_side_of_release(before):
# A request sent under the pedal is answered before or after the release; nothing new is sent in the hand-over
# window, and requests carry on once longitudinal control is back.
r = Rig()
assert r.tick(long=False, gas=True)
if before:
r.speed += 1
assert r.tick(long=False) is None
assert r.sync.blocked is None
r.speed = 46
for _ in range(15):
msg = r.tick()
if msg:
break
assert r.sync.blocked is None
assert msg is not None and len(r.sent) == 2
def test_no_initial_authority_and_held_pedal_engage():
r = Rig()
for _ in range(20):
assert r.tick(long=False) is None
assert not r.sent and r.sync.handover_until == 0
assert r.tick(long=False, gas=True) is not None
def test_no_new_command_during_handover_even_after_response():
r = Rig()
assert r.tick(long=False, gas=True)
r.speed += 1
for _ in range(8):
assert r.tick(long=False) is None
assert r.sync.pending is None and len(r.sent) == 1
assert r.sync.status == 'waiting_for_handover'
def test_grace_expires_once_not_renewed_by_false_samples():
r = Rig()
r.target = r.speed
r.tick(long=False, gas=True)
r.target = 50
r.tick(long=False)
deadline = r.sync.handover_until
assert deadline == r.now + HANDOVER_NS
for _ in range(9):
assert r.tick(long=False) is None
assert r.sync.handover_until == deadline and r.sync.status == 'waiting_for_handover'
assert r.tick(long=False) is None
assert r.now == deadline and r.sync.handover_until == 0 and r.sync.status == 'inhibited'
for _ in range(20):
assert r.tick(long=False) is None, 'no authority, no request'
assert r.sync.blocked is None and not r.sent
def test_release_with_a_request_open_sends_nothing_until_authority_returns():
r = Rig()
assert r.tick(long=False, gas=True)
for _ in range(20):
assert r.tick(long=False) is None
r.speed += 1 # the Tesla answers after the release
for _ in range(20):
assert r.tick(long=False) is None
assert r.sync.status == 'inhibited' and len(r.sent) == 1
assert any(r.tick() for _ in range(5)), 'carries on with longitudinal control'
def test_hard_failure_and_disengagement_clear_edge_history():
r = Rig()
r.target = r.speed
r.tick(gas=True)
r.tick(safe=False)
r.target = 50
assert r.tick(long=False) is None and r.sync.handover_until == 0
r.tick(gas=True, enabled=False)
assert r.tick(long=False) is None and r.sync.handover_until == 0
def test_feedback_loss_pauses_until_fresh_feedback():
r = Rig()
r.target = r.speed
for _ in range(30):
assert r.tick(feedback=False) is None
r.target = 50
assert r.tick(feedback=False) is None
assert r.sync.status == 'waiting_for_native_speed' and r.sync.blocked is None
assert r.tick() is not None, 'carries on once the Tesla speed is fresh again'
def test_units_change_inflight_is_not_handover():
r = Rig()
r.tick(gas=True)
r.units = 0
assert r.tick(long=False) is None
assert r.sync.blocked == 'units_changed_during_request'
def test_manual_input_during_a_request_wins():
# The driver's own scroll is recorded and given time to land; the open request is not repeated.
r = Rig()
assert r.tick(gas=True)
assert r.tick(long=False, wheel=scroll_request(NEUTRAL, -1)[1]) is None
assert r.sync.blocked is None
assert any(h['event'] == 'input_during_request' for h in r.sync.history)
r.speed -= 1
for _ in range(10):
assert r.tick() is None
assert r.sync.status == 'waiting_for_manual_processing', "waits for the comma to act on the driver's scroll"
assert len(r.sent) == 1
for _ in range(MANUAL_COMPLETION_NS // 10_000_000):
r.tick()
assert 'manual_action_unconfirmed' in r.sync.noticed and r.sync.blocked is None
assert len(r.sent) > 1, "after the wait the Tesla is scrolled back to the comma's speed"
def test_no_response_is_retried_a_few_times_then_waits_for_the_tesla():
r = Rig()
r.tick()
for _ in range(100):
r.tick(dt=100_000_000)
assert r.sync.blocked is None and 'no_native_response' in r.sync.noticed
assert r.sync.status == 'waiting_for_native_change'
sent = len(r.sent)
assert sent == MAX_RETRIES + 1, 'the first request and its retries'
for _ in range(20):
assert r.tick() is None
r.speed += 1 # the Tesla moves: requests carry on
assert any(r.tick() for _ in range(20))
def test_an_unanswered_request_does_not_hold_back_the_other_direction():
# The Tesla ignores scrolls one way (it is at its own lowest or highest set speed). A comma speed still on that side
# keeps waiting; once it is on the other side of the Tesla's, sync carries on without the Tesla changing first.
r = Rig()
r.tick()
for _ in range(100):
r.tick(dt=100_000_000)
assert r.sync.status == 'waiting_for_native_change'
sent = len(r.sent)
r.target = 55 # further the same way (the Tesla shows 45)
for _ in range(20):
assert r.tick() is None
assert r.sync.status == 'waiting_for_native_change'
r.target = 40 # now below the Tesla's
assert any(r.tick() for _ in range(20))
assert len(r.sent) == sent + 1 and clicks(r.sent[-1][1]) == -1
r.speed -= 1 # the Tesla follows: nothing is left of the old wait
assert any(r.tick() for _ in range(20)) and r.sync.unanswered is None
def test_request_needs_a_new_physical_neutral_frame():
r = Rig()
r.tick()
r.speed += 1
assert r.tick(wheel=None) is None, 'no neutral frame newer than the one the last request copied'
assert r.tick(wheel=NEUTRAL, wheel_bus=129) is None, "a bus-129 echo is not the driver's wheel"
assert r.sync.status == 'waiting_for_neutral_wheel'
assert r.tick() is not None
def test_request_not_echoed_by_the_panda_is_not_transmitted():
r = Rig()
r.echo = False
assert r.tick()
for _ in range(9):
assert r.tick() is None
r.tick()
assert any(h['event'] == 'not_transmitted' and h['reason'] == 'no_bus_return' for h in r.sync.history)
assert r.sync.pending is None and r.sync.blocked is None
def test_template_age_is_tighter_than_receive_freshness():
r = Rig()
r.target = r.speed
r.tick()
r.target = 50
assert r.tick(dt=TEMPLATE_SEND_NS + 1, wheel=None) is None
assert r.sync.status == 'waiting_for_neutral_wheel'
assert r.tick() is not None
@pytest.mark.parametrize('direction', [-1, 1])
def test_convergence_one_request_per_tesla_change(direction):
r = Rig()
r.target = r.speed + 10 * direction
waiting = None
for _ in range(400):
msg = r.tick()
if msg:
assert waiting is None, 'never two requests open at once'
waiting = r.speed
elif waiting is not None and r.sync.pending is not None and r.now - r.sync.pending.sent_ns >= 30_000_000:
r.speed += direction # the Tesla answers about 30 ms later
waiting = None
if r.sync.status == 'matched':
break
assert r.speed == r.target and len(r.sent) == 10
assert len(r.sync.history) <= 32
def test_same_rounded_target_never_sends():
r = Rig()
r.speed = 45.5
r.target = 46
for _ in range(10):
assert r.tick() is None
assert r.sync.status == 'matched'
def test_controller_clock_gap_pauses_one_frame():
r = Rig()
r.tick(gas=True)
r.speed += 1
assert r.tick(dt=FRESH_NS + 1, long=False) is None
assert r.sync.status == 'controller_clock_gap' and r.sync.blocked is None and r.sync.handover_until == 0
def test_disengaging_clears_the_engagement():
r = Rig()
assert r.tick()
assert r.tick(enabled=False) is None
assert r.sync.status == 'inactive' and r.sync.pending is None and r.sync.target is None and not r.sync.active
assert not r.sync.history and not r.sync.noticed
@pytest.mark.parametrize('native,target,fast,expected', [
(50, 51, True, (1, 51)), (50, 49, True, (-1, 49)),
(50, 55, True, (FAST_TICKS, 55)), (50, 45, True, (-FAST_TICKS, 45)),
(52, 60, True, (FAST_TICKS, 55)), (52, 44, True, (-FAST_TICKS, 50)),
(52, 54, True, (1, 53)), (53, 51, True, (-1, 52)), # the next multiple of five would pass the target
(54, 60, True, (1, 55)), (56, 50, True, (-1, 55)), # one away from the multiple: a click is as quick
(50, 60, False, (1, 51)), (50, 40, False, (-1, 49)), # fast steps paused, or km/h
])
def test_next_step_toward_the_target(native, target, fast, expected):
assert plan_step(native, target, fast) == expected
@pytest.mark.parametrize('ticks', [-FAST_TICKS, -1, 1, FAST_TICKS])
def test_a_request_is_the_neutral_frame_with_only_the_scroll_count_set(ticks):
address, data, bus = scroll_request(NEUTRAL, ticks)
assert (address, bus) == (0x3C2, 1) and len(data) == 8
assert data[3] == (NEUTRAL[3] & 0xC0) | (ticks & 0x3F)
assert data[:3] == NEUTRAL[:3] and data[4:] == NEUTRAL[4:]
assert not neutral_wheel(data), 'a scroll is not a template for the next request'
@pytest.mark.parametrize('ticks', [0, 2, 3, 4, 6, -2, -6, 31, -32])
def test_only_one_click_or_one_fast_flick_is_ever_requested(ticks):
assert scroll_request(NEUTRAL, ticks) is None
def test_no_request_is_built_from_a_frame_that_is_not_neutral():
assert neutral_wheel(NEUTRAL)
pressed = bytearray(NEUTRAL)
pressed[1] = (pressed[1] & ~0x03) | 0x02 # right wheel tilted left
for frame in (bytes(pressed), scroll_request(NEUTRAL, 1)[1], NEUTRAL[:7], bytes(8)):
assert not neutral_wheel(frame)
assert scroll_request(frame, 1) is None
@pytest.mark.parametrize('direction', [-1, 1])
def test_mph_convergence_uses_fast_steps_and_lands_on_the_target(direction):
r = Rig(engaged=False)
r.units, r.speed = 0, 52
r.target = (52 + 14 * direction) * 1.609344
for _ in range(ENGAGE_DELAY_NS // 10_000_000 + 1):
assert r.tick(long=False) is None
for _ in range(2000):
r.tick()
p = r.sync.pending
if p is not None and p.returned and r.now - p.sent_ns >= 30_000_000:
r.speed = p.expected # the Tesla answers about 30 ms later
if r.sync.status == 'matched':
break
assert r.speed == 52 + 14 * direction and r.sync.blocked is None
sizes = [abs(clicks(msg)) for _, msg in r.sent]
assert FAST_TICKS in sizes and 1 in sizes
assert len(r.sent) <= 5, 'far fewer requests than fourteen single clicks'
@@ -0,0 +1,341 @@
"""The driver's own scroll and speed sync. Wheel input that cannot be read as one clean scroll pauses sync; it never
stops it until disengaging.
A right-wheel nudge that springs back with one scroll click is taken by the Tesla and not by the comma, so sync
scrolls the Tesla back. A clean scroll waits for the comma: card's receipt for the step it applied releases it at
once, and without one it is dropped after its window and corrected the same way.
"""
from dataclasses import replace
import pytest
from opendbc.car.tesla.speed_sync import MANUAL_COMPLETION_NS, MANUAL_SETTLE_NS, ManualReceipt, SpeedSynchronizer, SyncAuthority
MPH = 1.609344
DOCUMENT, VEHICLE, SESSION, DRIVE = 'd' * 64, 'e' * 64, '0123456789abcdef' * 2, 100_000_000
NEUTRAL = bytes.fromhex('2955000000000040')
TICK = 50_000_000
def wheel(right_left=1, right_scroll=0):
bits = int.from_bytes(NEUTRAL, 'little')
bits = (bits & ~(3 << 8)) | (right_left << 8)
bits = (bits & ~(63 << 24)) | ((right_scroll & 63) << 24)
return bits.to_bytes(8, 'little')
class Rig:
"""The Tesla in mph at 77, the comma's set speed 77; nothing answers requests unless a test moves `speed`."""
def __init__(self):
self.sync = SpeedSynchronizer()
self.now = 1_000_000_000
self.counter = 0
self.speed = self.target = 77
self.sent = []
def tick(self, data=NEUTRAL):
self.now += TICK
self.counter = (self.counter + 1) % 16
bits = (self.counter << 8) | (2 << 12) | (round(self.speed * 2) << 15)
di = bytearray(bits.to_bytes(8, 'little'))
di[0] = (0x88 + sum(di[1:])) & 255
self.sync.observe([(self.now, [(0x286, bytes(di), 0), (0x3c2, data, 1)])])
msg = self.sync.update(self.now, target_kph=self.target * 1.609344, enabled=True, safe=True, longitudinal_active=True)
if msg:
self.sent.append((self.now, msg))
return msg
def settle(self, seconds):
return [m for m in (self.tick() for _ in range(round(seconds * 1e9 / TICK))) if m]
def clicks(msg):
ticks = msg[1][3] & 63
return ticks - 64 if ticks >= 32 else ticks
def test_nudge_release_click_is_corrected_not_a_stop():
r = Rig()
assert not r.settle(1)
r.tick(wheel(right_left=2))
r.tick(wheel(right_left=2))
r.tick(wheel(right_scroll=1)) # springs back with one click
r.speed = 78 # the Tesla took it; the comma stays at 77
sent = r.settle(1.5)
assert r.sync.blocked is None
assert 'ambiguous_manual_input' not in r.sync.noticed
assert sent and clicks(sent[0]) == -1, 'sync puts the Tesla back on the comma speed'
assert any(h['event'] == 'nudge_release_click' for h in r.sync.history)
def test_unclear_scroll_pauses_and_sync_carries_on():
r = Rig()
r.settle(1)
r.tick(wheel(right_left=2))
r.tick(wheel(right_left=2, right_scroll=1)) # a scroll while the wheel is still tilted
assert r.sync.blocked is None and 'ambiguous_manual_input' in r.sync.noticed
r.tick()
r.speed = 78
sent = r.settle(1.5)
assert r.sync.blocked is None and sent and clicks(sent[0]) == -1
def test_a_driver_scroll_waits_its_window_and_is_then_dropped_with_a_notice():
r = Rig()
r.settle(1)
r.tick(wheel(right_scroll=1)) # a clean scroll; the comma's own speed does not follow it here
r.tick()
r.speed = 78
assert not r.settle(MANUAL_COMPLETION_NS / 1e9 - 0.2), "nothing is sent while the comma may still act on the driver's scroll"
assert r.sync.status == 'waiting_for_manual_processing'
sent = r.settle(1)
assert r.sync.blocked is None and 'manual_action_unconfirmed' in r.sync.noticed
assert any(h['event'] == 'manual_action_unconfirmed' and h['dropped'] == 1 for h in r.sync.history)
assert not r.sync.manual_queue
assert sent and clicks(sent[0]) == -1, "then the Tesla is put back on the comma's speed"
def test_a_driver_scroll_the_comma_followed_needs_no_correction():
r = Rig()
r.settle(1)
r.tick(wheel(right_scroll=1))
r.tick()
r.speed = r.target = 78 # the Tesla and the comma both took the scroll
assert not r.settle(MANUAL_COMPLETION_NS / 1e9 + 1)
assert r.sync.status == 'matched' and r.sync.blocked is None
assert 'manual_action_unconfirmed' in r.sync.noticed, 'the wait always ends with the same notice'
def test_a_fast_driver_scroll_is_one_gesture_and_one_notice_per_engagement():
r = Rig()
r.settle(1)
for _ in range(2):
r.tick(wheel(right_scroll=3))
r.tick(wheel(right_scroll=2)) # the same flick, still turning
r.tick()
assert len(r.sync.manual_queue) == 1 and r.sync.manual_queue[0][2:] == ('right_wheel_up', True)
r.settle(MANUAL_COMPLETION_NS / 1e9 + 0.2)
assert not r.sync.manual_queue
assert len([h for h in r.sync.history if h['event'] == 'manual_action_unconfirmed']) == 2
assert [n['kind'] for n in r.sync.notices].count('manual_action_unconfirmed') == 1
def test_nothing_is_sent_right_after_a_driver_scroll_that_was_never_queued():
r = Rig()
r.settle(1)
r.tick(wheel(right_left=2, right_scroll=1)) # unclear input: paused, not queued
r.tick()
r.speed = 78
assert not r.settle(MANUAL_SETTLE_NS / 1e9 - 0.15), "the Tesla gets time to apply the driver's own scroll first"
assert r.sync.status == 'waiting_for_driver_scroll'
assert r.settle(0.5)
def test_clock_faults_still_stop():
r = Rig()
r.settle(0.5)
r.sync.observe([(r.now - TICK, [(0x3c2, NEUTRAL, 1)])])
assert r.sync.blocked == 'wheel_clock_reversal'
# Card's receipts for the driver's own scrolls.
def scrolled(r, ticks=1):
"""The driver scrolls once; returns the engine's record of it: (stamp, frame index, name, fast)."""
r.settle(1)
r.tick(wheel(right_scroll=ticks))
r.tick()
entry, = r.sync.manual_queue
return entry
def receipt_for(entry, **changes):
"""What card records when it applies the comma step for that scroll, in the frame the scroll was seen."""
stamp, index, name, fast = entry
values = dict(boot_ns=stamp, frame_index=index, name=name, fast=fast, worker_session=SESSION, sequence=1,
document_hash=DOCUMENT, vehicle_hash=VEHICLE, drive_start_ns=DRIVE, processed_boot_ns=stamp,
target_kph=78 * MPH)
values.update(changes)
return ManualReceipt(**values)
def authority(r, *receipts, **changes):
values = dict(observed_boot_ns=r.now, target_kph=r.target * MPH, is_metric=False, configuration_id='a' * 64, software_owned=True,
document_hash=DOCUMENT, vehicle_hash=VEHICLE, drive_start_ns=DRIVE, manual_receipts=tuple(receipts))
values.update(changes)
return SyncAuthority(**values)
def test_a_receipt_releases_the_drivers_scroll_at_once():
r = Rig()
entry = scrolled(r)
assert entry[1:] == (1, 'right_wheel_up', False) and r.sync.status == 'waiting_for_manual_processing'
receipt = receipt_for(entry)
r.speed = r.target = 78 # the Tesla and the comma both took it
r.sync.target = ('stale',)
r.sync.accept_manual_receipts(authority(r, receipt), r.now)
assert not r.sync.manual_queue and r.sync.target is None, 'the comma target is read again'
assert r.sync.take_manual_receipt_acks() == (receipt,) and r.sync.take_manual_receipt_acks() == ()
r.tick()
assert r.sync.status == 'matched' and r.sync.blocked is None
assert not r.settle(MANUAL_COMPLETION_NS / 1e9 + .5)
assert 'manual_action_unconfirmed' not in r.sync.noticed
def test_with_a_receipt_a_difference_is_corrected_without_waiting_out_the_window():
r = Rig()
receipt = receipt_for(scrolled(r))
r.speed, r.target = 79, 78 # the Tesla moved further than the comma did
r.sync.accept_manual_receipts(authority(r, receipt), r.now)
sent = r.settle(MANUAL_SETTLE_NS / 1e9 + .2)
assert sent and clicks(sent[0]) == -1, "corrected as soon as the Tesla has applied the driver's own scroll"
assert r.sent[0][0] - receipt.boot_ns < MANUAL_COMPLETION_NS // 2
waiting = Rig()
scrolled(waiting)
waiting.speed, waiting.target = 79, 78
assert not waiting.settle(MANUAL_SETTLE_NS / 1e9 + .2), 'without a receipt the scroll still waits'
def test_a_receipt_may_arrive_before_the_scroll_is_seen_on_the_bus():
r = Rig()
r.settle(1)
r.tick(wheel(right_scroll=3))
early = receipt_for((r.now + TICK, 1, 'right_wheel_up', True), processed_boot_ns=r.now + TICK)
r.now += TICK # card applied the step in the frame the release arrives in; speed sync sees that frame next
r.sync.accept_manual_receipts(authority(r, early), r.now)
assert r.sync.manual_receipts == {(early.boot_ns, 1): early} and r.sync.take_manual_receipt_acks() == (early,)
r.now -= TICK
r.tick()
assert r.sync.manual_queue == [(early.boot_ns, 1, 'right_wheel_up', True)]
r.sync.accept_manual_receipts(authority(r), r.now)
assert not r.sync.manual_queue and not r.sync.manual_receipts and r.sync.blocked is None
@pytest.mark.parametrize('changes', [dict(name='right_wheel_down'), dict(fast=True)])
def test_a_receipt_for_a_different_scroll_at_the_same_frame_stops_sync(changes):
r = Rig()
receipt = receipt_for(scrolled(r), **changes)
r.sync.accept_manual_receipts(authority(r, receipt), r.now)
assert r.sync.blocked == 'manual_receipt_mismatch'
assert not r.settle(3), 'stopped until disengaging'
@pytest.mark.parametrize('changes', [
dict(document_hash='f' * 64), dict(vehicle_hash='f' * 64), dict(drive_start_ns=DRIVE + 1), dict(drive_start_ns=0),
dict(worker_session='x' * 32), dict(worker_session='0' * 31), dict(sequence=0), dict(sequence=1.0),
dict(name='right_wheel_left'), dict(name='left_wheel_up'), dict(fast=1),
dict(frame_index=-1), dict(frame_index=4096), dict(frame_index=1.0),
dict(target_kph=0), dict(target_kph=255), dict(target_kph=float('nan')), dict(target_kph='125'),
dict(processed_boot_ns=0), dict(boot_ns=0), dict(boot_ns=1.5),
])
def test_a_receipt_that_fails_any_check_is_ignored_and_the_scroll_waits_out_its_window(changes):
r = Rig()
entry = scrolled(r)
receipt = receipt_for(entry, **changes)
r.sync.accept_manual_receipts(authority(r, receipt), r.now)
assert r.sync.manual_queue == [entry] and r.sync.blocked is None
assert r.sync.take_manual_receipt_acks() == (), 'never taken into custody'
r.settle(MANUAL_COMPLETION_NS / 1e9 + .2)
assert 'manual_action_unconfirmed' in r.sync.noticed and not r.sync.manual_queue
def test_a_receipt_processed_in_the_future_or_before_its_scroll_is_ignored():
r = Rig()
entry = scrolled(r)
for changes in (dict(processed_boot_ns=r.now + 1), dict(processed_boot_ns=entry[0] - 1)):
r.sync.accept_manual_receipts(authority(r, receipt_for(entry, **changes)), r.now)
assert r.sync.manual_queue == [entry] and r.sync.take_manual_receipt_acks() == ()
@pytest.mark.parametrize('changes', [dict(document_hash=''), dict(vehicle_hash=''), dict(document_hash='d' * 63)])
def test_receipts_need_an_admission_that_names_the_assignments_and_the_car(changes):
r = Rig()
entry = scrolled(r)
receipt = receipt_for(entry, **changes)
r.sync.accept_manual_receipts(authority(r, receipt, **changes), r.now)
assert r.sync.manual_queue == [entry] and r.sync.take_manual_receipt_acks() == ()
def test_an_expired_receipt_is_disposed_of_and_completes_nothing():
r = Rig()
entry = scrolled(r)
receipt = receipt_for(entry)
r.now = entry[0] + MANUAL_COMPLETION_NS + 1
r.sync.accept_manual_receipts(authority(r, receipt), r.now)
assert r.sync.manual_queue == [entry] and not r.sync.manual_receipts
assert r.sync.take_manual_receipt_acks() == (receipt,), 'handed back so card drops it'
r.now = entry[0] + MANUAL_COMPLETION_NS
r.sync.accept_manual_receipts(authority(r, receipt), r.now)
assert not r.sync.manual_queue, 'exactly at the end of the window still counts'
def test_a_receipt_for_a_scroll_already_dealt_with_is_handed_back():
r = Rig()
entry = scrolled(r)
receipt = receipt_for(entry)
r.sync.accept_manual_receipts(authority(r, receipt), r.now)
r.sync.take_manual_receipt_acks()
r.sync.accept_manual_receipts(authority(r, receipt), r.now) # card had not yet seen the acknowledgment
assert r.sync.take_manual_receipt_acks() == (receipt,) and not r.sync.manual_receipts and r.sync.blocked is None
def test_a_cached_receipt_expires_with_its_window():
r = Rig()
r.settle(1)
early = receipt_for((r.now, 1, 'right_wheel_up', False), processed_boot_ns=r.now)
r.sync.accept_manual_receipts(authority(r, early), r.now)
assert r.sync.manual_receipts
r.settle(MANUAL_COMPLETION_NS / 1e9 + .1)
r.sync.accept_manual_receipts(authority(r), r.now)
assert not r.sync.manual_receipts and r.sync.blocked is None
def test_more_receipts_than_card_ever_holds_stop_sync():
r = Rig()
entry = scrolled(r)
many = tuple(receipt_for(entry, sequence=index + 1) for index in range(17))
r.sync.accept_manual_receipts(authority(r, *many), r.now)
assert r.sync.blocked == 'invalid_manual_receipts'
r = Rig()
scrolled(r)
r.sync.accept_manual_receipts(replace(authority(r), manual_receipts=[]), r.now)
assert r.sync.blocked == 'invalid_manual_receipts', 'only a tuple, as card builds it'
def test_sixteen_receipts_are_accepted():
r = Rig()
r.settle(1)
receipts = tuple(receipt_for((r.now - index, index, 'right_wheel_up', False), processed_boot_ns=r.now, sequence=index + 1)
for index in range(16))
r.sync.accept_manual_receipts(authority(r, *receipts), r.now)
assert r.sync.blocked is None and len(r.sync.manual_receipts) == 16
assert r.sync.take_manual_receipt_acks() == receipts
def test_two_different_receipts_for_one_scroll_stop_sync():
r = Rig()
r.settle(1)
first = receipt_for((r.now, 1, 'right_wheel_up', False), processed_boot_ns=r.now)
r.sync.accept_manual_receipts(authority(r, first), r.now)
r.sync.accept_manual_receipts(authority(r, replace(first, sequence=2)), r.now)
assert r.sync.blocked == 'conflicting_manual_receipt'
def test_anything_that_is_not_a_receipt_is_skipped():
r = Rig()
entry = scrolled(r)
receipt = receipt_for(entry)
r.sync.accept_manual_receipts(authority(r, None, 'receipt', (1, 2), receipt), r.now)
assert not r.sync.manual_queue and r.sync.take_manual_receipt_acks() == (receipt,)
def test_disengaging_forgets_receipts_and_acknowledgments():
r = Rig()
r.settle(1)
early = receipt_for((r.now, 1, 'right_wheel_up', False), processed_boot_ns=r.now)
r.sync.accept_manual_receipts(authority(r, early), r.now)
assert r.sync.manual_receipts and r.sync.manual_receipt_acks
r.now += TICK
r.sync.update(r.now, target_kph=77 * MPH, enabled=False, safe=True)
assert not r.sync.manual_receipts and not r.sync.manual_receipt_acks and r.sync.take_manual_receipt_acks() == ()
@@ -0,0 +1,161 @@
"""Comma can set speed on Tesla dashboard: which cars can have it, and how the startup choice lands in CarParams."""
from types import SimpleNamespace
import pytest
from opendbc.car import gen_empty_fingerprint, get_safety_config, structs
from opendbc.car.tesla.carcontroller import CarController
from opendbc.car.tesla.interface import CarInterface
from opendbc.car.tesla.speed_sync import MODELS, SYNC_FLAG, SpeedSynchronizer, eligible, prepare, selected
from opendbc.car.tesla.values import CAR, CANBUS, DBC, TeslaFlags, TeslaSafetyFlags
MODERN = (CAR.TESLA_MODEL_3, CAR.TESLA_MODEL_Y)
def tesla(candidate=CAR.TESLA_MODEL_3, *, cable=True, long=True):
fingerprint = gen_empty_fingerprint()
fingerprint[CANBUS.autopilot_party][0x489] = 8
if cable:
fingerprint[CANBUS.vehicle][0x3DF] = 8
return CarInterface.get_params(candidate, fingerprint, [], long, False, False)
def word(cp):
return int(cp.safetyConfigs[0].safetyParam)
def raw(cp):
"""The whole CarParams as bytes, from a copy so the builder can be written again."""
return cp.as_reader().as_builder().to_bytes()
def two_configs(cp):
cp.safetyConfigs = [get_safety_config(structs.CarParams.SafetyModel.tesla, 1 | SYNC_FLAG),
get_safety_config(structs.CarParams.SafetyModel.tesla, 1 | SYNC_FLAG)]
def no_configs(cp):
cp.safetyConfigs = []
# Each one alone takes the feature away from an otherwise eligible Model 3.
MISSING = {
'other brand': lambda cp: setattr(cp, 'brand', 'hyundai'),
'model x': lambda cp: setattr(cp, 'carFingerprint', str(CAR.TESLA_MODEL_X)),
'model s hw1': lambda cp: setattr(cp, 'carFingerprint', str(CAR.TESLA_MODEL_S_HW1)),
'model s pre-ap': lambda cp: setattr(cp, 'carFingerprint', str(CAR.TESLA_MODEL_S_PREAP)),
'unknown fingerprint': lambda cp: setattr(cp, 'carFingerprint', 'MOCK'),
'stock longitudinal': lambda cp: setattr(cp, 'openpilotLongitudinalControl', False),
'no car cruise': lambda cp: setattr(cp, 'pcmCruise', False),
'passive': lambda cp: setattr(cp, 'passive', True),
'dashcam': lambda cp: setattr(cp, 'dashcamOnly', True),
'not a car': lambda cp: setattr(cp, 'notCar', True),
'no cable': lambda cp: setattr(cp, 'flags', int(cp.flags) & ~int(TeslaFlags.HAS_VEHICLE_BUS)),
'no safety config': no_configs,
'two safety configs': two_configs,
'safety word without longitudinal': lambda cp: setattr(cp.safetyConfigs[0], 'safetyParam', word(cp) & ~1),
}
def test_the_flag_is_its_own_bit():
assert SYNC_FLAG == 4096 == int(TeslaSafetyFlags.SCROLL_SPEED_SYNC)
others = [flag for flag in TeslaSafetyFlags if flag is not TeslaSafetyFlags.SCROLL_SPEED_SYNC]
assert not any(SYNC_FLAG & int(flag) for flag in others)
assert not SYNC_FLAG & 2048, 'ordinary Always On Lateral keeps 2048'
assert MODELS == tuple(str(model) for model in MODERN)
@pytest.mark.parametrize('candidate', MODERN)
def test_model_3_and_y_with_cable_and_longitudinal_are_eligible_and_start_unselected(candidate):
cp = tesla(candidate)
assert eligible(cp)
assert word(cp) == 1 and not selected(cp), 'the car interface never selects it; startup preferences do'
@pytest.mark.parametrize('candidate', MODERN)
@pytest.mark.parametrize('cable,long', [(False, True), (True, False), (False, False)])
def test_cable_and_longitudinal_are_both_needed(candidate, cable, long):
cp = tesla(candidate, cable=cable, long=long)
before = raw(cp)
assert not eligible(cp) and not selected(cp)
assert prepare(cp, True) is cp and raw(cp) == before
@pytest.mark.parametrize('reason', MISSING)
def test_every_condition_is_required(reason):
cp = tesla()
prepare(cp, True)
assert selected(cp)
MISSING[reason](cp)
assert not eligible(cp), reason
assert not selected(cp), 'a set bit alone selects nothing'
@pytest.mark.parametrize('reason', MISSING)
@pytest.mark.parametrize('requested', (False, True))
def test_prepare_never_touches_a_car_that_is_not_eligible(reason, requested):
cp = tesla()
if reason not in ('no safety config', 'two safety configs'):
cp.safetyConfigs[0].safetyParam = word(cp) | SYNC_FLAG # even a stale bit is left for the car's own code
MISSING[reason](cp)
before = raw(cp)
assert prepare(cp, requested) is cp
assert raw(cp) == before
@pytest.mark.parametrize('candidate', MODERN)
@pytest.mark.parametrize('base', (1, 257, 513, 769, 1537, 1793, 2049, 2305, 3073, 3329))
def test_prepare_sets_and_clears_only_its_own_bit(candidate, base):
cp = tesla(candidate)
cp.safetyConfigs[0].safetyParam = base
rest = raw(cp)
for _ in range(2):
assert prepare(cp, True) is cp
assert word(cp) == base | SYNC_FLAG and selected(cp)
for _ in range(2):
assert prepare(cp, False) is cp
assert word(cp) == base and not selected(cp) and eligible(cp)
assert raw(cp) == rest, 'nothing else in CarParams moved'
def test_prepare_clears_a_stale_selection():
cp = tesla()
cp.safetyConfigs[0].safetyParam = 4097
prepare(cp, False)
assert word(cp) == 1 and not selected(cp)
@pytest.mark.parametrize('cp', [None, object(), SimpleNamespace(), SimpleNamespace(brand='tesla'),
SimpleNamespace(brand='tesla', carFingerprint='TESLA_MODEL_3', openpilotLongitudinalControl=True,
pcmCruise=True, passive=False, dashcamOnly=False, notCar=False, flags=None,
safetyConfigs=[])])
def test_missing_or_malformed_car_parameters_are_not_eligible(cp):
assert eligible(cp) is False and selected(cp) is False
assert prepare(cp, True) is cp
def test_a_reader_is_judged_like_its_builder():
cp = tesla()
assert eligible(cp.as_reader()) and not selected(cp.as_reader())
prepare(cp, True)
assert selected(cp.as_reader())
@pytest.mark.parametrize('candidate', MODERN)
def test_the_controller_builds_a_synchronizer_only_when_selected(candidate):
cp = tesla(candidate)
assert CarController(DBC[candidate], cp).speed_sync is None
prepare(cp, True)
assert isinstance(CarController(DBC[candidate], cp).speed_sync, SpeedSynchronizer)
prepare(cp, False)
assert CarController(DBC[candidate], cp).speed_sync is None
@pytest.mark.parametrize('candidate', (CAR.TESLA_MODEL_X, CAR.TESLA_MODEL_S_HW1, CAR.TESLA_MODEL_S_PREAP))
def test_other_teslas_never_get_a_synchronizer(candidate):
cp = tesla(candidate)
before = raw(cp)
assert not eligible(cp) and not selected(cp)
prepare(cp, True)
assert raw(cp) == before
assert CarController(DBC[candidate], cp).speed_sync is None
+1
View File
@@ -132,6 +132,7 @@ class CarControllerParams:
class TeslaSafetyFlags(IntFlag):
LONG_CONTROL = 1
HW1 = 16
SCROLL_SPEED_SYNC = 4096 # 2048 is the ordinary AOL word
COOP_STEERING = 256
AOL_SCREEN_BUTTON = 512
AOL_SCREEN_DISENGAGE_ON_BRAKE = 1024
+2
View File
@@ -22,6 +22,7 @@ from opendbc.car.mg.values import CAR as MG
# Configurations with source tests but no matching recorded route.
unrecorded_route_gaps = {
SUBARU.SUBARU_CROSSTREK_2018: "subaru/tests/test_supported_firmware.py",
GM.CHEVROLET_VOLT_CC: "gm/tests/test_volt_cc_gas.py",
GM.CHEVROLET_MALIBU_HYBRID_CC: "gm/tests/test_ordinary_cc.py",
TOYOTA.TOYOTA_PRIUS_RETROFIT: "toyota/tests/test_retrofit.py",
@@ -29,6 +30,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)

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