Compare commits

..

401 Commits

Author SHA1 Message Date
firestarsdog 13c6a58ad2 Enlarge Large lead text and thicken lead line for readability 2026-11-27 10:16:48 -05:00
firestar5683 a73d8c0724 Damp Tucson steering oscillation in steady shallow curves 2026-11-27 00:13:43 -06:00
firestar5683 6b79f7a227 Soften Tucson steering feedback in shallow curves 2026-11-27 00:10:21 -06:00
firestar5683 bdef37d674 Default torque steering to StarPilot and Ford to BluePilot Angle 2026-11-27 00:04:17 -06:00
firestar5683 e01e382f81 Reduce residual highway steering oscillation on ninth-generation Accord 2026-11-27 00:02:56 -06:00
firestar5683 a11067b1a7 Cut repeated steering feedback work in Card 2026-11-26 23:58:15 -06:00
firestar5683 03d4f4678b Damp Palisade HDA II off-ramp corrections 2026-11-26 23:54:54 -06:00
firestar5683 bdf5acef74 Recognize the Tucson NX4 with the CW010 camera 2026-11-26 23:47:38 -06:00
firestar5683 58581e40b8 Keep Model Y no-lead departures within normal acceleration 2026-11-26 23:44:54 -06:00
firestar5683 108ab4c931 Apply highway steering damping to the Kona EV SE 2026-11-26 23:42:18 -06:00
firestar5683 a6cd443b63 Release Corolla TSS2 brakes promptly after the planner clears a stop 2026-11-26 23:39:46 -06:00
firestar5683 b074188701 Add Russian offline speed map regions 2026-11-26 23:39:05 -06:00
firestar5683 2614a5bec6 Require factory SET or RESUME before Kona SE engagement 2026-11-26 23:37:36 -06:00
Prabhaav Pillai e4dd33148d build params 2026-11-26 23:46:34 -05:00
Prabhaav Pillai 586da8495e fix default mismatch values for ForceStops and LaneCentering in params and tests 2026-11-26 23:42:57 -05:00
firestarsdog 3db077ff93 Replace lead chevron with shared path lead and stop lines for both UIs 2026-11-26 15:35:36 -05:00
firestar5683 3c93f81677 Smooth Kona CCNC stops and correct standby cruise status 2026-11-26 12:34:36 -06:00
firestar5683 e81f4ff1c7 Latch mixed HDA II AOL after factory Cruise Main is ready 2026-11-26 12:30:01 -06:00
natehuby76 553f2f8cd0 add icons and descriptions to the staff action picker 2026-11-26 13:26:54 -05:00
firestar5683 ab02163241 Recognize the 2026 European Hyundai i30 2026-11-26 12:24:06 -06:00
natehuby76 4ee3010f0d restore AI summaries for companion report titles 2026-11-26 13:18:19 -05:00
natehuby76 9acdd6f0ad clean up companion report titles 2026-11-26 13:00:54 -05:00
firestar5683 26cb9ba73c Fill missed Kona steering slots with neutral output 2026-11-26 11:14:44 -06:00
firestar5683 ea5143fe2c Smooth the final rolling stop on Kona CCNC 2026-11-26 11:10:44 -06:00
natehuby76 ca9adfd5f3 skip reports already moved to driving support 2026-11-26 12:08:07 -05:00
Danny 4d721e9cc7 Build 2026-11-26 08:56:01 -08:00
Danny e33a942745 CI: Build once and run balanced custom and vehicle test shards in parallel 2026-11-26 08:55:20 -08:00
ryan 090eabda53 Leapmotor: add the B10 (angle steering, alpha longitudinal) 2026-11-26 10:46:37 -06:00
firestar5683 4ff8e7a5da Keep Redneck Cruise SET pending until accelerator release 2026-11-26 10:41:25 -06:00
firestar5683 00a65fc19f Allow on-device model downloads on a powered bench 2026-11-26 10:39:25 -06:00
firestar5683 227dffc5b4 Release clear gradual launches on the current model frame 2026-11-26 10:38:30 -06:00
firestar5683 ca17d3963d Smooth Palisade HDA II curve transitions 2026-11-26 10:35:35 -06:00
firestar5683 1bc4c35a0e Keep Mazda AOL armed through brief EPS blocks 2026-11-26 10:32:08 -06:00
firestar5683 b13976776a Keep Palisade HDA II lateral armed when stock ACC pauses 2026-11-26 10:30:37 -06:00
firestar5683 0413e9baa9 Confirm gradual launches while acceleration builds 2026-11-26 10:30:03 -06:00
firestar5683 ed82ef5fde Increase highway steering damping on ninth-generation Accord 2026-11-26 10:25:52 -06:00
firestar5683 0eb7b7f820 Keep manual MQB AOL armed through source recovery and Cancel 2026-11-26 10:25:12 -06:00
Jason Wen 76e2b275f8 HKG: Car Port for Kia Carnival 2027 (HDA II) 2026-11-26 10:24:55 -06:00
firestar5683 e8cab33282 Resume on sustained straight model launches 2026-11-26 10:24:10 -06:00
ryan 763d32b415 aol: drop the Leapmotor CAN2 interrupt-rate exemption
The fault comes from the harness leaving panda bus 1 unconnected, not
from the B10's traffic, so it doesn't belong in the port.
2026-11-26 10:49:05 +01:00
ryan 487227cea9 leapmotor: cap the EPS effort word at the stock maximum
The low-speed boost still deepens the ramp while the wheel lags, but no
further than stock LCC's 46 steps (0x4A5D); the panda limit follows. The
boost past 46 can come back later with its own data.
2026-11-26 10:49:05 +01:00
Prabhaav Pillai 4ecf06649b update test to check for improprerly spaced buttons and fix them 2026-11-26 00:10:49 -05:00
Prabhaav Pillai c33241ba7e incorporate advanced setting levels 2026-11-26 00:10:49 -05:00
firestar5683 3ca28e6f24 Restore parked PID steering evidence and checkpoint replay 2026-11-25 22:55:21 -06:00
firestar5683 8c34e34701 Support 2023 Kona Electric SE conventional cruise 2026-11-25 22:54:46 -06:00
firestar5683 ebb76dce4e Restore Kona stopping ramp and synchronize the cruise display 2026-11-25 22:46:34 -06:00
firestar5683 06ea4e1913 Restore Kona steering requests on the Panda host transport 2026-11-25 22:16:37 -06:00
firestar5683 33f726c85d Recognize the 2023 Kona Electric SE in dashcam mode 2026-11-25 22:10:28 -06:00
ds-sebastian 0730feecc9 RAV4 radar: keep the ACC target receiver under alpha long's radar disable 2026-11-25 22:09:06 -06:00
firestar5683 250c0917bb Soften Palisade HDA II friction feedback 2026-11-25 22:07:50 -06:00
firestar5683 0dc219edba Ask for a Discord report after PR checks pass 2026-11-25 21:58:25 -06:00
firestar5683 12b51d0308 Keep Subaru AOL armed through paddle-exit gear transitions 2026-11-25 21:57:44 -06:00
firestar5683 7d3815dbb5 Close pull requests targeting testing 2026-11-25 21:52:03 -06:00
firestar5683 542b4f463a Dampen Ioniq 6 steering corrections at highway speed 2026-11-25 21:51:00 -06:00
firestar5683 7ff81a0ffb Keep Subaru AOL armed across an early paddle denial 2026-11-25 21:40:33 -06:00
firestar5683 1317718b6d Reduce highway steering chatter on ninth-generation Accord 2026-11-25 21:39:18 -06:00
Sam Yau 6d40f1b0a5 Subaru SNG: accept any counter advance for captured source validity 2026-11-25 21:37:42 -06:00
Prabhaav Pillai aadc1f5700 VASM logs 2026-11-25 20:56:50 -05:00
ds-sebastian 7f8c0301d5 RAV4 radar: ACC target is the only ARS510 receiver
configure_radar() already selects only the ACC-target receiver, so the
object-list receiver (ars510_radar.py) and its ARS510_FUSED flag could
no longer be reached. Remove both, with their tests and their branches
in the radar interface and the angle, EPS8, pedal and filter-AOL checks.
get_params() rebuilds the flags on every start, so no saved value can
bring the old bit back.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 20:55:44 -05:00
ds-sebastian a147e084dc RAV4 radar: keep the ACC target receiver under alpha long's radar disable
Alpha long without a CAN filter disables the radar with UDS
CommunicationControl (28 01 01 to 0x750/0x0F). That stops the radar's
car-bus (bus 0) output only; the radar bus (bus 1) keeps running at full
rate, ACC target 0x235/0x237/0x239 included (RAV4s on 8821F0R03100, one
a 26 min drive; a C-HR Hybrid 8821FF410500 on opendbc's 22 min
"openpilot longitudinal, radar disabled" route).

configure_radar() used to clear the receiver and mark the radar
unavailable in that case, so alpha long without a CAN filter ran
vision-only. Keep the receiver on instead. The radar-torque AOL check
allows ARS510_RADAR on the RAV4 2022 with or without openpilot
longitudinal, as the filter, angle, pedal and EPS8 checks already do.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 20:43:47 -05:00
ds-sebastian 3b73537247 RAV4 radar: ARS510 DBC from commaai/opendbc#3860
TARGET_ID is 6 bits (61|6); the radar's support frames (0x100 PCS
state, 0x190 cycle clock, 0x191-0x194 target summaries, 0x195/0x196
event pair, 0x202 alive, 0x24F boot, 0x680) are documented. The ACC
target frames the receiver reads are otherwise unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 20:43:47 -05:00
Prabhaav Pillai c9bd6fa000 build 2026-11-25 20:42:19 -05:00
Prabhaav Pillai 749878055a device-wide simple advanced preference (this commit does NOT make any toggles simple or advanced and only introduces the feature) 2026-11-25 20:37:42 -05:00
firestar5683 f2b5c13620 Use the correct wheelbase for the 2018 Yukon XL CC 2026-11-25 16:52:00 -06:00
firestar5683 5e7287a796 Keep verified steering evidence from shorter windows 2026-11-25 16:45:47 -06:00
firestar5683 139d8cbe03 Tolerate Model Y launch prediction noise at stops 2026-11-25 16:42:20 -06:00
Sam Yau 3670055c6b Subaru SNG: accept any counter advance for captured source validity
capture() stores only the CANParser's newest accepted sample per batch,
so when pandad batches two Throttle frames (100 Hz) into one packet the
stored counter advances by 2 and the strict previously-stored + 1
validity check flaps False for a tick. Each flap hard-resets StopAndGo's
standstill clock, which needs 51 consecutive ready frames, so the 3 kph
hold pulse never fires and EyeSight's standstill timeout drops ACC --
on essentially every SNG standstill. Replay of the 2026-11-24 incident
segment through the real interface/controller: the counter check was the
only failing gate (71/544 stop ticks) and the clock peaked at 24/51.

Validity now means the stored sample is the parser's current accepted,
checksum-verified sample whose counter advanced from the previously
stored one. A counter that does not advance is still never stored or
validated, and the sender's freshness gates still retire stale
samples. The panda keeps enforcing the strict +1 sequence on the raw
bus, where it sees every frame, before passing any modified frame.

Tests: capture() unit tests for batched delivery (including wraparound
and stalled counters), and a caller-level test with jittered Throttle
batching that reaches the hold pulse -- a delivery pattern the existing
caller harness cannot represent, since it feeds exactly one frame per
message per tick. With this change the incident replay produces hold
pulses (speed=True on 45 calls, clock peak 55, 17 spoofed frames)
instead of none.
2026-11-25 12:49:58 -08:00
firestar5683 b022663e6e Test Volt resume cadence with a controlled clock 2026-11-25 12:40:25 -06:00
firestar5683 4b70f5be81 Test Galaxy save ordering across concurrent logout 2026-11-25 12:19:54 -06:00
firestar5683 d1baceb3ef Split Galaxy component styles to keep assets within CI limits 2026-11-25 12:05:20 -06:00
firestar5683 dfa5c3490f Bump testing version to 7.0.3 2026-11-25 12:03:34 -06:00
Danny 4d6e2a3780 Build 2026-11-25 10:00:10 -08:00
Danny 2f508d507c Connections Page Polish 2026-11-25 09:58:34 -08:00
firestar5683 aec40a8288 Refresh prebuilt receipt for Companion Bot 2026-11-25 11:54:05 -06:00
natehuby76 ab0b4ccf54 move old starport reports to companion support 2026-11-25 12:43:07 -05:00
firestar5683 6cd506c47a Refresh prebuilt receipt for Companion Bot 2026-11-25 11:22:05 -06:00
natehuby76 6ef1123e86 separate staff messages from bot instructions 2026-11-25 11:56:45 -05:00
firestar5683 9ade0195e9 Fix Galaxy log relay lint failures 2026-11-25 10:49:26 -06:00
Danny b9f349c72d Show Fork name in Warning 2026-11-25 07:57:58 -08:00
Danny bb2cd1407e Build 2026-11-25 07:38:24 -08:00
natehuby76 83ebdc716b include android beta and request fresh app logs 2026-11-25 10:27:06 -05:00
natehuby76 e495c527ca request testing on the latest public iphone beta 2026-11-25 10:24:57 -05:00
natehuby76 7547aeeb5c reserve phone tags for mobile app reports 2026-11-25 10:17:41 -05:00
natehuby76 b4c2dfd8b2 unfollow the staff member who closes a ticket 2026-11-25 10:14:02 -05:00
natehuby76 1437f6b8f5 summarize issues in companion thread titles 2026-11-25 09:51:31 -05:00
natehuby76 0d8918edf8 send galaxy diagnostic summaries with staged logs 2026-11-25 09:49:00 -05:00
Danny 670e65d35a Build 2026-11-25 05:55:22 -08:00
Danny 0c52893246 Reporting: Make Clear to User Post Bug post is not yet live 2026-11-25 05:55:00 -08:00
ryan 4dbf3f18f5 leapmotor safety: limit the EPS effort word while openpilot steers
ADAS_LKA.LCC_RAMP sets how much effort the EPS may use to follow the angle
request. While LCC_STEERING_ACTIVE_COPY is set, the panda now only lets it
range from idle (0x7801) to 56 steps deep (0x4071), the deepest value the
car code's low-speed boost sends. Stock LCC goes to 46 steps. When openpilot
is not steering, the field is the camera's own value and is passed on.
2026-11-25 13:50:50 +01:00
ryan e6acb363ed leapmotor safety: cover every branch of the camera accel history
Ported from the upstream PR (commaai/opendbc#3936), where master now
requires full branch coverage and no surviving mutants. The history index
step is an explicit wrap instead of a modulo, where a decrement was an
equivalent mutant. Only rx-checked frames reach the hook, and on the camera
bus that is only ADAS_LKA, so the address check there could not be false.

New tests: every history slot starts inactive (not raw 0, -5 m/s^2), the
stock brake floor uses the least braking request anywhere in the history,
the inactive request is always allowed, another camera frame is not a
camera request, and without the longitudinal flag the request is not
checked.
2026-11-25 10:50:50 +01:00
ryan eb9f52a9fe leapmotor: announce a cruise cancel the car makes by itself
The B10's camera drops ACC on its own, for example when the front
passenger unbuckles (route 00000018, 21:25 CET): cruise turns off and
unavailable in the same frame, and openpilot only showed pcmDisable and
wrongCarMode, a soft chime and no message, at 52 km/h.

Such a cancel is now cruiseDisabled: TAKE CONTROL IMMEDIATELY, "Car
Cancelled Cruise". The driver's own cancels also make ACC_STATE 1, so
braking and the stalk pushed up (now reported as the cancel button) keep
the usual disengage. Replayed on the logged CAN: the passenger cancel and
two others on route 00000017 (18:47, 19:06) are announced; a brake cancel
and a stalk cancel are not.
2026-11-25 10:50:50 +01:00
ryan f0886a5a23 leapmotor: use the stricter override rule whenever the wheel follows openpilot
The bend rule (a89037f) only applied past 15 deg with the EPS pushing into
the turn, and removed 13 of the 38 let-gos after which the wheel sprang back.
Most of the rest happened at small angles. A driver who steers moves the wheel
off openpilot's angle first: all 101 let-gos that came with the wheel 3 deg or
more off are unchanged, including the driver holding it straight against a
12 deg command (route 00000010 23:18:35). With the rule applied whenever the
wheel follows within 3 deg, 37 of the 38 no longer happen at that moment.

A model of the EPS torque needed hands-off did not separate the cases: at
every kind of let-go the EPS was 60-70 above it.
2026-11-25 10:50:50 +01:00
ryan 704d27bfce leapmotor: keep steering through a held bend when the driver only rests a hand
In a held bend the EPS pushes 60-175 into the turn and the driver-torque
reading follows less of it than the EPS-share estimate assumes; the rest
looked like the driver turning further in, and the EPS set its own override
flag with it. openpilot let go mid-bend, the wheel sprang back 7-18 deg and
the car drifted wide (route 0000000a 12:30-12:31).

While the wheel is past 15 deg, within 3 deg of openpilot's angle and the
EPS pushes into the turn, torque in the EPS's direction counts only as far
as the raw reading shows it, and the flag needs torque against the EPS too.
Anywhere else the previous rule applies. Replayed on 8 drives: 13 of 218
let-gos removed, the wheel sprang back after every one; none removed where
the wheel stayed where the driver held it.
2026-11-25 10:50:50 +01:00
ryan fe89adeca1 leapmotor: offer the camera's speed limit to the speed limit controller
ROAD_SIGNS.SPEED_LIMIT, the limit the cluster shows, becomes the dashboard
source (DASH), expiring with the camera's frames. On route 00000010 it
followed the road signs, while the vision source held a misread 25 km/h
for 26 minutes.
2026-11-25 10:50:50 +01:00
ryan 25da2438a3 car: wrap the Platform union under the line limit 2026-11-25 10:50:50 +01:00
ryan 541af7124d leapmotor: describe the 56-step ramp boost as tested 2026-11-25 10:50:50 +01:00
ryan 81e08eb4f8 leapmotor: keep the ramp boost below the EPS's own override torque
Past about 150 of STEER_TORQUE_EPS the EPS sets DRIVER_OVERRIDE with the
driver's hands off and openpilot lets go: engaged frames with the flag were
0-1% below 130, 9% at 130-160 and 50% above 160 (route 00000005). In a
tightening turn at 25 km/h the boost drove the EPS to -167..-218 three
times; it let go each time and the wheel sprang back 25-30 deg. The boost
now holds from 100 and backs off from 120.
2026-11-25 10:50:50 +01:00
ryan 4b1644d4a6 leapmotor: treat the B10's CAN2 interrupt-rate fault as diagnostic
The B10's CAN-FD traffic keeps the panda's interruptRateCan2 fault set on
every pandaStates sample (also on upstream-based drives, where engagement
worked). Dom blocks engagement on any panda fault, so route 00000002 had
controlsMismatch from startup. Exempt only that fault for the B10, as Dom
does for qualified Honda, Hyundai and GM profiles; all other faults block.
2026-11-25 10:50:50 +01:00
ryan cf296a2c5d schema policy: review leapmotor @40 as a second SafetyModel addition
The policy allowed a single reviewed enum field per schema (teslaPreap @39).
It now takes a list of fields.
2026-11-25 10:50:50 +01:00
ryan fcb9fd0d39 leapmotor: curb weight 1780 kg, from the owner 2026-11-25 10:50:50 +01:00
ryan 544b9c0d6c leapmotor: add the Leapmotor B10 port to Dom
Car code, DBC, fingerprints and panda safety from the opendbc Leapmotor port
(commaai/opendbc#3936), with alpha openpilot longitudinal and the low-speed
ramp boost to 56 steps.

Adapted to Dom:
- safety mode 40 (39 is Tesla pre-AP here)
- CRC-8H2F through crc8_update, rx checks const
- CarSpecs mass (Dom still uses it)
- no steering-wheel button events for wheel_actions
2026-11-25 10:50:49 +01:00
firestar5683 caa3b2a0f3 Bind Hyundai publication fixture to platform enum 2026-11-25 02:31:51 -06:00
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
1040 changed files with 80998 additions and 7946 deletions
+11
View File
@@ -11,6 +11,17 @@ jobs:
pull-requests: write pull-requests: write
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- name: Close pull requests targeting testing
if: github.repository == 'StarPilotHQ/StarPilot' && github.event.pull_request.base.ref == 'testing'
env:
GH_TOKEN: ${{ github.token }}
PR_NUMBER: ${{ github.event.pull_request.number }}
run: |
current=$(gh pr view "$PR_NUMBER" --repo "$GITHUB_REPOSITORY" --json baseRefName,state --jq '.baseRefName + ":" + .state')
if [ "$current" = testing:OPEN ]; then
gh pr close "$PR_NUMBER" --repo "$GITHUB_REPOSITORY" --comment 'Please retarget this pull request to `stable` and reopen it. Maintainers publish qualified changes to `testing`.'
fi
- uses: actions/checkout@v7 - uses: actions/checkout@v7
# Label PRs # Label PRs
+12 -2
View File
@@ -11,6 +11,7 @@ on:
- testing - testing
- dev - dev
pull_request: pull_request:
types: [opened, synchronize, reopened, edited]
workflow_dispatch: workflow_dispatch:
workflow_call: workflow_call:
inputs: inputs:
@@ -25,11 +26,15 @@ concurrency:
jobs: jobs:
docs: docs:
name: build docs name: build docs
permissions:
contents: read
runs-on: ${{ 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_name != 'pull_request') ||
(github.event.pull_request.head.repo.full_name == 'commaai/openpilot')) (github.event.pull_request.head.repo.full_name == 'commaai/openpilot'))
&& fromJSON('["namespace-profile-amd64-8x16"]') && fromJSON('["namespace-profile-amd64-8x16"]'))
|| fromJSON('["ubuntu-24.04"]') }} || fromJSON('["ubuntu-24.04"]') }}
steps: steps:
- uses: commaai/timeout@v1 - uses: commaai/timeout@v1
@@ -40,6 +45,11 @@ jobs:
/openpilot/selfdrive/assets/icons_mici/settings/comma_icon.png /openpilot/selfdrive/assets/icons_mici/settings/comma_icon.png
sparse-checkout-cone-mode: false 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 # Build
- name: Build docs - name: Build docs
run: python3 docs/serve.py --build run: python3 docs/serve.py --build
+5
View File
@@ -24,6 +24,9 @@ on:
- '.github/workflows/flm-offroad.yaml' - '.github/workflows/flm-offroad.yaml'
- 'pyproject.toml' - 'pyproject.toml'
- 'uv.lock' - 'uv.lock'
pull_request:
branches: [stable]
types: [opened, synchronize, reopened, edited]
workflow_dispatch: workflow_dispatch:
inputs: inputs:
source_sha: source_sha:
@@ -88,6 +91,8 @@ jobs:
--json-output ci-results/flm-offroad.json --json-output ci-results/flm-offroad.json
.venv/bin/python -m pytest -q --import-mode=importlib \ .venv/bin/python -m pytest -q --import-mode=importlib \
openpilot/starpilot/flm/tests/test_steering_compatibility.py \ 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_observed_maneuvers.py \
openpilot/starpilot/flm/tests/test_upstream_producer_transport.py \ openpilot/starpilot/flm/tests/test_upstream_producer_transport.py \
openpilot/starpilot/flm/tests/test_clock_resolution_budget.py \ openpilot/starpilot/flm/tests/test_clock_resolution_budget.py \
@@ -7,10 +7,12 @@ on:
- 'openpilot/starpilot/galaxy_bluetooth/**' - 'openpilot/starpilot/galaxy_bluetooth/**'
- '.github/workflows/galaxy-phone-bridge.yaml' - '.github/workflows/galaxy-phone-bridge.yaml'
pull_request: pull_request:
branches-ignore: [stable]
paths: paths:
- 'openpilot/starpilot/galaxy_bluetooth/**' - 'openpilot/starpilot/galaxy_bluetooth/**'
- '.github/workflows/galaxy-phone-bridge.yaml' - '.github/workflows/galaxy-phone-bridge.yaml'
workflow_dispatch: workflow_dispatch:
workflow_call:
permissions: permissions:
contents: read contents: read
+3 -2
View File
@@ -35,8 +35,9 @@ jobs:
REPO = "StarPilotHQ/StarPilot" REPO = "StarPilotHQ/StarPilot"
MARKER = "<!-- starpilot-pr-discord-reminder-v1 -->" MARKER = "<!-- starpilot-pr-discord-reminder-v1 -->"
BODY = ("In order to review this PR, please open a ticket in the " BODY = ("Thank you for your PR! Once CI passes on your PR against `stable`, "
"StarPilot Discord at https://firestar.link/discord.\n\n" + MARKER) "please open a report describing it in the StarPilot Discord at "
"[https://firestar.link/discord](https://firestar.link/discord)\n\n" + MARKER)
def remind(event, request): def remind(event, request):
if event.get("action") != "opened" or "pull_request" not in event: if event.get("action") != "opened" or "pull_request" not in event:
+1
View File
@@ -4,6 +4,7 @@ on:
push: push:
branches: [master, Domathon, Dom, StarPilot, stable, testing, dev] branches: [master, Domathon, Dom, StarPilot, stable, testing, dev]
pull_request: pull_request:
types: [opened, synchronize, reopened, edited]
workflow_dispatch: workflow_dispatch:
permissions: permissions:
+99 -25
View File
@@ -11,6 +11,7 @@ on:
- testing - testing
- dev - dev
pull_request: pull_request:
types: [opened, synchronize, reopened, edited]
workflow_dispatch: workflow_dispatch:
workflow_call: workflow_call:
inputs: inputs:
@@ -31,6 +32,12 @@ env:
PYTHONPATH: ${{ github.workspace }} PYTHONPATH: ${{ github.workspace }}
jobs: 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: source_integrity:
name: source integrity name: source integrity
runs-on: ubuntu-24.04 runs-on: ubuntu-24.04
@@ -45,6 +52,7 @@ jobs:
run: | run: |
python3 -m unittest tools.laptop_device_build.tests.test_runtime_dependencies -v 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; 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 - name: Test one-shot branch migration
run: python3 -m unittest discover -s scripts/tests -v run: python3 -m unittest discover -s scripts/tests -v
- name: Validate tracked dependencies - name: Validate tracked dependencies
@@ -93,7 +101,7 @@ jobs:
env: env:
GOTOOLCHAIN: local GOTOOLCHAIN: local
run: | 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) (cd mapd_repo && go mod download)
PYTHONPATH="$GITHUB_WORKSPACE" python3 -m openpilot.starpilot.maps.package_shadow PYTHONPATH="$GITHUB_WORKSPACE" python3 -m openpilot.starpilot.maps.package_shadow
- name: Build devel - name: Build devel
@@ -172,8 +180,31 @@ jobs:
timeout-minutes: 1 timeout-minutes: 1
run: scripts/lint/lint.sh run: scripts/lint/lint.sh
build_host:
name: build host
runs-on: ubuntu-24.04
permissions:
contents: read
steps:
- uses: actions/checkout@v7
- run: ./tools/op.sh setup
- name: Restore the latest native build cache
uses: actions/cache/restore@v4
with:
path: /tmp/scons_cache
key: scons-host-x64-${{ github.sha }}
restore-keys: scons-host-x64-
- name: Build openpilot once for every host test job
run: scons
- name: Share the native build cache with host test jobs
uses: actions/cache/save@v4
with:
path: /tmp/scons_cache
key: scons-host-x64-${{ github.sha }}
unit_tests: unit_tests:
name: unit tests name: unit tests
needs: build_host
runs-on: ${{ runs-on: ${{
(github.repository == 'commaai/openpilot') && (github.repository == 'commaai/openpilot') &&
((github.event_name != 'pull_request') || ((github.event_name != 'pull_request') ||
@@ -199,6 +230,11 @@ jobs:
run: go mod download run: go mod download
- run: ./tools/op.sh setup - run: ./tools/op.sh setup
id: setup id: setup
- name: Restore the shared native build
uses: actions/cache/restore@v4
with:
path: /tmp/scons_cache
key: scons-host-x64-${{ github.sha }}
- name: Build openpilot - name: Build openpilot
id: build id: build
run: scons run: scons
@@ -218,7 +254,7 @@ jobs:
env: env:
RAYLIB_BACKEND: headless RAYLIB_BACKEND: headless
STARPILOT_TEST_DIAGNOSTICS: ci-results/host-test-diagnostics/unittest 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 - name: Test GM vehicle configurations and CAN behavior
if: ${{ !cancelled() && steps.build.outcome == 'success' }} if: ${{ !cancelled() && steps.build.outcome == 'success' }}
timeout-minutes: 5 timeout-minutes: 5
@@ -265,15 +301,16 @@ jobs:
if-no-files-found: error if-no-files-found: error
custom_pytest: custom_pytest:
name: custom pytest (${{ matrix.shard }}) name: custom pytest (${{ matrix.group }})
needs: build_host
runs-on: ubuntu-24.04 runs-on: ubuntu-24.04
timeout-minutes: 35 timeout-minutes: 45
permissions: permissions:
contents: read contents: read
strategy: strategy:
fail-fast: false fail-fast: false
matrix: matrix:
shard: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31] group: [0, 1, 2, 3, 4, 5, 6, 7, 8]
steps: steps:
- uses: actions/checkout@v7 - uses: actions/checkout@v7
- name: Provide JavaScript runtime for Galaxy contract tests - name: Provide JavaScript runtime for Galaxy contract tests
@@ -293,6 +330,11 @@ jobs:
run: go mod download run: go mod download
- run: ./tools/op.sh setup - run: ./tools/op.sh setup
id: setup id: setup
- name: Restore the shared native build
uses: actions/cache/restore@v4
with:
path: /tmp/scons_cache
key: scons-host-x64-${{ github.sha }}
- name: Build openpilot - name: Build openpilot
id: build id: build
run: scons run: scons
@@ -303,22 +345,22 @@ jobs:
.venv/bin/python -c "import av; assert 'libx264' in av.codecs_available" .venv/bin/python -c "import av; assert 'libx264' in av.codecs_available"
- name: Provide Mesa software graphics for pixel-level tests - name: Provide Mesa software graphics for pixel-level tests
if: ${{ !cancelled() && steps.build.outcome == 'success' }} 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 - name: Test every assigned custom pytest node serially
if: ${{ !cancelled() && steps.build.outcome == 'success' }} if: ${{ !cancelled() && steps.build.outcome == 'success' }}
timeout-minutes: 20 timeout-minutes: 30
env: env:
RAYLIB_BACKEND: headless RAYLIB_BACKEND: headless
STARPILOT_AUTO_GL_TEST: "1" STARPILOT_AUTO_GL_TEST: "1"
STARPILOT_TEST_SOFTWARE_EGL: "1" STARPILOT_TEST_SOFTWARE_EGL: "1"
LIBGL_ALWAYS_SOFTWARE: "1" LIBGL_ALWAYS_SOFTWARE: "1"
run: .venv/bin/python -m tools.ci.custom_pytest_shards run --index "${{ matrix.shard }}" --count 32 --output "ci-results/custom-pytest-${{ matrix.shard }}" run: .venv/bin/python -m tools.ci.custom_pytest_shards run --group "${{ matrix.group }}" --groups 9 --count 32 --output "ci-results/custom-pytest-group-${{ matrix.group }}"
- name: Save collection, every outcome, JUnit and durable worker diagnostics - name: Save collection, every outcome, JUnit and durable worker diagnostics
if: always() if: always()
uses: actions/upload-artifact@v4 uses: actions/upload-artifact@v4
with: with:
name: custom-pytest-${{ matrix.shard }} name: custom-pytest-group-${{ matrix.group }}
path: ci-results/custom-pytest-${{ matrix.shard }}/ path: ci-results/custom-pytest-group-${{ matrix.group }}/
if-no-files-found: error if-no-files-found: error
custom_pytest_complete: custom_pytest_complete:
@@ -345,33 +387,39 @@ jobs:
if-no-files-found: error if-no-files-found: error
aol_lifecycles: aol_lifecycles:
name: AOL lifecycles (${{ matrix.shard }}) name: AOL lifecycles (${{ matrix.group }})
needs: build_host
runs-on: ubuntu-24.04 runs-on: ubuntu-24.04
timeout-minutes: 35 timeout-minutes: 45
permissions: permissions:
contents: read contents: read
strategy: strategy:
fail-fast: false fail-fast: false
matrix: matrix:
shard: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15] group: [0, 1, 2, 3]
env: env:
FUZZ_SEED: '0' FUZZ_SEED: '0'
steps: steps:
- uses: actions/checkout@v7 - uses: actions/checkout@v7
- run: ./tools/op.sh setup - run: ./tools/op.sh setup
- name: Restore the shared native build
uses: actions/cache/restore@v4
with:
path: /tmp/scons_cache
key: scons-host-x64-${{ github.sha }}
- name: Build native host dependencies - name: Build native host dependencies
run: scons run: scons
- name: Gate every assigned lifecycle module serially - name: Gate every assigned lifecycle module serially
timeout-minutes: 15 timeout-minutes: 30
env: env:
RAYLIB_BACKEND: headless RAYLIB_BACKEND: headless
run: python3 tools/ci/run_vehicle_tests.py --suite aol-lifecycle --shard-index "${{ matrix.shard }}" --shard-count 16 --output "ci-results/aol-lifecycle-${{ matrix.shard }}" run: python3 tools/ci/run_vehicle_tests.py --suite aol-lifecycle --shard-group "${{ matrix.group }}" --shard-groups 4 --shard-count 16 --output "ci-results/aol-lifecycle-group-${{ matrix.group }}"
- name: Save every lifecycle outcome and native build - name: Save every lifecycle outcome and native build
if: always() if: always()
uses: actions/upload-artifact@v4 uses: actions/upload-artifact@v4
with: with:
name: aol-lifecycle-${{ matrix.shard }} name: aol-lifecycle-group-${{ matrix.group }}
path: ci-results/aol-lifecycle-${{ matrix.shard }}/ path: ci-results/aol-lifecycle-group-${{ matrix.group }}/
if-no-files-found: error if-no-files-found: error
aol_lifecycle_complete: aol_lifecycle_complete:
@@ -410,7 +458,7 @@ jobs:
go-version: '1.25.1' go-version: '1.25.1'
cache-dependency-path: mapd_repo/go.sum cache-dependency-path: mapd_repo/go.sum
- name: Install native build dependencies - 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 - name: Test and build pinned map provider
run: python3 tools/ci/run_map_tests.py --output ci-results/map-provider run: python3 tools/ci/run_map_tests.py --output ci-results/map-provider
- name: Save test and build evidence - name: Save test and build evidence
@@ -423,6 +471,7 @@ jobs:
vehicle_contracts: vehicle_contracts:
name: vehicle contracts (${{ matrix.suite }}) name: vehicle contracts (${{ matrix.suite }})
needs: build_host
runs-on: ubuntu-24.04 runs-on: ubuntu-24.04
timeout-minutes: 35 timeout-minutes: 35
permissions: permissions:
@@ -436,10 +485,17 @@ jobs:
steps: steps:
- uses: actions/checkout@v7 - uses: actions/checkout@v7
- run: ./tools/op.sh setup - run: ./tools/op.sh setup
- name: Restore the shared native build
uses: actions/cache/restore@v4
with:
path: /tmp/scons_cache
key: scons-host-x64-${{ github.sha }}
- name: Build native host dependencies - name: Build native host dependencies
run: scons run: scons
- name: Run explicit vehicle suite and record every result - name: Run explicit vehicle suite and record every result
timeout-minutes: 20 timeout-minutes: 20
env:
STARPILOT_VEHICLE_WORKERS: ${{ matrix.suite == 'interfaces' && '4' || '1' }}
run: python3 tools/ci/run_vehicle_tests.py --suite "${{ matrix.suite }}" --output "ci-results/${{ matrix.suite }}" run: python3 tools/ci/run_vehicle_tests.py --suite "${{ matrix.suite }}" --output "ci-results/${{ matrix.suite }}"
- name: Require current complete interface regression coverage - name: Require current complete interface regression coverage
if: ${{ always() && matrix.suite == 'interfaces' }} if: ${{ always() && matrix.suite == 'interfaces' }}
@@ -457,33 +513,39 @@ jobs:
if-no-files-found: error if-no-files-found: error
safety_release_contracts: safety_release_contracts:
name: RELEASE vehicle contracts (${{ matrix.shard }}) name: RELEASE vehicle contracts (${{ matrix.group }})
needs: build_host
runs-on: ubuntu-24.04 runs-on: ubuntu-24.04
timeout-minutes: 35 timeout-minutes: 45
permissions: permissions:
contents: read contents: read
strategy: strategy:
fail-fast: false fail-fast: false
matrix: matrix:
shard: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15] group: [0, 1, 2, 3]
env: env:
FUZZ_SEED: '0' FUZZ_SEED: '0'
steps: steps:
- uses: actions/checkout@v7 - uses: actions/checkout@v7
- run: ./tools/op.sh setup - run: ./tools/op.sh setup
- name: Restore the shared native build
uses: actions/cache/restore@v4
with:
path: /tmp/scons_cache
key: scons-host-x64-${{ github.sha }}
- name: Build native host dependencies - name: Build native host dependencies
run: scons run: scons
- name: Run every assigned RELEASE target serially - name: Run every assigned RELEASE target serially
timeout-minutes: 20 timeout-minutes: 30
env: env:
RAYLIB_BACKEND: headless RAYLIB_BACKEND: headless
run: python3 tools/ci/run_vehicle_tests.py --suite safety-release --shard-index "${{ matrix.shard }}" --shard-count 16 --output "ci-results/safety-release-${{ matrix.shard }}" run: python3 tools/ci/run_vehicle_tests.py --suite safety-release --shard-group "${{ matrix.group }}" --shard-groups 4 --shard-count 16 --output "ci-results/safety-release-group-${{ matrix.group }}"
- name: Save every RELEASE outcome and native build - name: Save every RELEASE outcome and native build
if: always() if: always()
uses: actions/upload-artifact@v4 uses: actions/upload-artifact@v4
with: with:
name: safety-release-${{ matrix.shard }} name: safety-release-group-${{ matrix.group }}
path: ci-results/safety-release-${{ matrix.shard }}/ path: ci-results/safety-release-group-${{ matrix.group }}/
if-no-files-found: error if-no-files-found: error
safety_release_complete: safety_release_complete:
@@ -578,6 +640,7 @@ jobs:
process_replay: process_replay:
name: process replay name: process replay
needs: build_host
runs-on: ${{ runs-on: ${{
(github.repository == 'commaai/openpilot') && (github.repository == 'commaai/openpilot') &&
((github.event_name != 'pull_request') || ((github.event_name != 'pull_request') ||
@@ -587,6 +650,11 @@ jobs:
steps: steps:
- uses: actions/checkout@v7 - uses: actions/checkout@v7
- run: ./tools/op.sh setup - run: ./tools/op.sh setup
- name: Restore the shared native build
uses: actions/cache/restore@v4
with:
path: /tmp/scons_cache
key: scons-host-x64-${{ github.sha }}
- name: Build openpilot - name: Build openpilot
run: scons run: scons
- name: Run replay - name: Run replay
@@ -657,6 +725,7 @@ jobs:
create_ui_report: create_ui_report:
name: Create UI Report name: Create UI Report
needs: build_host
runs-on: ${{ runs-on: ${{
(github.repository == 'commaai/openpilot') && (github.repository == 'commaai/openpilot') &&
((github.event_name != 'pull_request') || ((github.event_name != 'pull_request') ||
@@ -666,6 +735,11 @@ jobs:
steps: steps:
- uses: actions/checkout@v7 - uses: actions/checkout@v7
- run: ./tools/op.sh setup - run: ./tools/op.sh setup
- name: Restore the shared native build
uses: actions/cache/restore@v4
with:
path: /tmp/scons_cache
key: scons-host-x64-${{ github.sha }}
- name: Build openpilot - name: Build openpilot
run: scons run: scons
- name: Create UI Report - name: Create UI Report
+5 -1
View File
@@ -24,7 +24,7 @@ The radar interface preserves that attribution while adapting to the current int
## RAV4 Continental ARS510 receiver ## RAV4 Continental ARS510 receiver
The optional ACC-target and fused-track receivers and DBC preserve firestar5683's Dom integration from `b220a37f4bd119e402225a7aa16a7cd84878d0af` (Sea Turtles, 2026-10-13) and its ARS510 source attribution to ds-sebastian/ars510-radar `fb5b29c2b5999f34afeb6f7ac494a73949d66c67`, copyright 2026 ARS510 radar contributors. The complete MIT permission and warranty notice is retained in THIRD_PARTY_NOTICES.md. Startup/settings ownership is adapted to the current StarPilot architecture; no original firmware binaries or safety permissions are copied. The ACC-target receiver and DBC preserve firestar5683's Dom integration from `b220a37f4bd119e402225a7aa16a7cd84878d0af` (Sea Turtles, 2026-10-13) and its ARS510 source attribution to ds-sebastian/ars510-radar `fb5b29c2b5999f34afeb6f7ac494a73949d66c67`, copyright 2026 ARS510 radar contributors. The DBC is the one in commaai/opendbc#3860 (ds-sebastian/opendbc `ddcc0b07d1759c96a1d208ae1db13ad91ce23435`). The complete MIT permission and warranty notice is retained in THIRD_PARTY_NOTICES.md. Startup/settings ownership is adapted to the current StarPilot architecture; no original firmware binaries or safety permissions are copied.
## Spotify Bluetooth output ## Spotify Bluetooth output
@@ -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 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. 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) [![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) [![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), StarPilot is an open source driver assistance system for comma 3, 3X, and 4. This branch is where you can try StarPilot 7.0.
an open source driver assistance system.
Openpilot provides ## What's on testing
* Automated Lane Centering
* Adaptive Cruise Control
* Lane Change Assist
* Driver Monitoring *without wheel nags*
Ford-specific lateral-control and vehicle-support work includes substantial adaptations from * **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.
[BluePilot](https://github.com/BluePilotDev/bluepilot/tree/bp-7.0), principally developed by * **Enhanced Stops** improves stops at stop signs and traffic lights. Vision Stop Sign Detection uses the road camera to recognize stop signs.
[Alan Polk](https://github.com/alan-polk) with additional BluePilot contributors. StarPilot's * **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.
implementation has since diverged, but that does not erase its lineage. See [CREDITS.md](CREDITS.md) * **Custom Models** let you choose from community fine tunes in Galaxy's Model Manager.
for the code-level provenance and [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md) for applicable * **On-Device UI Replay** lets you review a recorded drive with the driving interface overlaid on the footage.
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 ## StarPort and companion apps
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).
StarPilot has a vibrant, welcoming community [discord](https://firestar.link/discord). **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.
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)!
## 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, ## Getting started
installation guides, and software configuration.
## 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** ## More driving and device features
* 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!
* 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 ## 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. 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 ## 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. * 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.
+7 -2
View File
@@ -92,9 +92,10 @@ The Ford CAN FD camera-radar filtering includes work adapted from BluePilot's `b
## Continental ARS510 radar ## Continental ARS510 radar
The optional RAV4 radar decoders and `toyota_tss2_ars510.dbc` are adapted from The RAV4 ACC-target radar receiver is adapted from
<https://github.com/ds-sebastian/ars510-radar> at <https://github.com/ds-sebastian/ars510-radar> at
`fb5b29c2b5999f34afeb6f7ac494a73949d66c67`. `fb5b29c2b5999f34afeb6f7ac494a73949d66c67`. `toyota_tss2_ars510.dbc` is the DBC
of commaai/opendbc#3860 (ds-sebastian/opendbc `ddcc0b07d1759c96a1d208ae1db13ad91ce23435`).
MIT License MIT License
@@ -154,3 +155,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 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`. 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 export QCOM_PRIORITY=12
if [ -z "$AGNOS_VERSION" ]; then if [ -z "$AGNOS_VERSION" ]; then
export AGNOS_VERSION="20.5.3" export AGNOS_VERSION="20.5.5"
fi fi
# Legacy stagers defer flashing; agnos_init still requires AGNOS_VERSION before manager startup. # Legacy stagers defer flashing; agnos_init still requires AGNOS_VERSION before manager startup.
+3 -2
View File
@@ -65,8 +65,9 @@ func BundledManagedRegions() ([]ManagedRegion, error) {
if err != nil { if err != nil {
return nil, err return nil, err
} }
result := make([]ManagedRegion, 0, 242) result := make([]ManagedRegion, 0, 252)
for _, group := range []string{"nation", "us_state", "ca_province"} { // Russian district rectangles follow Geofabrik extract envelopes, split at ±180°.
for _, group := range []string{"nation", "us_state", "ca_province", "ru_district"} {
for key, data := range menu[group] { for key, data := range menu[group] {
if key == "" || strings.Contains(key, ".") || data.FullName == "" { if key == "" || strings.Contains(key, ".") || data.FullName == "" {
return nil, errors.New("invalid bundled region") return nil, errors.New("invalid bundled region")
+19 -2
View File
@@ -11,7 +11,7 @@ func TestBundledManagedRegionCoverage(t *testing.T) {
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
if len(regions) != 242 { if len(regions) != 252 {
t.Fatalf("bundled catalog changed: %d", len(regions)) t.Fatalf("bundled catalog changed: %d", len(regions))
} }
available := 0 available := 0
@@ -23,7 +23,7 @@ func TestBundledManagedRegionCoverage(t *testing.T) {
} }
} }
} }
if available != 238 { if available != 248 {
t.Fatalf("review supported-region count changed: %d", available) t.Fatalf("review supported-region count changed: %d", available)
} }
for token, groups := range map[string]int{"us_state.CA": 36, "us_state.TX": 56, "us_state.IL": 12, "nation.CA": 765, "nation.JP": 72, "nation.US": 390} { for token, groups := range map[string]int{"us_state.CA": 36, "us_state.TX": 56, "us_state.IL": 12, "nation.CA": 765, "nation.JP": 72, "nation.US": 390} {
@@ -39,6 +39,23 @@ func TestBundledManagedRegionCoverage(t *testing.T) {
} }
} }
func TestRussianDistrictCoverage(t *testing.T) {
for token, want := range map[string]struct {
bounds [4]float64
groups int
}{
"central": {[4]float64{48, 30, 60, 48}, 54},
"moscow": {[4]float64{54, 36, 58, 40}, 4},
"far-east": {[4]float64{36, 104, 84, 180}, 912},
"far-east-dateline": {[4]float64{62, -180, 74, -168}, 36},
} {
region, err := ResolveManagedRegion("ru_district." + token)
if err != nil || region.Bounds != want.bounds || region.Groups != want.groups {
t.Fatalf("%s: %+v %v", token, region, err)
}
}
}
// Province coverage comes from the pinned Geofabrik extract envelopes. Every // Province coverage comes from the pinned Geofabrik extract envelopes. Every
// envelope must survive outward grid alignment without losing any edge. // envelope must survive outward grid alignment without losing any edge.
func TestCanadianProvinceCoverage(t *testing.T) { func TestCanadianProvinceCoverage(t *testing.T) {
+92
View File
@@ -2183,5 +2183,97 @@
"max_lat": 70.16293 "max_lat": 70.16293
} }
} }
},
"ru_district": {
"central": {
"full_name": "Russia - Central Federal District",
"bounding_box": {
"min_lon": 30.6998,
"min_lat": 49.5045,
"max_lon": 47.6702,
"max_lat": 59.6533
}
},
"far-east": {
"full_name": "Russia - Far Eastern Federal District (main area)",
"bounding_box": {
"min_lon": 105.4219,
"min_lat": 37.3466,
"max_lon": 180,
"max_lat": 82.0002
}
},
"far-east-dateline": {
"full_name": "Russia - Far Eastern Federal District (across the date line)",
"bounding_box": {
"min_lon": -180,
"min_lat": 62.2613,
"max_lon": -168.6841,
"max_lat": 72.2393
}
},
"moscow": {
"full_name": "Russia - Moscow area",
"bounding_box": {
"min_lon": 36,
"min_lat": 54,
"max_lon": 40,
"max_lat": 58
}
},
"north-caucasus": {
"full_name": "Russia - North Caucasus Federal District",
"bounding_box": {
"min_lon": 40.6726,
"min_lat": 41.1355,
"max_lon": 48.8645,
"max_lat": 46.2391
}
},
"northwestern": {
"full_name": "Russia - Northwestern Federal District",
"bounding_box": {
"min_lon": 19.4084,
"min_lat": 54.3128,
"max_lon": 72.6248,
"max_lat": 82.5456
}
},
"siberian": {
"full_name": "Russia - Siberian Federal District",
"bounding_box": {
"min_lon": 70.2748,
"min_lat": 49.021,
"max_lon": 147.7133,
"max_lat": 81.8875
}
},
"southern": {
"full_name": "Russia - Southern Federal District",
"bounding_box": {
"min_lon": 36.5232,
"min_lat": 43.1896,
"max_lon": 49.9367,
"max_lat": 51.2554
}
},
"ural": {
"full_name": "Russia - Ural Federal District",
"bounding_box": {
"min_lon": 57.0426,
"min_lat": 51.8264,
"max_lon": 86.0952,
"max_lat": 75.011
}
},
"volga": {
"full_name": "Russia - Volga Federal District",
"bounding_box": {
"min_lon": 41.7211,
"min_lat": 49.751,
"max_lon": 61.7337,
"max_lat": 61.7197
}
}
} }
} }
+1 -1
View File
@@ -39,7 +39,7 @@ msgq_python = envNanobind.Program(f'msgq/_ipc{python_suffix}', ['msgq/ipc_py.cc'
# Build Vision IPC # Build Vision IPC
vipc_files = ['visionipc.cc', 'visionipc_server.cc', 'visionipc_client.cc'] 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'] vipc_files += ['visionbuf_ion.cc']
else: else:
vipc_files += ['visionbuf.cc'] vipc_files += ['visionbuf.cc']
Binary file not shown.
Binary file not shown.
Binary file not shown.
+3
View File
@@ -26,6 +26,7 @@ from opendbc.car.psa.psacan import psa_checksum
from opendbc.car.rivian.riviancan import rivian_checksum from opendbc.car.rivian.riviancan import rivian_checksum
from opendbc.car.ford.fordcan import FORD_CHECKSUM_FIELDS, ford_checksum from opendbc.car.ford.fordcan import FORD_CHECKSUM_FIELDS, ford_checksum
from opendbc.car.mg.mgcan import mg_checksum from opendbc.car.mg.mgcan import mg_checksum
from opendbc.car.leapmotor.leapmotorcan import leapmotor_checksum
class SignalType: class SignalType:
@@ -281,6 +282,8 @@ def get_checksum_state(dbc_name: str) -> ChecksumState | None:
return ChecksumState(SignalType.BODY_CHECKSUM, body_checksum) return ChecksumState(SignalType.BODY_CHECKSUM, body_checksum)
elif dbc_name.startswith("tesla_model3_party"): elif dbc_name.startswith("tesla_model3_party"):
return ChecksumState(SignalType.TESLA_CHECKSUM, tesla_checksum, tesla_setup_signal) return ChecksumState(SignalType.TESLA_CHECKSUM, tesla_checksum, tesla_setup_signal)
elif dbc_name.startswith("leapmotor_"):
return ChecksumState(SignalType.VOLKSWAGEN_MQB_MEB_CHECKSUM, leapmotor_checksum)
elif dbc_name.startswith("psa_"): elif dbc_name.startswith("psa_"):
return ChecksumState(SignalType.PSA_CHECKSUM, psa_checksum) return ChecksumState(SignalType.PSA_CHECKSUM, psa_checksum)
elif dbc_name.startswith("byd_"): elif dbc_name.startswith("byd_"):
+1
View File
@@ -651,6 +651,7 @@ struct CarParams {
bmw @37; bmw @37;
mg @38; mg @38;
teslaPreap @39; teslaPreap @39;
leapmotor @40;
} }
enum SteerControlType { enum SteerControlType {
+52 -9
View File
@@ -10,12 +10,18 @@ from opendbc.car.fw_versions import (ObdCallback, get_fw_versions, get_fw_versio
get_present_ecus, match_fw_to_car) get_present_ecus, match_fw_to_car)
from opendbc.car.mock.values import CAR as MOCK from opendbc.car.mock.values import CAR as MOCK
from opendbc.car.gm.pedal_capability import automatic_bolt_candidate 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.gm.values import CAR as GM
from opendbc.car.ford.discovery import (normal_bus0_selection as ford_normal_bus0_selection, 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) 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.hyundai.discovery import kona_electric_se_candidate, normal_bus_topology
from opendbc.car.honda.discovery import normal_bus_topology as honda_normal_bus_topology from opendbc.car.hyundai.values import CAR as HYUNDAI
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.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.tesla.discovery import normal_bus0_topology as tesla_normal_bus0_topology
from opendbc.car.values import BRANDS from opendbc.car.values import BRANDS
@@ -94,6 +100,7 @@ def can_fingerprint(can_recv: CanRecvCallable, *, vin: str = VIN_UNKNOWN,
frame += 1 frame += 1
car_fingerprint = automatic_volt_candidate(car_fingerprint, finger, candidate_cars) 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) car_fingerprint = automatic_trax_candidate(car_fingerprint, finger, candidate_cars, vin)
return automatic_bolt_candidate(car_fingerprint, finger, camera_cruise_messages, vin), finger return automatic_bolt_candidate(car_fingerprint, finger, camera_cruise_messages, vin), finger
@@ -143,6 +150,14 @@ def fingerprint(can_recv: CanRecvCallable, can_send: CanSendCallable, set_obd_mu
cached = True cached = True
else: else:
carlog.warning("Getting VIN & FW versions") 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: if known_gm_bus0:
# An explicit registered GM selection already identifies the query family. # An explicit registered GM selection already identifies the query family.
# Current GM requests use normal bus 0. Keep live VIN/FW collection and # Current GM requests use normal bus 0. Keep live VIN/FW collection and
@@ -179,21 +194,40 @@ def fingerprint(can_recv: CanRecvCallable, can_send: CanSendCallable, set_obd_mu
elif (normal_brand := normal_bus_query_brand( elif (normal_brand := normal_bus_query_brand(
observe_normal_bus, normal_bus_topology, observe_normal_bus, normal_bus_topology,
gm_probe=gm_normal_bus0_topology if _gm_fw_uses_normal_bus0() else None, 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 tesla_probe=tesla_normal_bus0_topology if _tesla_fw_uses_normal_bus0() else None) or
('honda' if honda_normal_bus_topology(normal_bus_packets) else None) or ('honda' 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) set_obd_multiplexing(False)
warmup_remaining = 0.1 - (time.monotonic() - start_time) warmup_remaining = 0.1 - (time.monotonic() - start_time)
if warmup_remaining > 0: if warmup_remaining > 0:
time.sleep(warmup_remaining) 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) 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, if normal_brand == 'honda_nidec':
query_brand=normal_brand, normal_bus_only=True) 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} ecu_rx_addrs = {(fw.responseAddress, fw.subAddress or None, fw.bus) for fw in car_fw if fw.responseAddress > 0}
else: else:
full_scan = True
if full_scan:
# enable OBD multiplexing for VIN query # enable OBD multiplexing for VIN query
# NOTE: this takes ~0.1s and is relied on to allow sendcan subscriber to connect in time # NOTE: this takes ~0.1s and is relied on to allow sendcan subscriber to connect in time
set_obd_multiplexing(True) set_obd_multiplexing(True)
@@ -238,6 +272,13 @@ def fingerprint(can_recv: CanRecvCallable, can_send: CanSendCallable, set_obd_mu
# Refine after both automatic sources, before the explicit override below. # Refine after both automatic sources, before the explicit override below.
if not fixed_fingerprint: if not fixed_fingerprint:
car_fingerprint = automatic_bolt_candidate(car_fingerprint, finger, camera_cruise_messages, vin) car_fingerprint = automatic_bolt_candidate(car_fingerprint, finger, camera_cruise_messages, vin)
if car_fingerprint is None:
car_fingerprint = kona_electric_se_candidate(vin, finger, car_fw)
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: if fixed_fingerprint:
car_fingerprint = fixed_fingerprint car_fingerprint = fixed_fingerprint
@@ -297,6 +338,8 @@ def get_car(can_recv: CanRecvCallable, can_send: CanSendCallable, set_obd_multip
CarInterface = interfaces[candidate] CarInterface = interfaces[candidate]
params_options = {'auto_pedal': False} if source == CarParams.FingerprintSource.fixed and candidate in interface_names['gm'] else {} params_options = {'auto_pedal': False} if source == CarParams.FingerprintSource.fixed and candidate in interface_names['gm'] else {}
if candidate in (GM.GMC_YUKON_CC, HYUNDAI.HYUNDAI_KONA_EV_2023_NON_SCC):
params_options['vin'] = vin
CP: CarParams = CarInterface.get_params(candidate, fingerprints, car_fw, alpha_long_allowed, is_release, docs=False, **params_options) CP: CarParams = CarInterface.get_params(candidate, fingerprints, car_fw, alpha_long_allowed, is_release, docs=False, **params_options)
CP.carVin = vin CP.carVin = vin
CP.carFw = car_fw CP.carFw = car_fw
@@ -375,6 +375,7 @@ FW_VERSIONS = {
b'68402704AB', b'68402704AB',
b'68402707AB', b'68402707AB',
b'68402708AB', b'68402708AB',
b'68402710AB',
b'68402714AB', b'68402714AB',
b'68402736AB', b'68402736AB',
b'68402971AD', b'68402971AD',
@@ -421,6 +422,7 @@ FW_VERSIONS = {
b'68412635AH ', b'68412635AH ',
b'68412660AD ', b'68412660AD ',
b'68412660AF ', b'68412660AF ',
b'68422857AD',
b'68422860AB', b'68422860AB',
b'68449435AE ', b'68449435AE ',
b'68496223AA ', b'68496223AA ',
@@ -435,6 +437,7 @@ FW_VERSIONS = {
b'68419675AC', b'68419675AC',
b'68419678AB', b'68419678AB',
b'68423905AB', b'68423905AB',
b'68423907AB',
b'68449258AC', b'68449258AC',
b'68495807AA', b'68495807AA',
b'68495807AB', 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,18 @@ 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) 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 leapmotor_sign(raw: int) -> tuple[Status, float]:
# ROAD_SIGNS.SPEED_LIMIT is in km/h: 20-130 in tens on the B10's drives. 0 and 255 only last single frames, and
# no code for "no sign" has been seen, so neither is evidence of absence.
if 1 <= raw <= 250:
return Status.VALID, raw / 3.6
return Status.UNKNOWN, 0.0
def hyundai_canfd_sign(speed: int, system_status: int, is_metric: bool) -> tuple[Status, float]: 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 # 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. # 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 import time
from opendbc.car.ford.values import CAR, FordFlags 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 # diagnostic query family; live VIN, ECU responses and fingerprinting still
# determine the vehicle and its control configuration. # determine the vehicle and its control configuration.
NORMAL_BUS0_LAYOUT = {(0, 0x82): 8, (0, 0x165): 8, (0, 0x204): 8, 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): 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 reads = 0
deadline = clock() + .12 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): def observe(**kwargs):
nonlocal malformed, gm_malformed, reads nonlocal malformed, gm_malformed, reads
reads += 1 reads += 1
@@ -67,9 +72,9 @@ def normal_bus_query_brand(can_recv, hyundai_probe, *, gm_probe=None, volvo_prob
length = len(frame.dat) length = len(frame.dat)
gm_malformed |= frame.address in bus and bus[frame.address] != length gm_malformed |= frame.address in bus and bus[frame.address] != length
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) length = len(frame.dat)
malformed |= length != NORMAL_BUS0_LAYOUT[key] malformed |= length != expected
received[key] = length received[key] = length
return packets return packets
@@ -77,11 +82,11 @@ def normal_bus_query_brand(can_recv, hyundai_probe, *, gm_probe=None, volvo_prob
return 'hyundai' return 'hyundai'
# Rejecting HKG or Ford does not reject GM. Finish the shared passive window # Rejecting HKG or Ford does not reject GM. Finish the shared passive window
# within its original budget even when an early frame excludes Ford. # 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): if malformed and ((gm_probe is None and volvo_probe is None and tesla_probe is None) or gm_malformed):
break break
observe(wait_for_one=True) 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' return 'ford'
if gm_probe is not None and not gm_malformed and gm_probe(gm_received): if gm_probe is not None and not gm_malformed and gm_probe(gm_received):
return 'gm' return 'gm'
@@ -93,6 +93,7 @@ class Request:
logging: bool = False logging: bool = False
# pandad toggles OBD multiplexing on/off as needed # pandad toggles OBD multiplexing on/off as needed
obd_multiplexing: bool = True obd_multiplexing: bool = True
brand_query_only: bool = False
@dataclass @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 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]]: 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) fw_versions_dict: defaultdict[AddrType, set[bytes]] = defaultdict(set)
for fw in fw_versions: 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: []} parallel_queries: dict[bool, list[EcuAddrBusType]] = {True: [], False: []}
responses: set[EcuAddrBusType] = set() 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]): for ecu_type, addr, sub_addr in config.get_all_ecus(VERSIONS[brand]):
# Only query ecus in whitelist if whitelist is not empty # Only query ecus in whitelist if whitelist is not empty
if len(r.whitelist_ecus) == 0 or ecu_type in r.whitelist_ecus: 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""" """Returns dictionary of brands and matches with ECUs in their FW versions"""
brand_rx_addrs = {brand: set() for brand in FW_QUERY_CONFIGS} 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 # 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]): for ecu in config.get_all_ecus(VERSIONS[brand]):
if len(r.whitelist_ecus) == 0 or ecu[0] in r.whitelist_ecus: 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])) 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, 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, 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() versions = VERSIONS.copy()
if query_brand is not None: 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 # Get versions and build capnp list to put into CarParams
car_fw = [] 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)] 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_group in tqdm(addrs, disable=not progress): # split by subaddr, if any
for addr_chunk in chunks(addr_group): for addr_chunk in chunks(addr_group):
+1 -1
View File
@@ -50,7 +50,7 @@ def migrate_assignments(params, cp):
('LongDistanceButtonControl', 'LongCancelButtonControl', 5), ('LongDistanceButtonControl', 'LongCancelButtonControl', 5),
('VeryLongDistanceButtonControl', 'VeryLongCancelButtonControl', 6)) ('VeryLongDistanceButtonControl', 'VeryLongCancelButtonControl', 6))
pending = [] 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: for source, target, default in pairs:
raw, readable = read_saved(params, target, 8) raw, readable = read_saved(params, target, 8)
previous, source_readable = read_saved(params, source, 8) previous, source_readable = read_saved(params, source, 8)
+5 -1
View File
@@ -1008,7 +1008,8 @@ class CarController(CarControllerBase):
else: else:
stop_brake = fixed_stopping_brake(CC.longActive, near_stop, stopping, CC.cruiseControl.resume, stop_brake = fixed_stopping_brake(CC.longActive, near_stop, stopping, CC.cruiseControl.resume,
self.CP.stopAccel, self.params.MAX_BRAKE) 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_gas = self.params.INACTIVE_REGEN
self.apply_brake = stop_brake self.apply_brake = stop_brake
if self.truck_tuning is not None: if self.truck_tuning is not None:
@@ -1035,6 +1036,9 @@ class CarController(CarControllerBase):
self.apply_gas, self.apply_brake = bolt_euv_demands( self.apply_gas, self.apply_brake = bolt_euv_demands(
actuators.accel, CS.out.vEgo, CC.orientationNED if long_pitch else None, 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) 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: 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( self.apply_gas, self.apply_brake = volt_demands(
actuators.accel, CS.out.vEgo, CC.orientationNED if long_pitch else None, 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 \ ret.standstill = abs(pt_cp.vl["EBCMWheelSpdRear"]["RLWheelSpd"]) <= STANDSTILL_THRESHOLD and \
abs(pt_cp.vl["EBCMWheelSpdRear"]["RRWheelSpd"]) <= STANDSTILL_THRESHOLD 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") ret.gearShifter = self.parse_gear_shifter("T")
else: 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) & source_be_brake = (gm_control_word(self.CP) &
(GMSafetyFlags.ASCM_INTERCEPT | GMSafetyFlags.SDGM).value and (GMSafetyFlags.ASCM_INTERCEPT | GMSafetyFlags.SDGM).value and
@@ -493,7 +495,10 @@ class CarState(CarStateBase):
if new_sample: if new_sample:
self.pedal_sensor_ts_nanos = sensor_ts self.pedal_sensor_ts_nanos = sensor_ts
self.pedal_sensor_counter = counter 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: elif sensor_ts < self.pedal_sensor_ts_nanos:
self.pedal_sensor_healthy = False self.pedal_sensor_healthy = False
self.pedal_sensor_ts_nanos = 0 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 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 # Frequent normal-bus frames observed on mirrored pedal installations. This is
# only diagnostic query-family evidence, never a vehicle/control fingerprint. # only diagnostic query-family evidence, never a vehicle/control fingerprint.
PEDAL_NORMAL_BUS_LAYOUT = {0xD3: 2, 0xBE: 6, 0xC9: 8, 0x1C4: 8, PEDAL_NORMAL_BUS_LAYOUT = {0xD3: 2, 0xBE: 6, 0xC9: 8, 0x1C4: 8,
+11 -3
View File
@@ -3,7 +3,7 @@ from opendbc.car import ACCEL_MAX_TAKEOFF
from math import fabs, exp from math import fabs, exp
import numpy as np import numpy as np
from opendbc.car import Bus, get_safety_config, structs from opendbc.car import Bus, get_safety_config, scale_rot_inertia, scale_tire_stiffness, structs
from opendbc.car.pedal import supported_pedal_detected from opendbc.car.pedal import supported_pedal_detected
from opendbc.car.gm.pedal_capability import pedal_candidate from opendbc.car.gm.pedal_capability import pedal_candidate
from opendbc.car.common.conversions import Conversions as CV from opendbc.car.common.conversions import Conversions as CV
@@ -22,6 +22,7 @@ from opendbc.car.gm.values import (volt_cc_pedal_profile, CAR, CarControllerPara
from opendbc.car.gm.values import (malibu_hybrid_profile, MALIBU_HYBRID_SOURCES, from opendbc.car.gm.values import (malibu_hybrid_profile, MALIBU_HYBRID_SOURCES,
is_volt_sdgm_accepted_envelope, volt_sdgm_accepted_accel_max) is_volt_sdgm_accepted_envelope, volt_sdgm_accepted_accel_max)
from opendbc.car.interfaces import CarInterfaceBase, TorqueFromLateralAccelCallbackType, LateralAccelFromTorqueCallbackType from opendbc.car.interfaces import CarInterfaceBase, TorqueFromLateralAccelCallbackType, LateralAccelFromTorqueCallbackType
from opendbc.car.vin import VIN_UNKNOWN, is_valid_vin
TransmissionType = structs.CarParams.TransmissionType TransmissionType = structs.CarParams.TransmissionType
NetworkLocation = structs.CarParams.NetworkLocation NetworkLocation = structs.CarParams.NetworkLocation
@@ -43,9 +44,16 @@ class CarInterface(CarInterfaceBase):
structs.CarState.GearShifter.eco, structs.CarState.GearShifter.manumatic) structs.CarState.GearShifter.eco, structs.CarState.GearShifter.manumatic)
@classmethod @classmethod
def get_params(cls, candidate, fingerprint, car_fw, alpha_long, is_release, docs, *, auto_pedal=True): def get_params(cls, candidate, fingerprint, car_fw, alpha_long, is_release, docs, *, auto_pedal=True, vin=VIN_UNKNOWN):
selected = pedal_candidate(candidate, fingerprint) if auto_pedal else candidate selected = pedal_candidate(candidate, fingerprint) if auto_pedal else candidate
return super().get_params(selected, fingerprint, car_fw, alpha_long, is_release, docs) ret = super().get_params(selected, fingerprint, car_fw, alpha_long, is_release, docs)
# The recorded 2018 Yukon XL SLT uses the same CC profile as the short Yukon.
if selected == CAR.GMC_YUKON_CC and is_valid_vin(vin) and vin.startswith('1GKS2GKC') and vin[9] == 'J':
ret.wheelbase = 3.302 # GMC 2018 Yukon brochure, 130.0 inches.
ret.centerToFront = ret.wheelbase * CAR.GMC_YUKON_CC.config.specs.centerToFrontRatio
ret.rotationalInertia = scale_rot_inertia(ret.mass, ret.wheelbase)
ret.tireStiffnessFront, ret.tireStiffnessRear = scale_tire_stiffness(ret.mass, ret.wheelbase, ret.centerToFront, ret.tireStiffnessFactor)
return ret
def apply(self, c, now_nanos=None, *, startup_keepalive=False): def apply(self, c, now_nanos=None, *, startup_keepalive=False):
if startup_keepalive: if startup_keepalive:
@@ -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 from opendbc.car.gm.values import CAR, DBC, is_bolt_euv_longitudinal
def original_demand(cp, active, speed, accel, state, resume, pitch): def original_demand(cp, active, speed, accel, state, resume, pitch, *, standstill=False):
# Original 6cae0ce, ordinary non-Volt camera path; default LongPitch on. # Original 6cae0ce camera path, with the hold demand as a floor while rolling.
if not active: if not active:
return 5650, 0 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 return 5650, 25
grade = math.sin(pitch) * 9.81 if speed > 0.25 else 0.0 grade = math.sin(pitch) * 9.81 if speed > 0.25 else 0.0
if grade > 0 and accel > 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]))) switch = int(round(np.interp(speed, [0.5, 10.0], [6150, 5610])))
brake_accel = min((torque - switch) / (radius * cp.mass), 0.0) brake_accel = min((torque - switch) / (radius * cp.mass), 0.0)
brake = int(round(np.interp(brake_accel, [-4.0, 0.0], [400, 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 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, 12., 1., 'pid', False, False, 0.),
(True, True, 7., -1.5, 'pid', False, False, -0.04)] (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, 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., 1., 'stopping', True, True, 0.),
(True, True, 0., 0.5, 'starting', True, True, 0.), (True, True, 0., 0.5, 'starting', True, True, 0.),
(True, True, 0.3, 0.5, 'starting', True, False, 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: if not alpha or frame % 4:
self.assertFalse(actual) self.assertFalse(actual)
continue 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') 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(actual, expected, (alpha, alignment, phase, frame))
self.assertEqual((controller.apply_gas, controller.apply_brake), (raw - 6150, brake)) self.assertEqual((controller.apply_gas, controller.apply_brake), (raw - 6150, brake))
@@ -50,9 +50,10 @@ class TestBoltFactoryAcc(unittest.TestCase):
ci = CarInterface(cp) ci = CarInterface(cp)
packer = CANPacker(DBC[cp.carFingerprint][Bus.pt]) packer = CANPacker(DBC[cp.carFingerprint][Bus.pt])
setup(cp) 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 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 now = 1_000_000_000 + tick * 40_000_000
out, sources = feed(ci, packer, now, counter=tick % 4, speed=speed) out, sources = feed(ci, packer, now, counter=tick % 4, speed=speed)
sources.append(packer.make_can_msg('ASCMActiveCruiseControlStatus', 2, {'ACCCruiseState': 3})) 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, control = structs.CarControl(enabled=True, longActive=cp.openpilotLongitudinalControl,
orientationNED=[0., pitch, 0.]) orientationNED=[0., pitch, 0.])
control.actuators.accel = accel control.actuators.accel = accel
control.actuators.longControlState = structs.CarControl.Actuators.LongControlState.pid control.actuators.longControlState = state
ci.CC.frame = tick * 4 ci.CC.frame = tick * 4
_, messages = ci.apply(control.as_reader(), now) _, messages = ci.apply(control.as_reader(), now)
long_messages = [m for m in messages if m[0] in (0x2CB, 0x315, 0x2CD)] 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)) self.assertFalse(any(m[0] in (0x200, 0x1F5, 0xBD) for m in messages))
if cp.openpilotLongitudinalControl: if cp.openpilotLongitudinalControl:
raw, brake = original_demand(cp, True, out.vEgo, accel, 'pid', False, pitch) raw, brake = original_demand(cp, True, out.vEgo, accel, state, False, pitch, standstill=out.standstill)
self.assertEqual(long_messages, original_frames(raw, brake, tick % 4, True, False)) 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: for message in long_messages:
self.assertTrue(native('tx', message, now // 1000), hex(message[0])) self.assertTrue(native('tx', message, now // 1000), hex(message[0]))
else: else:
@@ -337,6 +337,13 @@ class TestBoltPedalMessages(unittest.TestCase):
self.assertTrue(state.pedal_sensor_healthy, gas) self.assertTrue(state.pedal_sensor_healthy, gas)
self.assertEqual(out.gasPressed, gas > 23., 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})): 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, parsers[Bus.pt].update([(1_000_000_000 + counter * 20_000_000,
[self.sensor(packer, 30., counter, **kwargs)])]) [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,31 @@
from unittest.mock import patch
import pytest
from opendbc.car import car_helpers, gen_empty_fingerprint, scale_rot_inertia, structs
from opendbc.car.gm.values import CAR
from opendbc.car.vin import VIN_UNKNOWN
@pytest.mark.parametrize('candidate,vin,xl', [
(CAR.GMC_YUKON_CC, '1GKS2GKC0JR000001', True),
(CAR.GMC_YUKON_CC, '1GKS2BKC0JR000001', False),
(CAR.GMC_YUKON_CC, '1GKS2GKC0KR000001', False),
(CAR.GMC_YUKON_CC, VIN_UNKNOWN, False),
(CAR.GMC_YUKON, '1GKS2GKC0JR000001', False),
(CAR.BUICK_LACROSSE_ASCM_19US, '1GKS2GKC0JR000001', False),
])
def test_manual_profile_retains_its_control_config_with_vin_geometry(candidate, vin, xl):
fp = gen_empty_fingerprint()
with patch.object(car_helpers, 'fingerprint', return_value=(None, fp, vin, [], structs.CarParams.FingerprintSource.can, True)):
cp = car_helpers.get_car(lambda **_: [], lambda _: None, lambda _: None, False, True, forced_candidate=candidate).CP
assert cp.carFingerprint == candidate and cp.fingerprintSource == structs.CarParams.FingerprintSource.fixed
baseline = car_helpers.interfaces[candidate].get_params(candidate, fp, [], False, True, False, auto_pedal=False)
assert cp.wheelbase == pytest.approx(3.302 if xl else baseline.wheelbase)
assert cp.centerToFront == pytest.approx(cp.wheelbase * candidate.config.specs.centerToFrontRatio)
assert cp.rotationalInertia == pytest.approx(scale_rot_inertia(cp.mass, cp.wheelbase))
assert cp.lateralTuning.to_dict() == baseline.lateralTuning.to_dict()
assert cp.safetyConfigs[0].to_dict() == baseline.safetyConfigs[0].to_dict()
assert cp.openpilotLongitudinalControl == baseline.openpilotLongitudinalControl
assert cp.steerRatio == baseline.steerRatio
@@ -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) 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 @cached_config
def _bolt_pedal_profile(cp, *, stock_only=False): def _bolt_pedal_profile(cp, *, stock_only=False):
"""Exact selected interceptor profile, including its startup authority reduction.""" """Exact selected interceptor profile, including its startup authority reduction."""
@@ -1,3 +1,5 @@
import math
import numpy as np import numpy as np
from opendbc.car import ACCEL_MAX_TAKEOFF 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.bosch_longitudinal import BoschLongitudinal, qualified as bosch_long_qualified
from opendbc.car.honda.values import CAR, CruiseButtons, HondaFlags, CarControllerParams from opendbc.car.honda.values import CAR, CruiseButtons, HondaFlags, CarControllerParams
from opendbc.car.interfaces import CarControllerBase 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 VisualAlert = structs.CarControl.HUDControl.VisualAlert
LongCtrlState = structs.CarControl.Actuators.LongControlState LongCtrlState = structs.CarControl.Actuators.LongControlState
SteerControlType = structs.CarParams.SteerControlType
def compute_gb_honda_bosch(accel, speed): def compute_gb_honda_bosch(accel, speed):
@@ -120,6 +125,54 @@ class CarController(CarControllerBase):
self.brake = 0.0 self.brake = 0.0
self.last_torque = 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): def update(self, CC, CS, now_nanos):
_projection = self.learning_projection_observer _projection = self.learning_projection_observer
if _projection is not None: if _projection is not None:
@@ -176,7 +229,12 @@ class CarController(CarControllerBase):
can_sends.append(make_tester_present_msg(0x18DAB0F1, 1, suppress_response=True)) can_sends.append(make_tester_present_msg(0x18DAB0F1, 1, suppress_response=True))
# Send steering command. # 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: if _projection is not None:
_projection.emit('honda.STEERING_CONTROL', apply_torque, CC.latActive, can_sends[-1]) _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.brake = self.brake
new_actuators.torque = self.last_torque new_actuators.torque = self.last_torque
new_actuators.torqueOutputCan = apply_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 self.frame += 1
if _projection is not None: 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 from opendbc.can.dbc import DBC as CANDBC
TransmissionType = structs.CarParams.TransmissionType TransmissionType = structs.CarParams.TransmissionType
SteerControlType = structs.CarParams.SteerControlType
ButtonType = structs.CarState.ButtonEvent.Type ButtonType = structs.CarState.ButtonEvent.Type
BUTTONS_DICT = {CruiseButtons.RES_ACCEL: ButtonType.accelCruise, CruiseButtons.DECEL_SET: ButtonType.decelCruise, BUTTONS_DICT = {CruiseButtons.RES_ACCEL: ButtonType.accelCruise, CruiseButtons.DECEL_SET: ButtonType.decelCruise,
@@ -120,6 +121,16 @@ class CarState(CarStateBase):
ret.steerFaultPermanent = False ret.steerFaultPermanent = False
ret.steerFaultTemporary = 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 # 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 # 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): 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.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 # 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} (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() observed = set()
for packet in packets: for packet in packets:
for frame in packet: for frame in packet:
key = (frame.src, frame.address) key = (frame.src, frame.address)
if key in NORMAL_BUS_LAYOUT: if key in layout:
if (len(frame.dat) != NORMAL_BUS_LAYOUT[key] or if (len(frame.dat) != layout[key] or
honda_checksum(frame.address, None, frame.dat) != frame.dat[-1] & 0xF): honda_checksum(frame.address, None, frame.dat) != frame.dat[-1] & 0xF):
return False return False
observed.add(key) 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 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 = { 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, "STEER_TORQUE_REQUEST": lkas_active,
} }
if angle_arm is not None:
values["STEER_CONTROL_ARM"] = angle_arm
if tja_control: if tja_control:
values["STEER_DOWN_TO_ZERO"] = lkas_active 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.common.conversions import Conversions as CV
from opendbc.car.disable_ecu import disable_ecu from opendbc.car.disable_ecu import disable_ecu
from opendbc.car.honda.hondacan import CanBus 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.carcontroller import CarController
from opendbc.car.honda.carstate import CarState from opendbc.car.honda.carstate import CarState
from opendbc.car.honda.radar_interface import RadarInterface from opendbc.car.honda.radar_interface import RadarInterface
@@ -100,7 +102,12 @@ class CarInterface(CarInterfaceBase):
ret.longitudinalTuning.kiV = [1.2, 0.8, 0.5] 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] 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( eps_modified = bool(modified_eps) and all(
fw.address == 0x18DA30F1 and fw.subAddress == 0 and fw.address == 0x18DA30F1 and fw.subAddress == 0 and
fw.fwVersion in MODIFIED_EPS_FW.get(candidate, ()) for fw in eps_observations) 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: 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]]) 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: elif candidate == CAR.HONDA_ACCORD_11G:
ret.longitudinalActuatorDelay = 0.05 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 # 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 # everything that depends only on this module is computed once, and its flag
# tests use plain ints: IntFlag operators cost microseconds each in Python. # 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 | _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 _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}} 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) _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) safety.safetyModel == _HONDA_NIDEC and safety.safetyParam == expected)
if fingerprint in CLASSIC_BOSCH and flags & _BOSCH and not flags & _BOSCH_RADARLESS: if fingerprint in CLASSIC_BOSCH and flags & _BOSCH and not flags & _BOSCH_RADARLESS:
expected = int(bool(flags & _BOSCH_ALT_BRAKE)) 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: if cp.openpilotLongitudinalControl:
expected |= int(HondaSafetyFlags.BOSCH_LONG) expected |= int(HondaSafetyFlags.BOSCH_LONG)
if fingerprint == CAR.ACURA_RDX_3G: 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 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)]) 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 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 import json
from pathlib import Path from pathlib import Path
from types import SimpleNamespace
import unittest import unittest
from unittest.mock import patch from unittest.mock import patch
@@ -33,6 +34,32 @@ class TestHondaNormalDiscovery(unittest.TestCase):
generic_query.assert_not_called() generic_query.assert_not_called()
self.assertIsNone(actual[0]) 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): def test_incomplete_or_invalid_traffic_cannot_select_honda(self):
from opendbc.car.honda.discovery import normal_bus_topology from opendbc.car.honda.discovery import normal_bus_topology
frames = recorded_frames() frames = recorded_frames()
+74
View File
@@ -1,11 +1,14 @@
from dataclasses import dataclass, field from dataclasses import dataclass, field
from enum import Enum, IntFlag from enum import Enum, IntFlag
import numpy as np
from opendbc.car import Bus, CarSpecs, DbcDict, PlatformConfig, Platforms, structs, uds from opendbc.car import Bus, CarSpecs, DbcDict, PlatformConfig, Platforms, structs, uds
from opendbc.car.common.conversions import Conversions as CV from opendbc.car.common.conversions import Conversions as CV
from opendbc.car.docs_definitions import CarFootnote, CarHarness, CarDocs, CarParts, Column 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.fw_query_definitions import FwQueryConfig, Request, StdQueries, p16
from opendbc.car.honda.firmware_validation import validate_fw_match 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 Ecu = structs.CarParams.Ecu
VisualAlert = structs.CarControl.HUDControl.VisualAlert VisualAlert = structs.CarControl.HUDControl.VisualAlert
@@ -41,6 +44,27 @@ class CarControllerParams:
STEER_DELTA_DOWN = 3 STEER_DELTA_DOWN = 3
STEER_GLOBAL_MIN_SPEED = 3 * CV.MPH_TO_MS 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): def __init__(self, CP):
self.BOSCH_GAS_LOOKUP_BP = list(type(self).BOSCH_GAS_LOOKUP_BP) 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, gas_max = {CAR.HONDA_CIVIC_BOSCH: 750, CAR.HONDA_ODYSSEY_5G_MMR: 2000,
@@ -92,6 +116,7 @@ class HondaSafetyFlags(IntFlag):
RADARLESS = 8 RADARLESS = 8
BOSCH_CANFD = 16 BOSCH_CANFD = 16
BOSCH_CANFD_MVL = 64 BOSCH_CANFD_MVL = 64
ACCORD_ANGLE = 4096
CLASSIC_LONG_AOL = 2048 # Exact marked DEBUG classic Bosch alpha owner. CLASSIC_LONG_AOL = 2048 # Exact marked DEBUG classic Bosch alpha owner.
ALT_RADAR_AOL = 1024 # Exact marked DEBUG alpha owner; physical EPS/gear token. ALT_RADAR_AOL = 1024 # Exact marked DEBUG alpha owner; physical EPS/gear token.
NIDEC_PEDAL_AOL = 512 # Model1 only; distinct from model20 STOCK_TJA. NIDEC_PEDAL_AOL = 512 # Model1 only; distinct from model20 STOCK_TJA.
@@ -121,6 +146,55 @@ class HondaFlags(IntFlag):
BOSCH_TJA_CONTROL = 4096 BOSCH_TJA_CONTROL = 4096
EPS_MODIFIED = 8192 EPS_MODIFIED = 8192
GAS_INTERCEPTOR = 16384 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 # Car button codes
@@ -186,7 +186,7 @@ class CANFDLfaStatus:
return True return True
return 0 < self.popup_last_applied_ns <= now_ns <= self.popup_last_applied_ns + DISPLAY_RELEASE_NS 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) body = self.current(now_ns)
eps_fresh = 0 < self.eps_observed_ns <= now_ns and now_ns - self.eps_observed_ns <= MAX_AGE_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 indication = ((body[4] >> 6) | ((body[5] & 1) << 2)) if body is not None else 7
@@ -198,7 +198,13 @@ class CANFDLfaStatus:
if qualified_warning: if qualified_warning:
self.ccnc_last_owned_ns = now_ns self.ccnc_last_owned_ns = now_ns
return True 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): def last_fault(self):
body = self.body 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)) 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 CARNIVAL_LONG_AOL_WORD = 0x28B4
LONG_AOL_WORDS = frozenset((CARNIVAL_LONG_AOL_WORD, 0x080D, 0x0815, 0x0895, 0x2815, 0x2895)) | SPORTAGE_LONG_AOL_WORDS 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)) CCNC_LONG_AOL_WORDS = frozenset((0x0C0C, 0x0C0E, 0x0C2C, 0x0C2E))
LONG_EV_CARS = frozenset((CAR.HYUNDAI_IONIQ_5, CAR.HYUNDAI_KONA_EV_2ND_GEN)) LONG_EV_CARS = frozenset((CAR.HYUNDAI_IONIQ_5, CAR.HYUNDAI_KONA_EV_2ND_GEN))
LONG_AOL_WORDS |= CCNC_LONG_AOL_WORDS KONA_IDLE_AOL_WORD = 0x1C0C
INDEPENDENT_LONG_BUTTON_CARS = LONG_EV_CARS | CCNC_LONG_CARS | { LONG_AOL_WORDS |= CCNC_LONG_AOL_WORDS | {KONA_IDLE_AOL_WORD}
CAR.KIA_EV6, CAR.HYUNDAI_IONIQ_6, CAR.GENESIS_GV70_ELECTRIFIED_1ST_GEN, GENERIC_HDA2_CARS = frozenset((
CAR.GENESIS_G80_2ND_GEN_FL,
CAR.HYUNDAI_IONIQ_5_N,
CAR.HYUNDAI_KONA_2ND_GEN,
CAR.HYUNDAI_KONA_HEV_2ND_GEN,
CAR.HYUNDAI_SANTA_CRUZ_1ST_GEN,
CAR.HYUNDAI_SANTA_CRUZ_2025,
CAR.HYUNDAI_SONATA_2024,
CAR.HYUNDAI_SONATA_HEV_2024,
CAR.HYUNDAI_STARIA_4TH_GEN,
CAR.HYUNDAI_TUCSON_2025,
CAR.HYUNDAI_TUCSON_4TH_GEN,
CAR.HYUNDAI_TUCSON_HEV_2025,
CAR.HYUNDAI_TUCSON_PHEV_2025,
CAR.KIA_CARNIVAL_2025,
CAR.KIA_CARNIVAL_HEV_4TH_GEN,
CAR.KIA_K4_2025,
CAR.KIA_K5_2025,
CAR.KIA_K8_HEV_1ST_GEN,
CAR.KIA_NIRO_EV_2ND_GEN,
CAR.KIA_NIRO_HEV_2ND_GEN,
CAR.KIA_SORENTO_2024,
CAR.KIA_SPORTAGE_5TH_GEN,
))
INDEPENDENT_LONG_BUTTON_CARS = LONG_EV_CARS | GENERIC_HDA2_CARS | {
CAR.KIA_EV6, CAR.KIA_NIRO_EV_2ND_GEN, CAR.HYUNDAI_IONIQ_6, CAR.GENESIS_GV70_ELECTRIFIED_1ST_GEN,
CAR.GENESIS_GV60_EV_1ST_GEN, CAR.KIA_SPORTAGE_5TH_GEN, CAR.KIA_CARNIVAL_2025, 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): def qualified_long(cp, *, marked_only=False):
if cp.carFingerprint == CAR.KIA_EV6 and int(cp.flags) & _FLAG_CANFD_LKA_STEER_MSG: 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 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 cp.carFingerprint in (CAR.KIA_EV6, CAR.GENESIS_GV60_EV_1ST_GEN, CAR.HYUNDAI_IONIQ_6):
if word != 0x09: if word != 0x09:
return False 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: elif cp.carFingerprint == CAR.KIA_SPORTAGE_5TH_GEN:
if word is None or word | 0x804 not in SPORTAGE_LONG_AOL_WORDS: if word is None or word | 0x804 not in SPORTAGE_LONG_AOL_WORDS:
return False return False
elif cp.carFingerprint == CAR.KIA_CARNIVAL_2025: elif cp.carFingerprint == CAR.KIA_CARNIVAL_2025:
if word != 0x20B0: if word != 0x20B0:
return False 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): elif word not in (0x11, 0x91) and not (cp.carFingerprint == CAR.HYUNDAI_IONIQ_5 and word == 0x09):
return False return False
raw = int(cp.safetyConfigs[config_index(cp)].safetyParam) raw = int(cp.safetyConfigs[config_index(cp)].safetyParam)
@@ -155,6 +196,8 @@ def qualified_long(cp, *, marked_only=False):
if not raw & 0x2000: if not raw & 0x2000:
return False return False
raw &= ~0x2000 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 ( return (raw == (word | 0x804) and cp.alternativeExperience == 32) or (
not marked_only and raw == (word | 4) and cp.alternativeExperience == 0 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_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.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 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.g90_longitudinal import G90LongitudinalPolicy
from opendbc.car.hyundai.gv70_longitudinal import is_gv70, scc_request, suppress_stock_cancel 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 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.apply_angle_last = 0.0
self.angle_gain_last = 0.0 self.angle_gain_last = 0.0
self.angle_fault_driver_override = False self.angle_fault_driver_override = False
self.stock_angle_lka_active = False
self.angle_tx_recovery = (AngleTxRecovery(0xCB, self.CAN.ECAN) 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 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 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.apply_torque_last = 0
self.car_fingerprint = CP.carFingerprint self.car_fingerprint = CP.carFingerprint
self.last_button_frame = 0 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.cancel_counter = 0
self.blended_longitudinal = None self.blended_longitudinal = None
self.blended_previous_lateral = False self.blended_previous_lateral = False
self.blended_disengage_frame = None 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_161_ts_ns = 0
self.last_ccnc_162_ts_ns = 0 self.last_ccnc_162_ts_ns = 0
self.last_ccnc_now_ns = 0 self.last_ccnc_now_ns = 0
@@ -170,6 +178,7 @@ class CarController(CarControllerBase):
int(CP.safetyConfigs[-1].safetyParam) in (0x0811, 0x0891)) 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.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.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.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_dash_icons = CanFDDashIcons() if classic_aol_dash_enabled(CP) else None
self.classic_lfa_icon = None self.classic_lfa_icon = None
@@ -195,7 +204,8 @@ class CarController(CarControllerBase):
if _projection is not None: if _projection is not None:
_projection.begin(CC.actuators.torque, self.frame) _projection.begin(CC.actuators.torque, self.frame)
actuators = CC.actuators actuators = CC.actuators
if self.CP.carFingerprint == CAR.KIA_EV6_2025 and self.CP.dashcamOnly: if (self.CP.dashcamOnly and self.CP.carFingerprint in
(CAR.KIA_EV6_2025, CAR.HYUNDAI_KONA_EV_2023_NON_SCC, CAR.HYUNDAI_I30_2026)):
return actuators.as_builder(), [] return actuators.as_builder(), []
hud_control = CC.hudControl hud_control = CC.hudControl
# Card finalizes the AOL safety marker after CarInterface constructs us. # Card finalizes the AOL safety marker after CarInterface constructs us.
@@ -294,6 +304,16 @@ class CarController(CarControllerBase):
can_sends.extend(self.create_can_msgs(apply_steer_req, apply_torque, torque_fault, set_speed_in_units, accel, 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)) 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 = actuators.as_builder()
new_actuators.torque = apply_torque / self.params.STEER_MAX new_actuators.torque = apply_torque / self.params.STEER_MAX
new_actuators.torqueOutputCan = apply_torque new_actuators.torqueOutputCan = apply_torque
@@ -338,9 +358,15 @@ class CarController(CarControllerBase):
sys_warning, sys_state, CC.enabled, hud_control.leftLaneVisible, hud_control.rightLaneVisible, sys_warning, sys_state, CC.enabled, hud_control.leftLaneVisible, hud_control.rightLaneVisible,
left_lane_warning, right_lane_warning, {}, include_alerts=False, counter_mod=0xF, 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)) 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 if CS.out.canValid and not CS.out.canTimeout and CS.blended_camera_current:
CS.blended_camera_current): camera_counter = CS.lfa_block_msg["COUNTER"]
can_sends.append(hyundaicanfd.create_suppress_lfa(self.packer, self.CAN, CS.lfa_block_msg, False)) 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: else:
_projection_packet_index = len(can_sends) if _projection is not None else 0 _projection_packet_index = len(can_sends) if _projection is not None else 0
can_sends.extend(hyundaican.create_lkas11_can_canfd_blended( can_sends.extend(hyundaican.create_lkas11_can_canfd_blended(
@@ -520,7 +546,9 @@ class CarController(CarControllerBase):
angle_active, self.params, self.angle_vm) angle_active, self.params, self.angle_vm)
self.angle_gain_last = angle_torque_reduction_gain(CS.out.steeringTorque, CS.out.vEgoRaw, self.angle_gain_last = angle_torque_reduction_gain(CS.out.steeringTorque, CS.out.vEgoRaw,
angle_active, self.angle_gain_last) 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( can_sends.extend(
hyundaicanfd.create_angle_steering_messages( hyundaicanfd.create_angle_steering_messages(
self.packer, self.packer,
@@ -534,6 +562,7 @@ class CarController(CarControllerBase):
CS.out.steeringAngleDeg, CS.out.steeringAngleDeg,
) )
) )
self.stock_angle_lka_active = stock_angle_handoff and angle_active
else: else:
steering_status_active = CC.enabled steering_status_active = CC.enabled
if ((self.CP.carFingerprint == CAR.KIA_CARNIVAL_2025 and self.CP.safetyConfigs[-1].safetyParam == 0x28B4) or if ((self.CP.carFingerprint == CAR.KIA_CARNIVAL_2025 and self.CP.safetyConfigs[-1].safetyParam == 0x28B4) or
@@ -552,17 +581,29 @@ class CarController(CarControllerBase):
stock_popup_owned = stock_source.owns_disengage_popup(apply_steer_req, clock_boot_ns(), healthy=display_healthy, stock_popup_owned = stock_source.owns_disengage_popup(apply_steer_req, clock_boot_ns(), healthy=display_healthy,
qualified_warning=stock_owned_status) qualified_warning=stock_owned_status)
if ccnc_non_lka: if ccnc_non_lka:
stock_ccnc_owned = stock_source.owns_ccnc_fault_status(clock_boot_ns(), healthy=display_healthy, stock_ccnc_owned = stock_source.owns_ccnc_fault_status(clock_boot_ns(), display_sample_ns=CS.ccnc_162_ts_ns,
qualified_warning=stock_owned_status) healthy=display_healthy, qualified_warning=stock_owned_status)
damping_source = getattr(CS, "stock_lkas_damping", None) damping_source = getattr(CS, "stock_lkas_damping", None)
can_sends.extend(hyundaicanfd.create_steering_messages(self.packer, self.CP, self.CAN, kona_handoff = (self.CP.carFingerprint == CAR.HYUNDAI_KONA_2ND_GEN and
steering_status_active, apply_steer_req, apply_torque, self.CP.safetyConfigs[-1].safetyParam == KONA_IDLE_AOL_WORD)
stock_lfa=stock_lfa, stock_lfa_faults=stock_faults, lfa_counter = None
stock_lfa_owned_status=stock_owned_status, if kona_handoff:
stock_lkas_damping=(damping_source.current_damping(clock_boot_ns()) if (CC.enabled or CC.latActive) and stock_lfa is not None:
if damping_source is not None else None))) if stock_lfa[2] != self.kona_last_lfa_counter:
if _projection is not None: lfa_counter = stock_lfa[2]
_projection.emit('hyundai.CANFD_TORQUE', apply_torque, apply_steer_req, can_sends[-1]) 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 # prevent LFA from activating on LKA steering cars by sending "no lane lines detected" to ADAS ECU
if ( if (
@@ -587,13 +628,15 @@ class CarController(CarControllerBase):
now_nanos - min(CS.ccnc_161_ts_ns, CS.ccnc_162_ts_ns) <= 50_000_000 and now_nanos - min(CS.ccnc_161_ts_ns, CS.ccnc_162_ts_ns) <= 50_000_000 and
abs(CS.ccnc_161_ts_ns - CS.ccnc_162_ts_ns) <= 50_000_000) abs(CS.ccnc_161_ts_ns - CS.ccnc_162_ts_ns) <= 50_000_000)
if fresh_pair: if fresh_pair:
show_cruise = CS.out.cruiseState.available and (not kona_handoff or CC.enabled)
support_current = (CS.ccnc_1b5_ts_ns > 0 and CS.ccnc_1b5_ts_ns <= now_nanos and support_current = (CS.ccnc_1b5_ts_ns > 0 and CS.ccnc_1b5_ts_ns <= now_nanos and
abs(CS.ccnc_1b5_ts_ns - pair_ts) <= 50_000_000) abs(CS.ccnc_1b5_ts_ns - pair_ts) <= 50_000_000)
can_sends.extend(hyundaicanfd.create_ccnc(self.packer, self.CAN, self.CP.openpilotLongitudinalControl, can_sends.extend(hyundaicanfd.create_ccnc(self.packer, self.CAN, self.CP.openpilotLongitudinalControl,
CC.enabled, hud_control, CC.leftBlinker, CC.rightBlinker, CC.enabled, hud_control, CC.leftBlinker, CC.rightBlinker,
CS.ccnc_161.copy(), CS.ccnc_162.copy(), CS.ccnc_1b5 if support_current else None, CS.ccnc_161.copy(), CS.ccnc_162.copy(), CS.ccnc_1b5 if support_current else None,
CS.is_metric, CS.out, CS.out.cruiseState.available, CC.latActive, CS.is_metric, CS.out, show_cruise, CC.latActive,
owned_lfa_status=(stock_ccnc_owned if self.ccnc_fault_ownership_required else None))) owned_lfa_status=(stock_ccnc_owned if self.ccnc_fault_ownership_required else None),
owned_cruise_status=kona_handoff))
self.last_ccnc_161_ts_ns = CS.ccnc_161_ts_ns self.last_ccnc_161_ts_ns = CS.ccnc_161_ts_ns
self.last_ccnc_162_ts_ns = CS.ccnc_162_ts_ns self.last_ccnc_162_ts_ns = CS.ccnc_162_ts_ns
else: else:
@@ -653,7 +696,12 @@ class CarController(CarControllerBase):
lead = (self.torque_ev_lead_inputs.update(CS.torque_ev_camera_lead, hud_control.leadVisible, now_nanos) lead = (self.torque_ev_lead_inputs.update(CS.torque_ev_camera_lead, hud_control.leadVisible, now_nanos)
if self.torque_ev_lead_inputs is not None else if self.torque_ev_lead_inputs is not None else
fallback_lead(CS.torque_ev_camera_lead, hud_control.leadVisible, self.torque_ev_floor_boot_ns)) fallback_lead(CS.torque_ev_camera_lead, hud_control.leadVisible, self.torque_ev_floor_boot_ns))
acc_options = torque_ev_scc_options(CS.out.cruiseState.available, CC.actuators.longControlState, lead) acc_options = torque_ev_scc_options(CS.out.cruiseState.available and (not kona_handoff or CC.enabled),
CC.actuators.longControlState, lead)
if (kona_handoff and CC.longActive and not CC.cruiseControl.override and stopping and
not (CS.out.standstill or CS.out.brakePressed or CS.out.gasPressed or hud_control.leadVisible or lead.visible) and
0.0 < CS.out.vEgo < 3.0 and self.CP.stopAccel < accel < 0.0 and accel >= self.accel_last - 0.02):
acc_options["jerk_lower"] = 1.2
elif is_gv70(self.CP): elif is_gv70(self.CP):
request = scc_request(CC.enabled, CC.cruiseControl.override, stopping, accel, self.accel_last) request = scc_request(CC.enabled, CC.cruiseControl.override, stopping, accel, self.accel_last)
accel = request.accel accel = request.accel
+10 -1
View File
@@ -51,7 +51,7 @@ BUTTONS_DICT = {Buttons.RES_ACCEL: ButtonType.accelCruise, Buttons.SET_DECEL: Bu
def get_non_scc_cruise_signals(flags: int, car=None) -> tuple[str, str, str, str, str, str]: def get_non_scc_cruise_signals(flags: int, car=None) -> tuple[str, str, str, str, str, str]:
if car == CAR.KIA_RAY_EV: if car in (CAR.KIA_RAY_EV, CAR.HYUNDAI_KONA_EV_2023_NON_SCC):
return "LABEL11", "CC_React", "LABEL11", "CC_Engaged", "E_EMS11", "Cruise_Limit_Target" return "LABEL11", "CC_React", "LABEL11", "CC_Engaged", "E_EMS11", "Cruise_Limit_Target"
if flags & HyundaiFlags.EV: if flags & HyundaiFlags.EV:
return "LABEL11", "CC_React", "EMS12", "ACC_ACT", "E_EMS11", "Cruise_Limit_Target" return "LABEL11", "CC_React", "EMS12", "ACC_ACT", "E_EMS11", "Cruise_Limit_Target"
@@ -150,6 +150,7 @@ class CarState(CarStateBase):
self.params = CarControllerParams(CP) self.params = CarControllerParams(CP)
self.blended_camera_current = False self.blended_camera_current = False
self.blended_camera_updated = False
self.ray_pedal_valid = False self.ray_pedal_valid = False
self.ray_pedal_state = 5 self.ray_pedal_state = 5
@@ -259,6 +260,8 @@ class CarState(CarStateBase):
available_msg, available_sig, enabled_msg, enabled_sig, speed_msg, speed_sig = get_non_scc_cruise_signals(self.CP.flags, self.CP.carFingerprint) available_msg, available_sig, enabled_msg, enabled_sig, speed_msg, speed_sig = get_non_scc_cruise_signals(self.CP.flags, self.CP.carFingerprint)
ret.cruiseState.available = cp.vl[available_msg][available_sig] != 0 ret.cruiseState.available = cp.vl[available_msg][available_sig] != 0
ret.cruiseState.enabled = cp.vl[enabled_msg][enabled_sig] != 0 ret.cruiseState.enabled = cp.vl[enabled_msg][enabled_sig] != 0
if self.CP.carFingerprint == CAR.HYUNDAI_KONA_EV_2023_NON_SCC:
ret.cruiseState.enabled &= ret.cruiseState.available
ret.cruiseState.standstill = False ret.cruiseState.standstill = False
ret.cruiseState.nonAdaptive = False ret.cruiseState.nonAdaptive = False
ret.cruiseState.speed = cp.vl[speed_msg][speed_sig] * speed_conv ret.cruiseState.speed = cp.vl[speed_msg][speed_sig] * speed_conv
@@ -347,6 +350,7 @@ class CarState(CarStateBase):
self.lfa_block_msg = copy.copy(cp_cam.vl["CAM_0x2a4"]) self.lfa_block_msg = copy.copy(cp_cam.vl["CAM_0x2a4"])
from opendbc.car.hyundai.blended_stock_aol import camera_current from opendbc.car.hyundai.blended_stock_aol import camera_current
self.blended_camera_current = camera_current(cp_cam) self.blended_camera_current = camera_current(cp_cam)
self.blended_camera_updated = bool(cp_cam.vl_all["CAM_0x2a4"]["COUNTER"])
self.lkas11 = {} self.lkas11 = {}
else: else:
self.msg_364 = copy.copy(cp_cam.vl["ALERTS_364"]) self.msg_364 = copy.copy(cp_cam.vl["ALERTS_364"])
@@ -413,6 +417,11 @@ class CarState(CarStateBase):
ret.buttonEvents = button_events ret.buttonEvents = button_events
ret.blockPcmEnable = not self.recent_button_interaction() ret.blockPcmEnable = not self.recent_button_interaction()
if self.CP.carFingerprint == CAR.HYUNDAI_KONA_EV_2023_NON_SCC:
set_or_resume = next((not main and button in (Buttons.SET_DECEL, Buttons.RES_ACCEL)
for button, main in zip(reversed(self.cruise_buttons), reversed(self.main_buttons), strict=True)
if main or button in ENABLE_BUTTONS), False)
ret.blockPcmEnable = not set_or_resume or ret.brakePressed or ret.gasPressed
# low speed steer alert hysteresis logic (only for cars with steer cut off above 10 m/s) # low speed steer alert hysteresis logic (only for cars with steer cut off above 10 m/s)
if ret.vEgo < (self.CP.minSteerSpeed + 2.) and self.CP.minSteerSpeed > 10.: if ret.vEgo < (self.CP.minSteerSpeed + 2.) and self.CP.minSteerSpeed > 10.:
+37 -4
View File
@@ -1,6 +1,10 @@
import time import time
from itertools import product from itertools import product
from opendbc.car.hyundai.values import CAR
from opendbc.car.structs import CarParams
from opendbc.car.vin import is_valid_vin
NORMAL_BUS_LAYOUT = {(2, 0x110): 32, (2, 0x362): 32, (1, 0x35): 32, NORMAL_BUS_LAYOUT = {(2, 0x110): 32, (2, 0x362): 32, (1, 0x35): 32,
(1, 0xEA): 24, (1, 0xA0): 24, (1, 0x1A0): 32, (1, 0xEA): 24, (1, 0xA0): 24, (1, 0x1A0): 32,
@@ -22,11 +26,39 @@ 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} (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, 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, (0, 0x35): 32, (0, 0x1CF): 8, (0, 0x130): 16,
**{(1, address): 32 for address in range(0x210, 0x220)}} **{(1, address): 32 for address in range(0x210, 0x220)}}
def kona_electric_se_candidate(vin, fingerprint, car_fw):
if not is_valid_vin(vin) or vin[:8] != 'KM8K23AG' or vin[9] != 'P':
return None
layout = {(0, 0x251): 8, (0, 0x371): 8, (0, 0x386): 8, (0, 0x394): 8, (0, 0x4F1): 4,
(0, 0x592): 8, (1, 0x329): 8, (2, 0x340): 8}
if any(fingerprint.get(bus, {}).get(addr) != length for (bus, addr), length in layout.items()):
return None
if any(frames.keys() & {0x420, 0x421} for frames in fingerprint.values()):
return None
ecu = CarParams.Ecu
if any(fw.ecu == ecu.fwdRadar or (fw.address == 0x7D0 and fw.brand == 'hyundai') for fw in car_fw):
return None
observed_fw = {(fw.ecu.raw, fw.address, bytes(fw.fwVersion)) for fw in car_fw
if fw.brand == 'hyundai' and fw.bus == 0 and not fw.subAddress and not fw.logging}
expected_fw = {
(ecu.eps, 0x7D4, b'\xf1\x00OSP MDPS C 1.00 1.02 56310K4261\x00 4OEPC102'),
(ecu.fwdCamera, 0x7C4, b'\xf1\x00OSP LKA AT USA LHD 1.00 1.04 99211-J9200 904'),
}
return CAR.HYUNDAI_KONA_EV_2023_NON_SCC if expected_fw <= observed_fw else None
def _canfd_variant_layouts(): def _canfd_variant_layouts():
layouts = [] layouts = []
originals = (NORMAL_BUS_LAYOUT, HDA1_NORMAL_BUS_LAYOUT, HDA2_NORMAL_BUS_LAYOUT) originals = (NORMAL_BUS_LAYOUT, HDA1_NORMAL_BUS_LAYOUT, HDA2_NORMAL_BUS_LAYOUT)
@@ -59,8 +91,9 @@ def normal_bus_topology(can_recv, *, clock=time.monotonic):
hda2_invalid = False hda2_invalid = False
hda1_observed = {} hda1_observed = {}
hda1_invalid = False hda1_invalid = False
variants_observed = [{} for _ in CANFD_VARIANT_LAYOUTS] alternate_layouts = (*CANFD_VARIANT_LAYOUTS, MIXED_CAN_NORMAL_BUS_LAYOUT)
variants_invalid = [False for _ in CANFD_VARIANT_LAYOUTS] variants_observed = [{} for _ in alternate_layouts]
variants_invalid = [False for _ in alternate_layouts]
for _ in range(24): for _ in range(24):
if clock() >= deadline: if clock() >= deadline:
break break
@@ -76,7 +109,7 @@ def normal_bus_topology(can_recv, *, clock=time.monotonic):
return False return False
original_invalid = True original_invalid = True
received[key] = length received[key] = length
for index, layout in enumerate(CANFD_VARIANT_LAYOUTS): for index, layout in enumerate(alternate_layouts):
if key in layout: if key in layout:
if len(frame.dat) != layout[key]: if len(frame.dat) != layout[key]:
variants_invalid[index] = True variants_invalid[index] = True
@@ -98,6 +131,6 @@ def normal_bus_topology(can_recv, *, clock=time.monotonic):
not hda1_invalid and hda1_observed == HDA1_NORMAL_BUS_LAYOUT)): not hda1_invalid and hda1_observed == HDA1_NORMAL_BUS_LAYOUT)):
return True return True
if any(not invalid and received == layout and (not original_invalid or (2, 0x50) in layout) 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 True
return False return False
@@ -1,6 +1,6 @@
""" AUTO-FORMATTED USING opendbc/car/debug/format_fingerprints.py, EDIT STRUCTURE THERE.""" """ AUTO-FORMATTED USING opendbc/car/debug/format_fingerprints.py, EDIT STRUCTURE THERE."""
from opendbc.car.structs import CarParams from opendbc.car.structs import CarParams
from opendbc.car.hyundai.values import CAR from opendbc.car.hyundai.values import CAR, CARNIVAL_2027_CAMERA_FW
Ecu = CarParams.Ecu Ecu = CarParams.Ecu
@@ -153,10 +153,12 @@ FW_VERSIONS = {
}, },
CAR.KIA_CARNIVAL_2025: { CAR.KIA_CARNIVAL_2025: {
(Ecu.fwdCamera, 0x7c4, None): [ (Ecu.fwdCamera, 0x7c4, None): [
CARNIVAL_2027_CAMERA_FW,
b'\xf1\x00KA4 MFC AT CAN LHD 1.00 1.00 99210-R0700 250324', b'\xf1\x00KA4 MFC AT CAN LHD 1.00 1.00 99210-R0700 250324',
b'\xf1\x00KA4 MFC AT USA LHD 1.00 1.05 99210-R0500 240305', b'\xf1\x00KA4 MFC AT USA LHD 1.00 1.05 99210-R0500 240305',
], ],
(Ecu.fwdRadar, 0x7d0, None): [ (Ecu.fwdRadar, 0x7d0, None): [
b'\xf1\x00KA4_ RDR ----- 1.00 1.02 99110-R0510 ',
b'\xf1\x00KA4_ SCC FHCUP 1.00 1.01 99110-R0510 ', b'\xf1\x00KA4_ SCC FHCUP 1.00 1.01 99110-R0510 ',
b'\xf1\x00KA4_ RDR ----- 1.00 1.01 99110-R0510 ', b'\xf1\x00KA4_ RDR ----- 1.00 1.01 99110-R0510 ',
], ],
@@ -1178,6 +1180,17 @@ FW_VERSIONS = {
b'\xf1\x00PD__ SCC FNCUP 1.01 1.00 96400-G3000 ', b'\xf1\x00PD__ SCC FNCUP 1.01 1.00 96400-G3000 ',
], ],
}, },
CAR.HYUNDAI_I30_2026: {
(Ecu.fwdCamera, 0x7c4, None): [
b'\xf1\x00PD MFC AT EUR LHD 1.00 1.01 99211-G4600 251223',
],
(Ecu.eps, 0x7d4, None): [
b'\xf1\x00PDe MDPS C 1.00 1.00 56300G4BB0 4P3EC100',
],
(Ecu.fwdRadar, 0x7d0, None): [
b'\xf1\x00PDe_ RDR ----- 1.00 1.01 99110-G4500 ',
],
},
CAR.HYUNDAI_ELANTRA_2021: { CAR.HYUNDAI_ELANTRA_2021: {
(Ecu.fwdRadar, 0x7d0, None): [ (Ecu.fwdRadar, 0x7d0, None): [
b'\xf1\x00CN7_ SCC F-CUP 1.00 1.01 99110-AA000 ', b'\xf1\x00CN7_ SCC F-CUP 1.00 1.01 99110-AA000 ',
@@ -1401,6 +1414,7 @@ FW_VERSIONS = {
b'\xf1\x00NX4 FR_CMR AT EUR LHD 1.00 1.00 99211-N9220 14K', b'\xf1\x00NX4 FR_CMR AT EUR LHD 1.00 1.00 99211-N9220 14K',
b'\xf1\x00NX4 FR_CMR AT EUR LHD 1.00 1.00 99211-N9240 14Q', b'\xf1\x00NX4 FR_CMR AT EUR LHD 1.00 1.00 99211-N9240 14Q',
b'\xf1\x00NX4 FR_CMR AT EUR LHD 1.00 2.02 99211-N9000 14E', b'\xf1\x00NX4 FR_CMR AT EUR LHD 1.00 2.02 99211-N9000 14E',
b'\xf1\x00NX4 FR_CMR AT USA LHD 1.00 1.00 99211-CW010 14X',
b'\xf1\x00NX4 FR_CMR AT USA LHD 1.00 1.00 99211-N9210 14G', b'\xf1\x00NX4 FR_CMR AT USA LHD 1.00 1.00 99211-N9210 14G',
b'\xf1\x00NX4 FR_CMR AT USA LHD 1.00 1.00 99211-N9220 14K', b'\xf1\x00NX4 FR_CMR AT USA LHD 1.00 1.00 99211-N9220 14K',
b'\xf1\x00NX4 FR_CMR AT USA LHD 1.00 1.00 99211-N9240 14Q', b'\xf1\x00NX4 FR_CMR AT USA LHD 1.00 1.00 99211-N9240 14Q',
@@ -1,6 +1,7 @@
"""Exact Forte non-SCC AOL identity and physical-button observations.""" """Exact Forte non-SCC AOL identity and physical-button observations."""
from opendbc.car.structs import CarParams from opendbc.car.structs import CarParams
from opendbc.car.hyundai.values import CAR, HyundaiFlags 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_IDS = (CAR.KIA_FORTE_2019_NON_SCC, CAR.KIA_FORTE_2021_NON_SCC)
FORTE_AOL_MARKER = 0x0400 FORTE_AOL_MARKER = 0x0400
@@ -19,8 +20,10 @@ def qualified(cp):
not cp.notCar and not cp.openpilotLongitudinalControl and cp.pcmCruise and 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 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 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. # 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 from typing import Any
import time 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_continuity import ContinuousECUStartup, StartupKeeper
from opendbc.car.hyundai.ecu_startup import Outcome, stock_copy from opendbc.car.hyundai.ecu_startup import Outcome, stock_copy
from opendbc.car.hyundai.radar_hda2_startup import RadarHDA2Startup from opendbc.car.hyundai.radar_hda2_startup import RadarHDA2Startup
from opendbc.car.hyundai.values import CAR, HyundaiFlags, is_blended 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(( EXISTING_OWNERS_OR_DISTINCT_RECEIVERS = frozenset((
CAR.HYUNDAI_KONA_EV_2ND_GEN, CAR.HYUNDAI_KONA_EV_2ND_GEN,
CAR.HYUNDAI_IONIQ_5, CAR.HYUNDAI_IONIQ_5,
@@ -66,6 +66,7 @@ def create_lkas11(packer, frame, CP, apply_torque, steer_req,
if CP.carFingerprint in (CAR.HYUNDAI_SONATA, CAR.HYUNDAI_PALISADE, CAR.KIA_NIRO_EV, CAR.KIA_NIRO_HEV_2021, CAR.KIA_NIRO_PHEV_2022, CAR.HYUNDAI_SANTA_FE, if CP.carFingerprint in (CAR.HYUNDAI_SONATA, CAR.HYUNDAI_PALISADE, CAR.KIA_NIRO_EV, CAR.KIA_NIRO_HEV_2021, CAR.KIA_NIRO_PHEV_2022, CAR.HYUNDAI_SANTA_FE,
CAR.HYUNDAI_IONIQ_EV_2020, CAR.HYUNDAI_IONIQ_PHEV, CAR.KIA_SELTOS, CAR.HYUNDAI_ELANTRA_2021, CAR.GENESIS_G70_2020, CAR.HYUNDAI_IONIQ_EV_2020, CAR.HYUNDAI_IONIQ_PHEV, CAR.KIA_SELTOS, CAR.HYUNDAI_ELANTRA_2021, CAR.GENESIS_G70_2020,
CAR.HYUNDAI_ELANTRA_HEV_2021, CAR.HYUNDAI_SONATA_HYBRID, CAR.HYUNDAI_KONA_EV, CAR.HYUNDAI_KONA_HEV, CAR.HYUNDAI_KONA_EV_2022, CAR.HYUNDAI_ELANTRA_HEV_2021, CAR.HYUNDAI_SONATA_HYBRID, CAR.HYUNDAI_KONA_EV, CAR.HYUNDAI_KONA_HEV, CAR.HYUNDAI_KONA_EV_2022,
CAR.HYUNDAI_KONA_EV_2023_NON_SCC,
CAR.HYUNDAI_SANTA_FE_2022, CAR.KIA_K5_2021, CAR.HYUNDAI_IONIQ_HEV_2022, CAR.HYUNDAI_SANTA_FE_HEV_2022, CAR.HYUNDAI_SANTA_FE_2022, CAR.KIA_K5_2021, CAR.HYUNDAI_IONIQ_HEV_2022, CAR.HYUNDAI_SANTA_FE_HEV_2022,
CAR.HYUNDAI_SANTA_FE_PHEV_2022, CAR.KIA_STINGER_2022, CAR.KIA_K5_HEV_2020, CAR.KIA_CEED, CAR.KIA_XCEED_PHEV, CAR.KIA_CEED_PHEV, CAR.HYUNDAI_SANTA_FE_PHEV_2022, CAR.KIA_STINGER_2022, CAR.KIA_K5_HEV_2020, CAR.KIA_CEED, CAR.KIA_XCEED_PHEV, CAR.KIA_CEED_PHEV,
CAR.HYUNDAI_AZERA_6TH_GEN, CAR.HYUNDAI_AZERA_HEV_6TH_GEN, CAR.HYUNDAI_CUSTIN_1ST_GEN, CAR.HYUNDAI_KONA_2022, CAR.HYUNDAI_AZERA_6TH_GEN, CAR.HYUNDAI_AZERA_HEV_6TH_GEN, CAR.HYUNDAI_CUSTIN_1ST_GEN, CAR.HYUNDAI_KONA_2022,
@@ -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, 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 = { values = {
"LKA_OptUsmSta": 2, "LKA_OptUsmSta": 2,
"LKA_SysIndReq": 2 if enabled else 1, "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} lkas_values = {**values, "Damping_Gain": damping}
ret.append(packer.make_can_msg(lkas_msg, CAN.ACAN, lkas_values)) ret.append(packer.make_can_msg(lkas_msg, CAN.ACAN, lkas_values))
else: else:
if lfa_counter is not None:
values["COUNTER"] = lfa_counter
message = packer.make_can_msg("LFA", CAN.ECAN, values) message = packer.make_can_msg("LFA", CAN.ECAN, values)
source = stock_lfa if stock_lfa is not None else stock_lfa_faults source = stock_lfa if stock_lfa is not None else stock_lfa_faults
if source is not None: if source is not None:
@@ -327,7 +329,7 @@ def create_ioniq6_blindspot_status(counter: int, status: BlindspotStatus, *, bus
# Source-derived CCNC camera display transform; the repository MIT notice applies. # Source-derived CCNC camera display transform; the repository MIT notice applies.
def create_ccnc(packer, CAN, openpilot_longitudinal, enabled, hud, left_blinker, right_blinker, msg_161, msg_162, msg_1b5, def create_ccnc(packer, CAN, openpilot_longitudinal, enabled, hud, left_blinker, right_blinker, msg_161, msg_162, msg_1b5,
is_metric, out, main_cruise_enabled, lfa_icon, *, owned_lfa_status=None): is_metric, out, main_cruise_enabled, lfa_icon, *, owned_lfa_status=None, owned_cruise_status=False):
if owned_lfa_status or (owned_lfa_status is None and lfa_icon): if owned_lfa_status or (owned_lfa_status is None and lfa_icon):
# The host owns lateral; keep unrelated faults and obstruction warnings. # The host owns lateral; keep unrelated faults and obstruction warnings.
for field in ("FAULT_LSS", "FAULT_HDA", "FAULT_DAS", "FAULT_LFA", "FAULT_DAW"): for field in ("FAULT_LSS", "FAULT_HDA", "FAULT_DAS", "FAULT_LFA", "FAULT_DAW"):
@@ -411,6 +413,9 @@ def create_ccnc(packer, CAN, openpilot_longitudinal, enabled, hud, left_blinker,
"DISTANCE_LEAD": 0 if not main_cruise_enabled else 2 if enabled and hud.leadVisible else 1 if hud.leadVisible else 0, "DISTANCE_LEAD": 0 if not main_cruise_enabled else 2 if enabled and hud.leadVisible else 1 if hud.leadVisible else 0,
"DISTANCE_CAR": 0 if not main_cruise_enabled else 2 if enabled else 1, "DISTANCE_CAR": 0 if not main_cruise_enabled else 2 if enabled else 1,
}) })
if owned_cruise_status:
msg_161["SETSPEED"] = msg_161["SETSPEED_HUD"]
msg_161["DISTANCE"] = hud.leadDistanceBars if main_cruise_enabled else 0
msg_162["LEAD"] = 0 if not main_cruise_enabled else 2 if enabled else 1 msg_162["LEAD"] = 0 if not main_cruise_enabled else 2 if enabled else 1
if msg_1b5 is not None: if msg_1b5 is not None:
msg_162["LEAD_DISTANCE"] = msg_1b5["Longitudinal_Distance"] msg_162["LEAD_DISTANCE"] = msg_1b5["Longitudinal_Distance"]
+24 -1
View File
@@ -3,10 +3,11 @@ from opendbc.car.hyundai.ioniq5pe_long_profile import required as pe_long_requir
from opendbc.car.pedal import supported_pedal_detected from opendbc.car.pedal import supported_pedal_detected
from opendbc.car.hyundai.classic_scc_aol import CLASSIC_SCC_IDS from opendbc.car.hyundai.classic_scc_aol import CLASSIC_SCC_IDS
from opendbc.car import Bus, get_safety_config, structs, uds from opendbc.car import Bus, get_safety_config, structs, uds
from opendbc.car.hyundai.discovery import kona_electric_se_candidate
from opendbc.car.hyundai.hyundaicanfd import CanBus from opendbc.car.hyundai.hyundaicanfd import CanBus
from opendbc.car.hyundai.non_scc_aol import NON_SCC_IDS from opendbc.car.hyundai.non_scc_aol import NON_SCC_IDS
from opendbc.car.hyundai.values import (is_blended, is_blended_alpha, HyundaiFlags, CAR, DBC, HyundaiSafetyFlags, CANFD_ANGLE_MODEL_BITS, from opendbc.car.hyundai.values import (is_blended, is_blended_alpha, HyundaiFlags, CAR, DBC, HyundaiSafetyFlags, CANFD_ANGLE_MODEL_BITS,
CANFD_ANGLE_OBSERVED_ADAS_BIT, HYUNDAI_MRR35_RADAR_DBC, HYUNDAI_MRR30_RADAR_DBC, CANFD_ANGLE_OBSERVED_ADAS_BIT, CARNIVAL_2027_CAMERA_FW, HYUNDAI_MRR35_RADAR_DBC, HYUNDAI_MRR30_RADAR_DBC,
HYUNDAI_GV70_RADAR_DBC, HYUNDAI_G90_RADAR_DBC, HYUNDAI_MRREVO14F_RADAR_DBC) HYUNDAI_GV70_RADAR_DBC, HYUNDAI_G90_RADAR_DBC, HYUNDAI_MRREVO14F_RADAR_DBC)
from opendbc.car.hyundai.radar_interface import RADAR_START_ADDR, MRR35_RADAR_START_ADDR, MRR30_RADAR_START_ADDR, radar_bus, \ from opendbc.car.hyundai.radar_interface import RADAR_START_ADDR, MRR35_RADAR_START_ADDR, MRR30_RADAR_START_ADDR, radar_bus, \
stinger_2022_radar_available stinger_2022_radar_available
@@ -121,10 +122,30 @@ class CarInterface(CarInterfaceBase):
return -3.5, 3.5 return -3.5, 3.5
return CarInterfaceBase.get_pid_accel_limits(CP, current_speed, cruise_speed, faster_takeoffs=faster_takeoffs) return CarInterfaceBase.get_pid_accel_limits(CP, current_speed, cruise_speed, faster_takeoffs=faster_takeoffs)
@classmethod
def get_params(cls, candidate, fingerprint, car_fw, alpha_long, is_release, docs, *, vin=""):
cp = super().get_params(candidate, fingerprint, car_fw, alpha_long, is_release, docs)
if candidate == CAR.HYUNDAI_KONA_EV_2023_NON_SCC:
identified = kona_electric_se_candidate(vin, fingerprint, car_fw) == candidate
if (identified and fingerprint.get(0, {}).get(0x391) == 8 and fingerprint.get(2, {}).get(0x485) == 4 and
cp.safetyConfigs[-1].safetyParam == 0x1841):
cp.safetyConfigs[-1].safetyParam |= HyundaiSafetyFlags.KONA_EV_LABEL_CRUISE.value
else:
cp.dashcamOnly = True
cp.safetyConfigs = [get_safety_config(structs.CarParams.SafetyModel.noOutput)]
cp.autoResumeSng = False
return cp
@staticmethod @staticmethod
def _get_params(ret: structs.CarParams, candidate, fingerprint, car_fw, alpha_long, is_release, docs) -> structs.CarParams: def _get_params(ret: structs.CarParams, candidate, fingerprint, car_fw, alpha_long, is_release, docs) -> structs.CarParams:
ret.brand = "hyundai" ret.brand = "hyundai"
if candidate == CAR.HYUNDAI_I30_2026:
ret.dashcamOnly = True
ret.radarUnavailable = True
ret.safetyConfigs = [get_safety_config(structs.CarParams.SafetyModel.noOutput)]
return ret
if is_blended(ret): if is_blended(ret):
cam_can = CanBus(None, fingerprint).CAM cam_can = CanBus(None, fingerprint).CAM
lka_steering = any(fw.ecu == Ecu.adas for fw in car_fw) or 0x50 in fingerprint[cam_can] lka_steering = any(fw.ecu == Ecu.adas for fw in car_fw) or 0x50 in fingerprint[cam_can]
@@ -310,6 +331,8 @@ class CarInterface(CarInterfaceBase):
ret.alphaLongitudinalAvailable = not is_release ret.alphaLongitudinalAvailable = not is_release
alpha_long = False alpha_long = False
from opendbc.car.hyundai.legacy_long_aol import CARS as legacy_long_cars from opendbc.car.hyundai.legacy_long_aol import CARS as legacy_long_cars
if candidate == CAR.KIA_CARNIVAL_2025 and any(fw.ecu == Ecu.fwdCamera and fw.fwVersion == CARNIVAL_2027_CAMERA_FW for fw in car_fw):
ret.alphaLongitudinalAvailable = False
ret.openpilotLongitudinalControl = alpha_long and ret.alphaLongitudinalAvailable and candidate not in legacy_long_cars ret.openpilotLongitudinalControl = alpha_long and ret.alphaLongitudinalAvailable and candidate not in legacy_long_cars
if (candidate in (CAR.KIA_CARNIVAL_2025, CAR.KIA_CARNIVAL_HEV_4TH_GEN) and if (candidate in (CAR.KIA_CARNIVAL_2025, CAR.KIA_CARNIVAL_HEV_4TH_GEN) and
ret.flags & HyundaiFlags.CANFD_ALT_BUTTONS and 0x1aa in fingerprint[CAN.ECAN] and ret.flags & HyundaiFlags.CANFD_ALT_BUTTONS and 0x1aa in fingerprint[CAN.ECAN] and
@@ -9,12 +9,13 @@ from opendbc.car import structs
from opendbc.car.hyundai.values import CAR, HyundaiFlags, HyundaiSafetyFlags from opendbc.car.hyundai.values import CAR, HyundaiFlags, HyundaiSafetyFlags
NON_SCC_IDS = frozenset((CAR.HYUNDAI_BAYON_1ST_GEN_NON_SCC, CAR.HYUNDAI_ELANTRA_2022_NON_SCC, NON_SCC_IDS = frozenset((CAR.HYUNDAI_BAYON_1ST_GEN_NON_SCC, CAR.HYUNDAI_ELANTRA_2022_NON_SCC,
CAR.HYUNDAI_ELANTRA_HEV_2022_NON_SCC, CAR.HYUNDAI_KONA_NON_SCC, CAR.HYUNDAI_KONA_EV_NON_SCC, CAR.HYUNDAI_ELANTRA_HEV_2022_NON_SCC, CAR.HYUNDAI_KONA_NON_SCC, CAR.HYUNDAI_KONA_EV_NON_SCC, CAR.HYUNDAI_KONA_EV_2023_NON_SCC,
CAR.KIA_CEED_PHEV_2022_NON_SCC, CAR.KIA_FORTE_2019_NON_SCC, CAR.KIA_FORTE_2021_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)) CAR.KIA_SELTOS_2023_NON_SCC, CAR.GENESIS_G70_2021_NON_SCC))
SOFTWARE_CRUISE = 0x0020
AOL_MARKER = 0x0400 AOL_MARKER = 0x0400
AOL_EXPERIENCE = 32 AOL_EXPERIENCE = 32
AOL_WORDS = frozenset((0x1400, 0x1c00, 0x1440, 0x1c40, 0x1441, 0x1c41, 0x1402, 0x1c02)) AOL_WORDS = frozenset((0x1400, 0x1c00, 0x1440, 0x1c40, 0x1441, 0x1c41, 0x1c51, 0x1402, 0x1c02))
def stock_word(cp): def stock_word(cp):
@@ -26,6 +27,8 @@ def stock_word(cp):
word |= int(safety) word |= int(safety)
if cp.flags & HyundaiFlags.HAS_LDA_BUTTON: if cp.flags & HyundaiFlags.HAS_LDA_BUTTON:
word |= int(HyundaiSafetyFlags.HAS_LDA_BUTTON) word |= int(HyundaiSafetyFlags.HAS_LDA_BUTTON)
if cp.carFingerprint == CAR.HYUNDAI_KONA_EV_2023_NON_SCC:
word |= int(HyundaiSafetyFlags.KONA_EV_LABEL_CRUISE)
return word return word
@@ -46,12 +49,15 @@ def qualified(cp):
# The observed alternative CLU source is marked only at the AOL boundary; # The observed alternative CLU source is marked only at the AOL boundary;
# ordinary safety may still use its original MAIN-only profile. # ordinary safety may still use its original MAIN-only profile.
ordinary = word & ~int(HyundaiSafetyFlags.HAS_LDA_BUTTON) ordinary = word & ~int(HyundaiSafetyFlags.HAS_LDA_BUTTON)
if cp.carFingerprint == CAR.HYUNDAI_KONA_EV_2023_NON_SCC:
return (safety.safetyModel == structs.CarParams.SafetyModel.hyundai and
(safety.safetyParam & ~SOFTWARE_CRUISE) in (0x1851, 0x1C51))
return (safety.safetyModel == structs.CarParams.SafetyModel.hyundai and 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): 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 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.actuators.longControlState = structs.CarControl.Actuators.LongControlState.pid
command.hudControl.setSpeed = 25.0 command.hudControl.setSpeed = 25.0
for frame in range(32): 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 = [] wanted = []
if frame % 100 == 0: if frame % 100 == 0:
wanted.append((0x730 if hdaii else 0x7D0, int(hdaii))) wanted.append((0x730 if hdaii else 0x7D0, int(hdaii)))
@@ -90,6 +93,8 @@ class TestBlendedSender(unittest.TestCase):
wanted.append((0x485, 1)) wanted.append((0x485, 1))
self.assertEqual([(address, bus) for address, _, bus in messages], wanted) self.assertEqual([(address, bus) for address, _, bus in messages], wanted)
packets = {address: data for address, data, _ in messages} 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: for address, data, _ in messages:
if address not in (0x730, 0x7D0, 0x50, 0x51, 0x2A4): if address not in (0x730, 0x7D0, 0x50, 0x51, 0x2A4):
self.assertEqual(data[0], hyundai_checksum(data[1:8]), hex(address)) 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('hda2', (False, True))
@pytest.mark.parametrize('corruption', ('crc', 'replay', 'wrong_bus', 'inactive')) @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 = params(hda2)
cp.alternativeExperience = 32 cp.alternativeExperience = 32
ci = CarInterface(cp) ci = CarInterface(cp)
@@ -295,7 +295,14 @@ def test_real_controller_invalid_replacement_does_not_acquire_forwarding(hda2, c
elif corruption == 'wrong_bus': elif corruption == 'wrong_bus':
assert not safety.safety_tx_hook(libsafety_py.make_CANPacket(addr, 1, data)) assert not safety.safety_tx_hook(libsafety_py.make_CANPacket(addr, 1, data))
else: 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)) 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 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 permission == 0 and not accepted
assert safety.safety_fwd_hook(2, addr) == 0 assert safety.safety_fwd_hook(2, addr) == 0
if 80 <= tick < 100: 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: if tick >= 115:
assert permission == 1 and accepted assert permission == 1 and accepted
assert safety.safety_fwd_hook(2, addr) == -1 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)
@@ -122,3 +122,31 @@ def test_exact_recorded_configuration_keeps_irq_fault_blocking():
assert cp.alternativeExperience == 0 and cp.pcmCruise and not cp.openpilotLongitudinalControl assert cp.alternativeExperience == 0 and cp.pcmCruise and not cp.openpilotLongitudinalControl
assert blocking_fault_mask(8, cp) assert blocking_fault_mask(8, cp)
assert blocking_fault_list([log.PandaState.FaultType.interruptRateCan2], cp) assert blocking_fault_list([log.PandaState.FaultType.interruptRateCan2], cp)
def test_carnival_2027_uses_the_gas_ccnc_profile_and_standard_stock_acc():
from opendbc.car import gen_empty_fingerprint
from opendbc.car.fw_versions import match_fw_to_car
from opendbc.car.hyundai.interface import CarInterface
from opendbc.car.hyundai.values import CAR, HyundaiFlags
from opendbc.car.structs import CarParams
fw = [CarParams.CarFw(ecu=ecu, address=address, fwVersion=version, brand='hyundai') for ecu, address, version in (
(CarParams.Ecu.fwdCamera, 0x7c4, b'\xf1\x00KA4 MFC AT USA LHD 1.00 1.02 99210-R0800 251031'),
(CarParams.Ecu.fwdRadar, 0x7d0, b'\xf1\x00KA4_ RDR ----- 1.00 1.02 99110-R0510 '),
(CarParams.Ecu.adas, 0x730, b'\xf1\x00KA4 FBL6 1.00 1.02 251159'),
)]
exact, matches = match_fw_to_car(fw, VIN_UNKNOWN)
assert exact and matches == {CAR.KIA_CARNIVAL_2025}
observed = gen_empty_fingerprint()
observed[0].update({0x3A5: 24})
observed[1].update({0x100: 32, 0x40: 32, 0xEA: 24, 0xA0: 24, 0x1A0: 32, 0x1CF: 8, 0x1AA: 16})
observed[2].update({0x110: 32, 0x362: 32})
frames = [CanData(address, bytes(length), bus) for bus in (0, 1, 2) for address, length in observed[bus].items()]
assert normal_bus_topology(lambda **kw: [frames])
for alpha_requested in (False, True):
cp = CarInterface.get_params(CAR.KIA_CARNIVAL_2025, observed, fw, alpha_requested, False, False)
assert cp.pcmCruise and not cp.openpilotLongitudinalControl and not cp.alphaLongitudinalAvailable
assert cp.flags & HyundaiFlags.CANFD_LKA_STEER_MSG_ALT
assert not cp.flags & (HyundaiFlags.CANFD_ALT_BUTTONS | HyundaiFlags.HYBRID)
assert cp.safetyConfigs[-1].safetyParam == 0x90
@@ -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)}) eps = packer.make_can_msg('MDPS', 0, {'COUNTER': tick, 'MDPS_LkaToiActvSta': int(tick >= 4)})
source.update([(clock[0], [eps, camera])]) source.update([(clock[0], [eps, camera])])
owned = source.owns_display_status(tick >= 2, clock[0], healthy=True) 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 assert owned
final_owned_ns = clock[0] final_owned_ns = clock[0]
for tick in range(16, 23): 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) frames.append(camera)
source.update([(clock[0], frames)]) source.update([(clock[0], frames)])
now = final_owned_ns - 1 if failure == 'backward' else -1 if failure == 'negative' else clock[0] 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') qualified_warning=failure == 'stale_camera_qualified')
if failure == 'expired': if failure == 'expired':
assert held == (clock[0] - final_owned_ns <= 50_000_000) 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) camera = template(packer, 2, tick)
eps = packer.make_can_msg('MDPS', 0, {'COUNTER': tick}) eps = packer.make_can_msg('MDPS', 0, {'COUNTER': tick})
source.update([(clock[0], [eps, camera])]) 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)) @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.interface import CarInterface
from opendbc.car.hyundai.ioniq6_handoff import TimestampedCanPacket from opendbc.car.hyundai.ioniq6_handoff import TimestampedCanPacket
from opendbc.car.hyundai.generic_hda2_startup import GenericHDA2Startup, qualified 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.tests.test_generic_hda2_startup import FUEL_CASES
from opendbc.car.hyundai.values import CAR from opendbc.car.hyundai.values import CAR
from opendbc.safety.tests.libsafety import libsafety_py 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") assert {key: saved.get(key) for key in keys} == settings and not saved.get_bool("ControlsReady")
if mode == "rejected" and aol: if mode == "rejected" and aol:
expected.safetyConfigs[0].safetyParam |= 0x800 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.safetyConfigs[0].safetyParam |= 0x800
expected.alternativeExperience = 32 expected.alternativeExperience = 32
assert card.CP.to_dict() == expected.to_dict() 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 commands == [b"\x10\x03", b"\x28\x83\x01"] and owner.keeper.running
assert owner.outcome is Outcome.SENT_UNCONFIRMED and not owner.restored assert owner.outcome is Outcome.SENT_UNCONFIRMED and not owner.restored
cp = card.CP 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] config = cp.safetyConfigs[0]
native.set_alternative_experience(cp.alternativeExperience) native.set_alternative_experience(cp.alternativeExperience)
assert native.set_safety_hooks(int(config.safetyModel.raw), int(config.safetyParam)) == 0 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 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 = gen_empty_fingerprint()
fp[offset].update({0x1CF: 8, 0x35: 32, 0x175: 24, 0xA0: 24, 0xEA: 24, 0x1BA: 24, 0x1E5: 16}) 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 + 2].update({0x12A: 16, 0x1A0: 32})
fp[offset + 1].update({0x110: 32, 0x100: 24}) 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.openpilotLongitudinalControl and not cp.pcmCruise
assert cp.flags & HyundaiFlags.CANFD_CAMERA_SCC assert cp.flags & HyundaiFlags.CANFD_CAMERA_SCC
assert not cp.flags & HyundaiFlags.CANFD_LKA_STEER_MSG 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]) @pytest.mark.parametrize('offset', [0, 4])
def test_factory_ioniq5_camera_long_uses_existing_paired_axis_profile(offset): @pytest.mark.parametrize('identity', CAMERA_LONG_CARS)
cp = camera_long(offset) def test_factory_camera_long_uses_existing_paired_axis_profile(identity, offset):
cp = camera_long(offset, identity=identity)
before = cp.to_dict() before = cp.to_dict()
assert qualified_long(cp) assert qualified_long(cp)
assert independent_cruise_buttons_supported(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('offset', [0, 4])
@pytest.mark.parametrize('mutation', ['alternate_buttons', 'unknown_word', 'wrong_experience', 'passive', 'angle']) @pytest.mark.parametrize('mutation', ['alternate_buttons', 'unknown_word', 'wrong_experience', 'passive', 'angle', 'hda2'])
def test_camera_long_extension_keeps_unrecognized_contracts_closed(offset, mutation): @pytest.mark.parametrize('identity', CAMERA_LONG_CARS)
cp = camera_long(offset) def test_camera_long_extension_keeps_unrecognized_contracts_closed(identity, offset, mutation):
cp = camera_long(offset, identity=identity)
owner = config_index(cp) owner = config_index(cp)
cp.safetyConfigs[owner].safetyParam = 0x80D cp.safetyConfigs[owner].safetyParam = 0x80D
cp.alternativeExperience = 32 cp.alternativeExperience = 32
@@ -59,18 +64,23 @@ def test_camera_long_extension_keeps_unrecognized_contracts_closed(offset, mutat
cp.alternativeExperience = 0 cp.alternativeExperience = 0
elif mutation == 'passive': elif mutation == 'passive':
cp.passive = True cp.passive = True
else: elif mutation == 'angle':
cp.flags |= int(HyundaiFlags.CANFD_ANGLE_STEERING) 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('offset', [0, 4])
@pytest.mark.parametrize('button', ['lkas', 'mainCruise']) @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.aol.intent import AolSettings
from openpilot.starpilot.car.hyundai.aol import create_intent 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.safetyConfigs[config_index(cp)].safetyParam = 0x80D
cp.alternativeExperience = 32 cp.alternativeExperience = 32
settings = AolSettings(enabled=True, pause_brake_mps=0.0, lkas_action=0, main_action=0, 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] 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): def test_camera_extension_does_not_admit_unqualified_identities(identity):
cp = camera_long(0) cp = camera_long(0)
cp.carFingerprint = identity 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('offset', [0, 4])
@pytest.mark.parametrize('enabled', [False, True]) @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 import os
from unittest.mock import patch from unittest.mock import patch
from opendbc.car.hyundai.radar_interface import RadarInterface from opendbc.car.hyundai.radar_interface import RadarInterface
from openpilot.common.params import Params from openpilot.common.params import Params
from openpilot.common.prefix import OpenpilotPrefix from openpilot.common.prefix import OpenpilotPrefix
from openpilot.selfdrive.car.card import Car 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'}): with OpenpilotPrefix(), patch.dict(os.environ, {'SIMULATION': '1'}):
saved = Params() saved = Params()
saved.put_bool('OpenpilotEnabledToggle', True, block=True) 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 qualified_long(published, marked_only=enabled)
assert config_index(published) == offset // 4 assert config_index(published) == offset // 4
assert not CarInterface.startup_required(published) 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 assert card.aol_qualified == enabled
if enabled: if enabled:
assert card.aol_card_intent.explicit_latch and card.aol_card_intent.independent_cruise_buttons assert card.aol_card_intent.explicit_latch and card.aol_card_intent.independent_cruise_buttons
@@ -1,5 +1,6 @@
import os import os
from unittest.mock import Mock, patch from unittest.mock import Mock, patch
from types import SimpleNamespace
import pytest 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.canfd_stock_aol import qualified_long
from opendbc.car.hyundai.interface import CarInterface from opendbc.car.hyundai.interface import CarInterface
from opendbc.car.hyundai.values import CAR, HyundaiFlags 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) 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) assert qualified_long(cp) and independent_cruise_buttons_supported(cp)
policy = policy_for(cp) policy = policy_for(cp)
assert policy.intent_supported and policy.runtime_supported and policy.explicit_latch 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 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.safetyConfigs[-1].safetyParam = word
cp.alternativeExperience = 32 cp.alternativeExperience = 32
assert qualified_long(cp, marked_only=True) assert qualified_long(cp, marked_only=True)
@@ -199,3 +201,106 @@ def test_wheel_choices_keep_aol_with_either_longitudinal_owner(car, alternate, a
feature = WheelFeature(Owner()) feature = WheelFeature(Owner())
assert 'Toggle AOL' in feature.choices('LKASButtonControl') assert 'Toggle AOL' in feature.choices('LKASButtonControl')
assert 'Toggle AOL' in feature.choices('MainCruiseButtonControl') 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
@pytest.mark.parametrize('handoff,enabled,hud_mode', ((True, False, 0), (True, True, 2), (False, False, 1)))
def test_kona_handoff_cruise_main_display_follows_star_long_engagement(handoff, enabled, hud_mode):
from opendbc.can import CANParser
cp = kona_params(CARS[0])
cp.safetyConfigs[0].safetyParam = 0x1C0C if handoff else 0x0C0C
cp.alternativeExperience = 32
ci = CarInterface(cp)
ci.CS.out = structs.CarState(cruiseState={'available': True}, vCruiseCluster=40.).as_reader()
for frame in range(5):
ci.apply(structs.CarControl().as_reader(), 950_000_000 + frame * 10_000_000)
ci.CS.ccnc_161_ts_ns = ci.CS.ccnc_162_ts_ns = 1_000_000_000
ci.CS.ccnc_161 = {'SETSPEED_HUD': 3, 'SETSPEED_SPEED': 20, 'DISTANCE_SPACING': 1}
ci.CS.ccnc_162 = {'FAULT_LSS': 2, 'FAULT_FCA': 1}
command = structs.CarControl(enabled=enabled, latActive=True, longActive=enabled)
_, packets = ci.apply(command.as_reader(), 1_000_000_000)
parser = CANParser('hyundai_canfd_generated', [('CCNC_0x161', 0), ('CCNC_0x162', 0), ('SCC_CONTROL', 0)], 0)
# The display runs at 20 Hz and SCC at 50 Hz.
_, scc_packets = ci.apply(command.as_reader(), 1_010_000_000)
assert {0x161, 0x162} <= parser.update((1_000_000_000, packets))
assert 0x1A0 in parser.update((1_010_000_000, scc_packets))
assert parser.vl['SCC_CONTROL']['MainMode_ACC'] == int(not handoff or enabled)
display = parser.vl['CCNC_0x161']
assert display['SETSPEED_HUD'] == hud_mode
assert display['LFA_ICON'] == 2
if handoff:
assert display['SETSPEED'] == hud_mode
if hud_mode == 0:
assert display['DISTANCE'] == 0
assert display['SETSPEED_SPEED'] == 255
assert display['DISTANCE_SPACING'] == 0
assert parser.vl['CCNC_0x162']['FAULT_LSS'] == 2
assert parser.vl['CCNC_0x162']['FAULT_FCA'] == 1
@pytest.mark.parametrize('speed,accel,previous,standstill,lead,word,cap', [
(0.3, -0.27, -0.26, False, False, 0x1C0C, 1.2),
(2.2, -0.67, -0.66, False, False, 0x1C0C, 1.2),
(2.4, -1.13, -1.12, False, False, 0x1C0C, 1.2),
(1.2, -1.80, -1.78, False, False, 0x1C0C, 1.2),
(3.0, -0.60, -0.59, False, False, 0x1C0C, 5.0),
(0.3, -2.00, -1.99, False, False, 0x1C0C, 5.0),
(0.3, -0.45, -0.20, False, False, 0x1C0C, 5.0),
(0.1, -0.27, -0.26, True, False, 0x1C0C, 5.0),
(0.3, -0.27, -0.26, False, True, 0x1C0C, 5.0),
(0.3, -0.27, -0.26, False, False, 0x0C0C, 5.0),
])
def test_kona_final_braking_jerk(speed, accel, previous, standstill, lead, word, cap):
from opendbc.can import CANParser
cp = kona_params(CARS[0])
cp.safetyConfigs[0].safetyParam = word
cp.alternativeExperience = 32
ci = CarInterface(cp)
ci.CS.out = structs.CarState(vEgo=speed, standstill=standstill, cruiseState={'available': True}).as_reader()
ci.CC.accel_last = previous
command = structs.CarControl(enabled=True, longActive=True,
actuators={'accel': accel, 'longControlState': 'stopping'},
hudControl={'leadVisible': lead})
_, frames = ci.apply(command.as_reader(), 1_000_000_000)
parser = CANParser('hyundai_canfd_generated', [('SCC_CONTROL', 0)], 0)
assert 0x1A0 in parser.update((1_000_000_000, frames))
values = parser.vl['SCC_CONTROL']
assert values['aReqValue'] == pytest.approx(accel)
assert values['aReqRaw'] == pytest.approx(accel)
assert values['ACCMode'] == values['StopReq'] == 1
assert values['JerkLowerLimit'] == pytest.approx(cap)
@@ -0,0 +1,107 @@
from unittest import TestCase, mock
from opendbc.car import CanData, gen_empty_fingerprint, structs
from opendbc.car.car_helpers import get_car
from opendbc.car.hyundai import non_scc_aol, software_cruise
from opendbc.car.hyundai.discovery import kona_electric_se_candidate
from opendbc.car.hyundai.fingerprints import FW_VERSIONS
from opendbc.car.hyundai.values import CAR
MODEL = CAR.HYUNDAI_KONA_EV_2023_NON_SCC
SE_VIN = 'KM8K23AG0PU000000'
SCC_VIN = 'KM8K53AG1PU000000'
SE_LAYOUT = ((0, 0x251, 8), (0, 0x371, 8), (0, 0x386, 8), (0, 0x394, 8), (0, 0x4F1, 4),
(0, 0x391, 8), (0, 0x592, 8), (1, 0x329, 8), (2, 0x340, 8), (2, 0x485, 4))
def kona_electric_fw(include_radar=False):
ecu = structs.CarParams.Ecu
versions = FW_VERSIONS[CAR.HYUNDAI_KONA_EV_2022]
firmware = [
structs.CarParams.CarFw(ecu=ecu.eps, address=0x7D4, brand='hyundai',
fwVersion=b'\xf1\x00OSP MDPS C 1.00 1.02 56310K4261\x00 4OEPC102'),
structs.CarParams.CarFw(ecu=ecu.fwdCamera, address=0x7C4, brand='hyundai',
fwVersion=b'\xf1\x00OSP LKA AT USA LHD 1.00 1.04 99211-J9200 904'),
]
if include_radar:
firmware.append(structs.CarParams.CarFw(ecu=ecu.fwdRadar, address=0x7D0, brand='hyundai',
fwVersion=versions[(ecu.fwdRadar, 0x7D0, None)][0]))
return firmware
def interface(vin, layout=SE_LAYOUT, radar=False, forced_candidate=None):
packets = [CanData(addr, bytes(length), bus) for bus, addr, length in layout]
cached = structs.CarParams(brand='hyundai', carVin=vin, carFw=kona_electric_fw(radar), carFingerprint=forced_candidate or '')
with mock.patch.dict('os.environ', clear=True):
return get_car(lambda *args, **kwargs: [packets] if kwargs.get('wait_for_one') else [], mock.Mock(), mock.Mock(),
alpha_long_allowed=True, is_release=False, cached_params=cached, forced_candidate=forced_candidate)
class TestKonaElectricSE(TestCase):
def test_exact_auto_and_manual_identity_use_stock_cruise_steering(self):
for manual in (None, MODEL):
with self.subTest(manual=manual):
ci = interface(SE_VIN, forced_candidate=manual)
cp = ci.CP
self.assertEqual(cp.carFingerprint, MODEL)
self.assertFalse(cp.dashcamOnly)
self.assertTrue(cp.pcmCruise)
self.assertFalse(cp.alphaLongitudinalAvailable)
self.assertFalse(cp.openpilotLongitudinalControl)
self.assertFalse(cp.autoResumeSng)
self.assertEqual([(s.safetyModel, s.safetyParam) for s in cp.safetyConfigs], [(structs.CarParams.SafetyModel.hyundai, 0x1851)])
self.assertTrue(non_scc_aol.qualified(cp))
self.assertEqual(non_scc_aol.aol_word(cp), 0x1c51)
self.assertFalse(software_cruise.selected(software_cruise.prepare(cp, False)))
self.assertTrue(software_cruise.selected(software_cruise.prepare(cp, True)))
self.assertEqual(cp.safetyConfigs[0].safetyParam, 0x1871)
self.assertEqual(non_scc_aol.aol_word(cp), 0x1c71)
def test_wrong_manual_match_remains_read_only(self):
wrong_lkas = (*SE_LAYOUT[:-1], (2, 0x485, 8))
for vin, layout in ((SCC_VIN, SE_LAYOUT), (SE_VIN, wrong_lkas)):
with self.subTest(vin=vin, layout=layout):
ci = interface(vin, layout, forced_candidate=MODEL)
cp = ci.CP
self.assertTrue(cp.dashcamOnly)
self.assertFalse(software_cruise.eligible(cp))
self.assertEqual([(s.safetyModel, s.safetyParam) for s in cp.safetyConfigs], [(structs.CarParams.SafetyModel.noOutput, 0)])
cmd = structs.CarControl(enabled=True, latActive=True, longActive=True)
self.assertFalse(ci.apply(cmd.as_reader(), 0)[1])
def test_scc_firmware_still_owns_matching_sibling(self):
ci = interface(SCC_VIN, (*SE_LAYOUT, (2, 0x420, 8), (2, 0x421, 8)), radar=True)
self.assertEqual(ci.CP.carFingerprint, CAR.HYUNDAI_KONA_EV_2022)
self.assertFalse(ci.CP.dashcamOnly)
def test_evidence_is_conjunctive(self):
fp = gen_empty_fingerprint()
for bus, addr, length in SE_LAYOUT:
fp[bus][addr] = length
firmware = kona_electric_fw()
self.assertEqual(kona_electric_se_candidate(SE_VIN, fp, firmware), MODEL)
for vin in ('', '00000000000000000', SCC_VIN, SE_VIN[:9] + 'N' + SE_VIN[10:]):
self.assertIsNone(kona_electric_se_candidate(vin, fp, firmware))
self.assertIsNone(kona_electric_se_candidate(SE_VIN, fp, firmware[:1]))
self.assertIsNone(kona_electric_se_candidate(SE_VIN, fp, kona_electric_fw(include_radar=True)))
fp[2][0x421] = 8
self.assertIsNone(kona_electric_se_candidate(SE_VIN, fp, firmware))
del fp[2][0x421]
fp[1][0x329] = 7
self.assertIsNone(kona_electric_se_candidate(SE_VIN, fp, firmware))
def test_only_regular_set_and_resume_allow_pcm_enable(self):
from opendbc.can import CANPacker
for main, button, permitted in ((True, 0, False), (False, 4, False), (True, 2, False),
(False, 2, True), (False, 1, True)):
with self.subTest(main=main, button=button):
ci = interface(SE_VIN)
packer = CANPacker('hyundai_can_generated')
stamp = 1_000_000_000
ci.CS.cruise_buttons.append(button)
ci.CS.main_buttons.append(main)
active = packer.make_can_msg('LABEL11', 0, {'CC_React': 1, 'CC_Engaged': 1})
result = ci.update([(stamp, [active])])
self.assertTrue(result.cruiseState.available and result.cruiseState.enabled)
self.assertEqual(not result.blockPcmEnable, permitted)
@@ -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) 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]) packer = CANPacker(DBC[ci.CP.carFingerprint][Bus.pt])
messages = [] messages = []
for parser in ci.can_parsers.values(): for parser in ci.can_parsers.values():
for address in parser.addresses: for address in parser.addresses:
if address == 0x2A4 and camera is False:
continue
message = parser.dbc.addr_to_msg[address] message = parser.dbc.addr_to_msg[address]
values = {'COUNTER': tick % 16} if 'COUNTER' in message.sigs else {} 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': if message.name == 'SCC12':
values.update(MainMode_ACC=int(main), ACCMode=cruise, SCCInfoDisplay=display, VSetDis=90) values.update(MainMode_ACC=int(main), ACCMode=cruise, SCCInfoDisplay=display, VSetDis=90)
elif message.name == 'EMS16': elif message.name == 'EMS16':
@@ -100,13 +104,14 @@ class TestPalisade2023(unittest.TestCase):
command.hudControl.setSpeed = 25. command.hudControl.setSpeed = 25.
previous = 0 previous = 0
for tick in range(20): 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) 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) self.assertEqual(actuators.torqueOutputCan - previous, 3 if topology == 'hdaii' else 2)
previous = actuators.torqueOutputCan previous = actuators.torqueOutputCan
addresses = {a for a, _, _ in messages} addresses = {a for a, _, _ in messages}
self.assertFalse(addresses & {0x420, 0x421, 0x389, 0x7D0, 0x730}) self.assertFalse(addresses & {0x420, 0x421, 0x389, 0x7D0, 0x730})
if topology == 'hdaii': 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)) self.assertTrue(all(bus == 0 for _, _, bus in messages))
else: else:
self.assertEqual(addresses, {0x340, 0x364}) self.assertEqual(addresses, {0x340, 0x364})
@@ -123,6 +128,37 @@ class TestPalisade2023(unittest.TestCase):
actuators, _ = ci.apply(command.as_reader(), 1_500_000_000) actuators, _ = ci.apply(command.as_reader(), 1_500_000_000)
self.assertEqual(actuators.torqueOutputCan, 0) 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): def test_cancel_resume_route_to_exact_pt_bus_and_sibling_params_unchanged(self):
for topology in ('hdai', 'hdaii'): for topology in ('hdai', 'hdaii'):
ci = CarInterface(params(topology)) ci = CarInterface(params(topology))
@@ -40,7 +40,8 @@ def card_publication_sequence(context):
calls=[statement.value.func.attr for statement in statements if isinstance(statement,ast.Expr)] calls=[statement.value.func.attr for statement in statements if isinstance(statement,ast.Expr)]
assert calls==['configure','finalize_aol_configuration','seal_publication'] assert calls==['configure','finalize_aol_configuration','seal_publication']
exec(compile(ast.Module(body=statements,type_ignores=[]),'actual-card-publication-order','exec'), exec(compile(ast.Module(body=statements,type_ignores=[]),'actual-card-publication-order','exec'),
{'self':context,'aol_policy':policy_for(context.CP), 'hyundai_aol_safety_config':hyundai_aol_safety_config}) {'self':context,'aol_policy':policy_for(context.CP), 'HYUNDAI_CAR':CAR,
'hyundai_aol_safety_config':hyundai_aol_safety_config})
@pytest.fixture(params=[(CAR.KIA_EV6,EV6Startup),(CAR.GENESIS_GV70_ELECTRIFIED_1ST_GEN,GV70Startup)]) @pytest.fixture(params=[(CAR.KIA_EV6,EV6Startup),(CAR.GENESIS_GV70_ELECTRIFIED_1ST_GEN,GV70Startup)])
@@ -78,6 +78,7 @@ class HyundaiSafetyFlags(IntFlag):
LONG = 4 LONG = 4
CAMERA_SCC = 8 CAMERA_SCC = 8
CANFD_LKA_STEER_MSG = 16 CANFD_LKA_STEER_MSG = 16
KONA_EV_LABEL_CRUISE = 16
CANFD_ALT_BUTTONS = 32 CANFD_ALT_BUTTONS = 32
ALT_LIMITS = 64 ALT_LIMITS = 64
CANFD_LKA_STEER_MSG_ALT = 128 CANFD_LKA_STEER_MSG_ALT = 128
@@ -262,6 +263,9 @@ class HyundaiCanFDPlatformConfig(PlatformConfig):
self.dbc_dict = {Bus.pt: "hyundai_canfd_generated", Bus.radar: self.radar_dbc} self.dbc_dict = {Bus.pt: "hyundai_canfd_generated", Bus.radar: self.radar_dbc}
CARNIVAL_2027_CAMERA_FW = b'\xf1\x00KA4 MFC AT USA LHD 1.00 1.02 99210-R0800 251031'
class CAR(Platforms): class CAR(Platforms):
# Hyundai # Hyundai
HYUNDAI_AZERA_6TH_GEN = HyundaiPlatformConfig( HYUNDAI_AZERA_6TH_GEN = HyundaiPlatformConfig(
@@ -300,6 +304,7 @@ class CAR(Platforms):
HYUNDAI_ELANTRA.specs, HYUNDAI_ELANTRA.specs,
flags=HyundaiFlags.LEGACY | HyundaiFlags.CLUSTER_GEARS | HyundaiFlags.MIN_STEER_32_MPH, flags=HyundaiFlags.LEGACY | HyundaiFlags.CLUSTER_GEARS | HyundaiFlags.MIN_STEER_32_MPH,
) )
HYUNDAI_I30_2026 = HyundaiPlatformConfig([], HYUNDAI_ELANTRA_GT_I30.specs)
HYUNDAI_ELANTRA_2021 = HyundaiPlatformConfig( HYUNDAI_ELANTRA_2021 = HyundaiPlatformConfig(
[HyundaiCarDocs("Hyundai Elantra 2021-23", video="https://youtu.be/_EdYQtV52-c", car_parts=CarParts.common([CarHarness.hyundai_k]))], [HyundaiCarDocs("Hyundai Elantra 2021-23", video="https://youtu.be/_EdYQtV52-c", car_parts=CarParts.common([CarHarness.hyundai_k]))],
CarSpecs(mass=2800 * CV.LB_TO_KG, wheelbase=2.72, steerRatio=12.9, tireStiffnessFactor=0.65), CarSpecs(mass=2800 * CV.LB_TO_KG, wheelbase=2.72, steerRatio=12.9, tireStiffnessFactor=0.65),
@@ -823,6 +828,7 @@ class CAR(Platforms):
[ [
HyundaiCarDocs("Kia Carnival 2025", car_parts=CarParts.common([CarHarness.hyundai_k])), HyundaiCarDocs("Kia Carnival 2025", car_parts=CarParts.common([CarHarness.hyundai_k])),
HyundaiCarDocs("Kia Carnival (with HDA II) 2025", "Highway Driving Assist II", car_parts=CarParts.common([CarHarness.hyundai_q])), HyundaiCarDocs("Kia Carnival (with HDA II) 2025", "Highway Driving Assist II", car_parts=CarParts.common([CarHarness.hyundai_q])),
HyundaiCarDocs("Kia Carnival (with HDA II) 2027", "Highway Driving Assist II", car_parts=CarParts.common([CarHarness.hyundai_q])),
], ],
KIA_CARNIVAL_4TH_GEN.specs, KIA_CARNIVAL_4TH_GEN.specs,
flags=HyundaiFlags.CCNC, flags=HyundaiFlags.CCNC,
@@ -950,6 +956,11 @@ class CAR(Platforms):
HYUNDAI_KONA_EV.specs, HYUNDAI_KONA_EV.specs,
flags=HyundaiFlags.EV | HyundaiFlags.ALT_LIMITS, flags=HyundaiFlags.EV | HyundaiFlags.ALT_LIMITS,
) )
HYUNDAI_KONA_EV_2023_NON_SCC = HyundaiNonSccPlatformConfig(
[HyundaiNonSccCarDocs("Hyundai Kona Electric SE 2023", package="Non-SCC", car_parts=CarParts.common([CarHarness.hyundai_o]))],
HYUNDAI_KONA_EV_2022.specs,
flags=HyundaiFlags.EV | HyundaiFlags.ALT_LIMITS,
)
KIA_RAY_EV = HyundaiNonSccPlatformConfig( KIA_RAY_EV = HyundaiNonSccPlatformConfig(
[HyundaiNonSccCarDocs("Kia Ray EV 2025", package="Non-SCC with comma pedal (6-byte sensor) and 8-byte LFA; other variants dashcam only", [HyundaiNonSccCarDocs("Kia Ray EV 2025", package="Non-SCC with comma pedal (6-byte sensor) and 8-byte LFA; other variants dashcam only",
car_parts=CarParts.common([CarHarness.hyundai_h]))], car_parts=CarParts.common([CarHarness.hyundai_h]))],
@@ -0,0 +1,101 @@
import math
import numpy as np
from opendbc.can import CANPacker
from opendbc.car import Bus
from opendbc.car.interfaces import CarControllerBase
from opendbc.car.lateral import apply_steer_angle_limits_vm, get_max_angle_vm
from opendbc.car.leapmotor import leapmotorcan
from opendbc.car.leapmotor.values import CarControllerParams
from opendbc.car.vehicle_model import VehicleModel
def get_safety_CP():
# the safety model's vehicle-model limits are computed for this platform
from opendbc.car.leapmotor.interface import CarInterface
return CarInterface.get_non_essential_params("LEAPMOTOR_B10")
class CarController(CarControllerBase):
"""Replaces the camera's ADAS_LKA (0x83) with a copy carrying openpilot's angle request, and cancels the
stock ACC through the camera's copy of POWERTRAIN_STATE when openpilot disengages."""
def __init__(self, dbc_names, CP):
super().__init__(dbc_names, CP)
self.packer = CANPacker(dbc_names[Bus.pt])
self.apply_angle_last = 0.
self.lcc_ramp = leapmotorcan.LCC_RAMP_IDLE
self.lat_active_last = False
self.VM = VehicleModel(get_safety_CP())
self.adas_lka_idle = leapmotorcan.decode_adas_lka_idle()
self.ramp_boost = 0
def update_ramp_boost(self, lat_active: bool, CS) -> int:
"""Extra LCC_RAMP steps: one more per frame while the wheel lags the command at low speed, one fewer once it is
back (see CarControllerParams.RAMP_BOOST_LAG), and none past the EPS torque at which the EPS lets go by itself
(see CarControllerParams.RAMP_BOOST_EPS_TORQUE_HOLD)."""
if not lat_active or CS.out.vEgoRaw * 3.6 > CarControllerParams.RAMP_BOOST_MAX_SPEED:
return 0
behind = abs(self.apply_angle_last - CS.out.steeringAngleDeg)
eps_torque = abs(CS.out.steeringTorqueEps)
boost = self.ramp_boost
if eps_torque >= CarControllerParams.RAMP_BOOST_EPS_TORQUE_BACK or behind < CarControllerParams.RAMP_BOOST_CAUGHT_UP:
boost -= 1
elif behind > CarControllerParams.RAMP_BOOST_LAG and eps_torque < CarControllerParams.RAMP_BOOST_EPS_TORQUE_HOLD:
boost += 1
return min(max(boost, 0), leapmotorcan.LCC_RAMP_STEPS_MAX - leapmotorcan.LCC_RAMP_STEPS_MIN)
def long_accel(self, CC, camera_lka: dict) -> float | None:
"""openpilot's acceleration request for ADAS_LKA, or None to send the camera's.
Only while the stock ACC is engaged (ACC_STATE 3): the camera keeps engagement, the standstill hold and the
accelerator override (ACC_STATE 1), and its request goes through unchanged then. When the camera asks for hard
braking, openpilot never asks for less.
"""
if not (self.CP.openpilotLongitudinalControl and CC.longActive and int(camera_lka["ACC_STATE"]) == 3):
return None
accel = float(np.clip(CC.actuators.accel, CarControllerParams.ACCEL_MIN, CarControllerParams.ACCEL_MAX))
camera_accel = float(camera_lka["ACC_ACCEL_REQ"])
if camera_accel <= CarControllerParams.STOCK_BRAKE_PASSTHROUGH:
accel = min(accel, camera_accel)
return accel
def update(self, CC, CS, now_nanos):
actuators = CC.actuators
can_sends = []
# like the stock LCC, let go while the driver steers (the EPS flags it), then ramp back in
# (while the wheel follows openpilot's angle, the stricter rule: see CarControllerParams.OVERRIDE_TRACKING_ERROR)
tracking = (self.lat_active_last and
abs(self.apply_angle_last - CS.out.steeringAngleDeg) < CarControllerParams.OVERRIDE_TRACKING_ERROR)
lat_active = CC.latActive and not (CS.driver_override_tracking if tracking else CS.driver_override)
# take the wheel back only once it is near the angle openpilot wants: after the driver let go mid-turn at walking
# pace with the wheel at +308 deg and the model at +24, the EPS swung it to -203 deg in 3 s
if lat_active and not self.lat_active_last:
lat_active = abs(actuators.steeringAngleDeg - CS.out.steeringAngleDeg) < CarControllerParams.TAKE_BACK_MAX_ANGLE_ERROR
# and within the angle openpilot may command at this speed: otherwise the first frame jumps to that limit, the
# panda blocks it, and the missing frame cancels ACC
if CS.out.vEgoRaw > 1.:
max_angle = get_max_angle_vm(CS.out.vEgoRaw, self.VM, CarControllerParams)
lat_active = lat_active and abs(CS.out.steeringAngleDeg) < max_angle - 1.0
if self.frame % CarControllerParams.STEER_STEP == 0:
camera_lka = CS.adas_lka if CS.adas_lka is not None else self.adas_lka_idle
self.apply_angle_last = apply_steer_angle_limits_vm(actuators.steeringAngleDeg, self.apply_angle_last, CS.out.vEgoRaw,
CS.out.steeringAngleDeg, lat_active, CarControllerParams, self.VM)
lat_accel = self.VM.calc_curvature(math.radians(self.apply_angle_last), CS.out.vEgoRaw, 0.) * CS.out.vEgoRaw ** 2
self.ramp_boost = self.update_ramp_boost(lat_active, CS)
self.lcc_ramp = leapmotorcan.lcc_ramp_next(self.lcc_ramp, lat_active,
leapmotorcan.lcc_ramp_target(lat_accel, CS.out.vEgoRaw * 3.6, self.ramp_boost))
can_sends.append(leapmotorcan.create_steering_control(self.packer, camera_lka, self.apply_angle_last, lat_active,
self.lcc_ramp, self.long_accel(CC, camera_lka)))
# cancel stock ACC when openpilot asks (it is engaged with ACC, so it cancels ACC whenever it disengages)
if CC.cruiseControl.cancel and self.frame % CarControllerParams.STEER_STEP == 0 and CS.powertrain_state is not None:
can_sends.append(leapmotorcan.create_cancel(self.packer, CS.powertrain_state))
self.lat_active_last = lat_active
new_actuators = actuators.as_builder()
new_actuators.steeringAngleDeg = self.apply_angle_last
self.frame += 1
return new_actuators, can_sends
@@ -0,0 +1,137 @@
import numpy as np
from opendbc.car import DT_CTRL, Bus, create_button_events, structs
from opendbc.can.parser import CANParser
from opendbc.car.common.conversions import Conversions as CV
from opendbc.car.common.filter_simple import FirstOrderFilter
from opendbc.car.dashboard_speed_limit import Tracker as LimitTracker, leapmotor_sign, parser_expiry
from opendbc.car.interfaces import CarStateBase
from opendbc.car.leapmotor.values import DBC, CarControllerParams
GearShifter = structs.CarState.GearShifter
ButtonType = structs.CarState.ButtonEvent.Type
GEARS = {0: GearShifter.park, 1: GearShifter.reverse, 2: GearShifter.neutral, 3: GearShifter.drive}
# POWERTRAIN_STATE.STALK_PUSH 3 (stalk pushed up) cancels assist; the engage pushes (1, 2) are not reported
STALK_CANCEL = 3
class CarState(CarStateBase):
def __init__(self, CP):
super().__init__(CP)
self.steering_angle_last = 0.0
self.adas_lka: dict | None = None
self.lka_received_seen = False
self.driver_override_frames = 0
self.driver_override = False
# the override used by the controller while the wheel follows openpilot's angle (see OVERRIDE_TRACKING_ERROR)
self.tracking_pressed_cnt = 0
self.tracking_override_frames = 0
self.driver_override_tracking = False
# the EPS's own effort as it shows up in the driver-torque reading, which lags it (see EPS_TORQUE_LAG)
self.eps_torque_lagged = FirstOrderFilter(0., CarControllerParams.EPS_TORQUE_LAG, DT_CTRL)
self.powertrain_state: dict | None = None
self.dashboard_limit = LimitTracker()
self.stalk_cancel = False
def update(self, can_parsers) -> structs.CarState:
cp = can_parsers[Bus.pt]
cp_cam = can_parsers[Bus.cam]
ret = structs.CarState()
# speed
self.parse_wheel_speeds(ret,
cp.vl['WHEEL_SPEEDS']['WHEEL_SPEED_FL'],
cp.vl['WHEEL_SPEEDS']['WHEEL_SPEED_FR'],
cp.vl['WHEEL_SPEEDS']['WHEEL_SPEED_RL'],
cp.vl['WHEEL_SPEEDS']['WHEEL_SPEED_RR'],
)
ret.vEgoCluster = cp.vl['CLUSTER']['DISPLAY_SPEED'] * CV.KPH_TO_MS
ret.standstill = ret.vEgoRaw < 0.01
ret.yawRate = cp.vl['IMU']['YAW_RATE'] * CV.DEG_TO_RAD
# pedals
ret.gasPressed = cp.vl['VEHICLE_STATE']['ACCEL_PEDAL'] > 0
ret.brakePressed = bool(cp.vl['VEHICLE_STATE']['BRAKE_PRESSED'])
# steering: the EPS speed field has no sign, so take the sign from the angle change
angle = cp.vl['EPS_STEERING']['STEER_ANGLE']
sign = 1.0 if angle > self.steering_angle_last else (-1.0 if angle < self.steering_angle_last else 0.0)
ret.steeringAngleDeg = angle
ret.steeringRateDeg = sign * cp.vl['EPS_STEERING']['STEER_SPEED_ABS']
self.steering_angle_last = angle
ret.steeringTorqueEps = cp.vl['EPS_STEERING']['STEER_TORQUE_EPS']
# the driver's torque: the reading minus the share that follows the EPS's own effort
driver_torque_raw = cp.vl['EPS_STEERING']['STEER_TORQUE_DRIVER']
eps_share = self.eps_torque_lagged.update(ret.steeringTorqueEps) / CarControllerParams.EPS_TORQUE_PER_DRIVER_TORQUE
ret.steeringTorque = driver_torque_raw + eps_share
# the torque reading is coarse: during an LCC override it only reached 2-3, but the EPS flagged the override itself.
# The EPS also sets that flag whenever the car is above about 121 km/h, with or without the driver (99% of frames
# above 121 km/h on a stock drive, and openpilot's own drive at 125 km/h), so above 118 km/h only the torque counts.
eps_override = cp.vl['EPS_STEERING']['DRIVER_OVERRIDE'] and ret.vEgoRaw < 118 * CV.KPH_TO_MS
self.driver_override_frames = self.driver_override_frames + 1 if eps_override else 0
torque_pressed = self.update_steering_pressed(abs(ret.steeringTorque) > CarControllerParams.STEER_DRIVER_ALLOWANCE, 5)
ret.steeringPressed = torque_pressed or self.driver_override_frames >= 2
# When to let go of the wheel: on the EPS's own flag, like stock LCC, or on the driver's torque. Not on the raw
# reading, which read 5-7 whenever the EPS pushed 65-95 in a curve: letting go on it dropped the EPS to 0 and back
# every 0.7 s (41 times in 14 min). The flag alone is not enough: above 118 km/h it is always set, and at walking
# pace it stayed off while openpilot pulled the wheel from +324 to -203 deg through the driver's hands.
self.driver_override = self.driver_override_frames >= 2 or torque_pressed
# While the wheel follows openpilot the share estimate overshoots, so there it only removes torque, and the flag
# needs torque against the EPS as well (see CarControllerParams.OVERRIDE_TRACKING_ERROR)
tracking_torque = ret.steeringTorque if ret.steeringTorque * eps_share <= 0 else \
(driver_torque_raw if driver_torque_raw * eps_share > 0 else 0.)
pressed = abs(tracking_torque) > CarControllerParams.STEER_DRIVER_ALLOWANCE
self.tracking_pressed_cnt = int(np.clip(self.tracking_pressed_cnt + (1 if pressed else -1), 0, 11))
opposing = tracking_torque * eps_share < 0 and abs(tracking_torque) >= CarControllerParams.OVERRIDE_OPPOSING_TORQUE
self.tracking_override_frames = self.tracking_override_frames + 1 if eps_override and opposing else 0
self.driver_override_tracking = self.tracking_override_frames >= 2 or self.tracking_pressed_cnt > 5
# The EPS reports whether it receives ADAS_LKA (0x83): losing it after it was received means our steering frame is
# missing or rejected (camera-unplug test). Not set before the camera's first frame after ignition.
lka_received = bool(cp.vl['EPS_STEERING']['ADAS_LKA_RECEIVED'])
self.lka_received_seen = self.lka_received_seen or lka_received
ret.steerFaultTemporary = self.lka_received_seen and not lka_received
# gear
ret.gearShifter = GEARS.get(int(cp.vl['VEHICLE_STATE']['GEAR']), GearShifter.unknown)
# body
ret.leftBlinker, ret.rightBlinker = self.update_blinker_from_lamp(50, cp.vl['BODY_CONTROL']['BLINKER_LEFT'] == 1,
cp.vl['BODY_CONTROL']['BLINKER_RIGHT'] == 1)
ret.doorOpen = bool(cp.vl['BODY_CONTROL']['DRIVER_DOOR_OPEN'])
ret.seatbeltUnlatched = bool(cp.vl['SEATBELT']['DRIVER_SEATBELT_UNLATCHED'])
# blind-spot radars: silent when stopped, so they are not timeout-checked (see get_can_parsers)
ret.leftBlindspot = bool(cp.vl['BSD_LEFT']['OBJECT_DETECTED'])
ret.rightBlindspot = bool(cp.vl['BSD_RIGHT']['OBJECT_DETECTED'])
# stock ACC / LCC, read from the camera side
ret.cruiseState.enabled = bool(cp.vl['POWERTRAIN_STATE']['ASSIST_ENGAGED'])
# the driver's cancel push, so a cancel the car makes by itself can be told apart from the driver's
prev_cancel = self.stalk_cancel
self.stalk_cancel = int(cp.vl['POWERTRAIN_STATE']['STALK_PUSH']) == STALK_CANCEL
ret.buttonEvents = create_button_events(int(self.stalk_cancel), int(prev_cancel), {1: ButtonType.cancel})
# latest VCU frame, copied by the controller to cancel ACC; None until received
self.powertrain_state = dict(cp.vl['POWERTRAIN_STATE']) if cp.ts_nanos['POWERTRAIN_STATE']['COUNTER'] > 0 else None
# ACC_STATE: 1 not ready (Park, brake, accelerator override), 2 ready, 3 engaged. Engaged also counts as
# available so that an accelerator override (state 1 while engaged) does not raise wrongCarMode
ret.cruiseState.available = ret.cruiseState.enabled or int(cp_cam.vl['ADAS_LKA']['ACC_STATE']) in (2, 3)
ret.cruiseState.speed = cp_cam.vl['ADAS_LKA']['ACC_SET_SPEED'] * CV.KPH_TO_MS
ret.cruiseState.speedCluster = ret.cruiseState.speed
ret.cruiseState.standstill = ret.cruiseState.enabled and ret.standstill
# the camera's forward collision warning, shown by openpilot too
ret.stockFcw = bool(cp_cam.vl['ROAD_SIGNS']['FCW'])
# the camera's posted speed limit, as the cluster shows it; offered to the speed limit controller as the dashboard
timestamp, expiry = parser_expiry(cp_cam, 'ROAD_SIGNS', 'SPEED_LIMIT')
if timestamp > self.dashboard_limit.observation.observed_ns:
status, value_mps = leapmotor_sign(int(cp_cam.vl['ROAD_SIGNS']['SPEED_LIMIT']))
self.dashboard_limit.update(timestamp, status, value_mps, valid_until_ns=expiry)
# latest camera frame, rebuilt by the controller; None until the camera's 0x83 has been received
self.adas_lka = dict(cp_cam.vl['ADAS_LKA']) if cp_cam.ts_nanos['ADAS_LKA']['COUNTER'] > 0 else None
return ret
@staticmethod
def get_can_parsers(CP):
return {
Bus.pt: CANParser(DBC[CP.carFingerprint][Bus.pt], [("BSD_LEFT", float('nan')), ("BSD_RIGHT", float('nan'))], 0),
Bus.cam: CANParser(DBC[CP.carFingerprint][Bus.pt], [], 2),
}
@@ -0,0 +1,19 @@
""" AUTO-FORMATTED USING opendbc/car/debug/format_fingerprints.py, EDIT STRUCTURE THERE."""
from opendbc.car.structs import CarParams
from opendbc.car.leapmotor.values import CAR
Ecu = CarParams.Ecu
FW_VERSIONS = {
CAR.LEAPMOTOR_B10: {
(Ecu.eps, 0x735, None): [
b'3401100-AG01\x00\x00\x00\x00\x00\x00\x00',
],
(Ecu.abs, 0x736, None): [
b'3565101-AG03\x00\x00\x00\x00\x00\x00\x00',
],
(Ecu.fwdCamera, 0x756, None): [
b'8021010-AH01\x00\x00\x00\x00\x00\x00\x00',
],
},
}
@@ -0,0 +1,34 @@
from opendbc.car import structs, get_safety_config
from opendbc.car.interfaces import CarInterfaceBase
from opendbc.car.leapmotor.carcontroller import CarController
from opendbc.car.leapmotor.carstate import CarState
from opendbc.car.leapmotor.values import LeapmotorSafetyFlags
class CarInterface(CarInterfaceBase):
CarState = CarState
CarController = CarController
@staticmethod
def _get_params(ret: structs.CarParams, candidate, fingerprint, car_fw, alpha_long, is_release, docs) -> structs.CarParams:
ret.brand = 'leapmotor'
ret.safetyConfigs = [get_safety_config(structs.CarParams.SafetyModel.leapmotor)]
# The camera's angle request (ADAS_LKA.STEER_ANGLE_REQ) leads the measured angle by 70-100 ms during LCC
ret.steerControlType = structs.CarParams.SteerControlType.angle
ret.steerActuatorDelay = 0.15
ret.steerLimitTimer = 0.4
ret.steerAtStandstill = False
ret.radarUnavailable = True
# Alpha longitudinal: the stock ACC keeps engagement, set speed (knob), cancel and the standstill hold; openpilot
# only replaces its acceleration request in ADAS_LKA, which openpilot already sends for steering.
ret.alphaLongitudinalAvailable = True
if alpha_long:
ret.openpilotLongitudinalControl = True
ret.safetyConfigs[0].safetyParam |= LeapmotorSafetyFlags.LONG_CONTROL.value
# the stock request leads the measured acceleration by about 0.2-0.25 s
ret.longitudinalActuatorDelay = 0.25
return ret
@@ -0,0 +1,138 @@
from opendbc.car.crc import CRC8H2F
# AUTOSAR E2E Profile 2 constants, one per counter value, for each message: the same algorithm as
# opendbc's volkswagen_mqb_meb_checksum. Learned from logs of a 2025 global-market Leapmotor B10 and
# exact on every frame tested from 3 other routes on 2 other days.
LEAPMOTOR_E2E_CONSTANTS: dict[int, list[int]] = {
0x083: [0xCD, 0x81, 0x0A, 0xC1, 0x99, 0x7F, 0x8D, 0x05, 0x3B, 0xA2, 0x43, 0xD2, 0xB6, 0x72, 0x2A, 0xD9],
0x084: [0x5A, 0x77, 0x5F, 0xEA, 0x3F, 0xCD, 0xF9, 0x2E, 0x34, 0xF1, 0x2C, 0x81, 0x60, 0x37, 0xC6, 0x5B],
0x0B1: [0x49, 0x56, 0x0E, 0x67, 0x81, 0x1E, 0x76, 0x9F, 0xBF, 0xC1, 0xE5, 0x6C, 0x96, 0x83, 0x7F, 0xC2],
0x0B6: [0x71, 0x0D, 0x0B, 0xC2, 0x08, 0xC6, 0x63, 0x4B, 0x3F, 0x2B, 0x06, 0x10, 0xF0, 0xD2, 0x87, 0x0D],
0x0B7: [0xEB, 0x4E, 0xAE, 0xCE, 0x79, 0x7C, 0x52, 0x03, 0x6A, 0x84, 0xC2, 0x3A, 0x0A, 0x64, 0x2F, 0x17],
0x0B8: [0xB9, 0x24, 0xDD, 0x54, 0x98, 0xE5, 0xB7, 0x87, 0x51, 0xDB, 0x71, 0x31, 0xF9, 0x26, 0x43, 0x6D],
0x0CB: [0x44, 0x73, 0x30, 0x2E, 0xA7, 0xAE, 0x40, 0x96, 0x33, 0x58, 0x84, 0x36, 0xF1, 0x43, 0xBF, 0x0A],
0x0CD: [0x93, 0x33, 0x70, 0x1A, 0x9A, 0xB5, 0xEA, 0x04, 0x7E, 0xD4, 0xB6, 0x9D, 0x8A, 0x2E, 0x18, 0x41],
0x0FA: [0x96, 0x97, 0x8B, 0x02, 0x69, 0xBB, 0x54, 0xE6, 0x4E, 0x46, 0x8D, 0x7B, 0xEA, 0x87, 0xE9, 0xB3],
0x0FD: [0x53, 0x58, 0x37, 0xDA, 0x94, 0x57, 0x79, 0x27, 0x8D, 0xDD, 0xD0, 0x39, 0x16, 0x84, 0x07, 0xAF],
0x134: [0x1A, 0x04, 0x9D, 0x41, 0xAB, 0x01, 0x5B, 0x2A, 0x8F, 0x6E, 0x46, 0xD0, 0xD8, 0xA8, 0x47, 0x2D],
0x138: [0xC1, 0x05, 0xD2, 0xD9, 0xAE, 0x93, 0xB1, 0x90, 0x42, 0x7C, 0x60, 0x33, 0x46, 0xB8, 0x6A, 0xE1],
0x142: [0x0E, 0x1E, 0xBF, 0x6C, 0x7F, 0xFA, 0xC0, 0x14, 0x8A, 0xD2, 0x52, 0x3C, 0x8B, 0xA6, 0x92, 0xAD],
0x182: [0xE8, 0x40, 0x60, 0xDE, 0xC2, 0xAC, 0xE3, 0xA4, 0x3D, 0x88, 0xD1, 0xEE, 0x51, 0x16, 0xAD, 0x49],
0x183: [0xF7, 0xC0, 0x40, 0xA6, 0xA5, 0xDE, 0x62, 0x1C, 0xAC, 0x5A, 0x4F, 0xA4, 0xE5, 0x18, 0x88, 0x08],
0x184: [0xD9, 0x90, 0x33, 0xE1, 0x3A, 0x1A, 0xDF, 0xC6, 0xB5, 0xDC, 0xEE, 0x04, 0xFA, 0xD7, 0xD4, 0x99],
0x185: [0x5D, 0x96, 0x82, 0x97, 0xB6, 0x8B, 0x24, 0x02, 0xEB, 0x69, 0x20, 0xBB, 0x77, 0x54, 0x86, 0xE6],
0x186: [0xD3, 0xE0, 0x75, 0x85, 0x83, 0x55, 0x33, 0xE3, 0x4C, 0x9C, 0x91, 0x1D, 0x23, 0x1A, 0xA6, 0x16],
0x18C: [0x0F, 0xD1, 0x6B, 0x63, 0x9E, 0x74, 0x22, 0x94, 0xD7, 0xA1, 0xE7, 0x6F, 0x9C, 0xCF, 0x96, 0xDD],
0x18D: [0x61, 0x4B, 0x17, 0xE4, 0x78, 0x0B, 0xA1, 0xB4, 0xBC, 0xD8, 0xEA, 0xF5, 0xD9, 0x21, 0xCA, 0x86],
0x227: [0x66, 0xF4, 0xA8, 0xC8, 0xBB, 0xA7, 0xAF, 0x2B, 0xD9, 0x7B, 0xC0, 0x50, 0x56, 0x0F, 0xCE, 0xED],
0x228: [0xC5, 0x9E, 0x5D, 0xA1, 0xAC, 0x96, 0x1B, 0x21, 0x82, 0xEE, 0xF9, 0x97, 0xB1, 0xCB, 0xB6, 0x13],
0x22A: [0xD5, 0xEB, 0xA2, 0x4E, 0x35, 0xAE, 0x51, 0xCE, 0x2D, 0x79, 0x9F, 0x7C, 0x34, 0x52, 0x09, 0x03],
0x233: [0xA5, 0xE9, 0x85, 0x04, 0xFB, 0x6C, 0xDF, 0xF1, 0xDE, 0x90, 0xA8, 0xCB, 0xDD, 0x3B, 0x80, 0x87],
0x241: [0x3F, 0xF7, 0x25, 0x5E, 0xAA, 0x47, 0x62, 0x61, 0x5B, 0x3C, 0xDC, 0xE5, 0x73, 0xB4, 0xED, 0x0D],
0x243: [0xAC, 0xEE, 0xB6, 0x68, 0x4D, 0x69, 0x1F, 0x0E, 0x86, 0x34, 0x6F, 0x46, 0xED, 0x38, 0x11, 0x1E],
0x24D: [0x0B, 0xC6, 0x3F, 0x10, 0x87, 0xF7, 0x42, 0xC5, 0x25, 0xDA, 0x40, 0x5E, 0x69, 0x4A, 0xAA, 0xA5],
0x25A: [0x64, 0x5D, 0x7D, 0x96, 0x3D, 0x82, 0xB9, 0x97, 0xD5, 0xB6, 0xAA, 0x8B, 0x5A, 0x24, 0xB4, 0x02],
0x290: [0x5C, 0x09, 0x71, 0x2F, 0x23, 0x73, 0x61, 0x25, 0x15, 0x48, 0x93, 0x65, 0x01, 0x4B, 0xAF, 0xF8],
0x2A3: [0x14, 0x99, 0x49, 0x0B, 0x04, 0xD5, 0x74, 0xC6, 0x17, 0xF1, 0xE1, 0x3F, 0x50, 0x9B, 0xCB, 0x10],
0x2D1: [0x0D, 0x28, 0xB8, 0x6B, 0x64, 0xDF, 0xEC, 0x74, 0xEA, 0x5D, 0x16, 0xD7, 0xC0, 0xC4, 0x7D, 0x6F],
0x2D5: [0xB1, 0xB8, 0x77, 0xDF, 0xED, 0xEA, 0x53, 0xD7, 0xCD, 0x7D, 0x44, 0x2E, 0x40, 0x58, 0xF1, 0x66],
0x2E1: [0x0E, 0x4D, 0xEE, 0x19, 0x73, 0x03, 0xAF, 0x8F, 0x32, 0x2E, 0x70, 0x31, 0x0B, 0xB3, 0xAE, 0x0E],
0x2E5: [0x15, 0xB9, 0xD1, 0xC1, 0x72, 0x93, 0x8C, 0x60, 0x12, 0xE1, 0x01, 0x77, 0xC4, 0xBF, 0x1F, 0x11],
0x331: [0x42, 0x4A, 0x62, 0xCD, 0x1B, 0xB4, 0xA0, 0x16, 0x14, 0xE8, 0x0A, 0x71, 0xEF, 0x24, 0x7C, 0xDF],
0x332: [0x23, 0xC8, 0x53, 0x83, 0xD9, 0x64, 0xD5, 0x0F, 0x89, 0xC7, 0xAB, 0xB7, 0x65, 0x3F, 0x9A, 0x2D],
0x3B0: [0x6D, 0x69, 0x44, 0xAC, 0x7A, 0x73, 0x06, 0x9C, 0x30, 0x17, 0x12, 0x2E, 0x8B, 0xEF, 0xA7, 0xCF],
0x3B2: [0xA1, 0x21, 0x97, 0x13, 0x68, 0x02, 0x10, 0x43, 0xBB, 0x0E, 0x57, 0xE6, 0xDF, 0xBD, 0x46, 0x8E],
0x3CE: [0x6C, 0x14, 0x3C, 0xAD, 0x93, 0x59, 0x1C, 0x4D, 0xD8, 0x33, 0x5D, 0x89, 0x7B, 0x08, 0x70, 0x34],
}
def leapmotor_checksum(address: int, sig, d: bytearray) -> int:
constants = LEAPMOTOR_E2E_CONSTANTS.get(address)
if constants is None:
return -1 # unknown message: never matches, so the frame is rejected rather than trusted
crc = 0xFF
for b in d[1:]:
crc = CRC8H2F[crc ^ b]
crc = CRC8H2F[crc ^ constants[d[1] & 0x0F]]
return crc ^ 0xFF
# LCC_RAMP (bytes 16-17 of ADAS_LKA): 0x7801 when LCC is not steering. While stock LCC steers it moves down a ladder of
# 254 per step, one step per frame: from idle to about 31 steps when LCC starts, then deeper with more lateral
# acceleration and speed, and back to idle at once when LCC stops. The step count sets how much torque the EPS may use
# (about +/-10 early in the ramp, +/-45 at 30-31 steps, +/-70 at 42-46). Stock LCC on 3 routes (142,234 frames):
# steps = 19.1 + 9.94 * |lateral accel| + 0.112 * speed (km/h), R^2 0.83, always 25-46. With the idle word the EPS only
# applied torque to the right; with a fixed 30 steps (0x5A3D) it could not hold a curve at 75 km/h (torque flat at 61).
LCC_RAMP_IDLE = 0x7801
LCC_RAMP_STEP = 254
LCC_RAMP_STEPS_MIN = 25
LCC_RAMP_STEPS_MAX = 46
# Ramp-in speed below LCC_RAMP_STEPS_MIN: stock moves one step per frame (0.5 s to 25 steps), and 50-68% of the frames
# where the wheel fell > 5 deg behind were in that ramp-in. Two steps per frame reaches 25 steps in 0.25 s; deeper than
# that, one step per frame as stock. Not seen from stock: the EPS's response to skipped ladder steps is untested.
LCC_RAMP_IN_STEPS_PER_FRAME = 2
def lcc_ramp_target(lat_accel: float, v_ego_kph: float, extra_steps: int = 0) -> int:
"""LCC_RAMP word that stock LCC would send for this lateral acceleration (m/s^2) and speed, extra_steps deeper,
never beyond the deepest stock value."""
steps = min(max(round(19.1 + 9.94 * abs(lat_accel) + 0.112 * v_ego_kph), LCC_RAMP_STEPS_MIN), LCC_RAMP_STEPS_MAX)
return LCC_RAMP_IDLE - LCC_RAMP_STEP * min(steps + max(extra_steps, 0), LCC_RAMP_STEPS_MAX)
def lcc_ramp_next(word: int, lat_active: bool, target: int) -> int:
"""Next LCC_RAMP value while steering: toward target, LCC_RAMP_IN_STEPS_PER_FRAME ladder steps per frame while ramping
in (shallower than LCC_RAMP_STEPS_MIN), one step per frame otherwise; straight back to idle when not steering."""
if not lat_active:
return LCC_RAMP_IDLE
if word > target:
ramping_in = word > LCC_RAMP_IDLE - LCC_RAMP_STEP * LCC_RAMP_STEPS_MIN
return max(word - LCC_RAMP_STEP * (LCC_RAMP_IN_STEPS_PER_FRAME if ramping_in else 1), target)
if word < target:
return word + LCC_RAMP_STEP
return word
def create_steering_control(packer, camera_lka: dict, apply_angle: float, lat_active: bool, lcc_ramp: int = LCC_RAMP_IDLE,
accel: float | None = None):
"""Rebuild ADAS_LKA (0x83) from the camera's latest frame, replacing only the steering fields.
Every other field (ACC state, acceleration request, set speed, constants) is copied unchanged, so the
stock ACC keeps working while openpilot steers. The packer recomputes the E2E checksum and runs its own
counter, since the EPS only ever sees openpilot's frames once the camera's are blocked.
While steering, LCC_RAMP carries lcc_ramp (see lcc_ramp_next); otherwise it is the camera's.
With openpilot longitudinal, accel (m/s^2) replaces the camera's ACC_ACCEL_REQ; None keeps the camera's.
"""
values = {k: v for k, v in camera_lka.items() if k not in ("CHECKSUM", "COUNTER")}
if accel is not None:
values["ACC_ACCEL_REQ"] = accel
values["STEER_ANGLE_REQ"] = apply_angle
values["LCC_STEERING_ACTIVE_COPY"] = 1 if lat_active else 0
if lat_active:
values["LCC_RAMP"] = lcc_ramp
return packer.make_can_msg("ADAS_LKA", 0, values)
STALK_PUSH_UP_CANCEL = 3
# A real ADAS_LKA frame from the camera with ACC and LCC off, used until the camera's first frame is received
ADAS_LKA_IDLE = bytes.fromhex("260500446411E100007D00700043E4000178007D000000000000000000000000")
def decode_adas_lka_idle() -> dict:
from opendbc.can.dbc import DBC # imported here: opendbc.can.dbc imports this module for the checksum
msg = DBC("leapmotor_b10").addr_to_msg[0x83]
return {name: sig.get_raw_value(ADAS_LKA_IDLE) * sig.factor + sig.offset for name, sig in msg.sigs.items()}
def create_cancel(packer, powertrain_state: dict):
"""Copy of the VCU's latest POWERTRAIN_STATE (0xB7) with the right stalk pushed up, sent to the camera (bus 2).
The camera runs ACC and reads the stalk from this frame; pushing the stalk up cancels ACC and LCC (14 of 14 logged
pushes ended assist within 0.25 s). The copy uses the next counter value, so it takes the place of the next real
frame. The safety model only allows this frame with the stalk pushed up.
"""
values = {k: v for k, v in powertrain_state.items() if k != "CHECKSUM"}
values["STALK_PUSH"] = STALK_PUSH_UP_CANCEL
values["COUNTER"] = (int(powertrain_state["COUNTER"]) + 1) % 16
return packer.make_can_msg("POWERTRAIN_STATE", 2, values)
@@ -0,0 +1,419 @@
import unittest
from opendbc.can import CANPacker
from opendbc.can.dbc import DBC
from opendbc.car import Bus, structs
from opendbc.car.leapmotor import leapmotorcan
from opendbc.car.leapmotor.carcontroller import CarController, get_safety_CP
from opendbc.car.leapmotor.leapmotorcan import leapmotor_checksum
from opendbc.car.leapmotor.values import DBC as LEAPMOTOR_DBC, CarControllerParams
DBC_NAMES = LEAPMOTOR_DBC["LEAPMOTOR_B10"]
# Real ADAS_LKA (0x83) frames from a 2025 global-market B10: stock LCC steering, ACC only, and assist off
REAL_ADAS_LKA = {
"lcc": [
"6D0C004666007D00007D007009E87E00375D007D000000000000000000000000",
"600D004664007D00007D007008A67F004D53007D000000000000000000000000",
"A808004664808900007D007008E87E004158007D000000000000000000000000",
],
"acc": [
"B90A005A64005F00007D007000A47F000178007D000008000000000000000000",
"B40200465F802500007D007000087F000178007D000000000000000000000000",
"BA03004A64C07100007D0070004F7E000178007D000008000000000000000000",
],
"off": [
"260500446411E100007D00700043E4000178007D000000000000000000000000",
"4B0700446411E100007D007000A05A000178007D000000000000000000000000",
"4008004464918900007D0070002D7E000178007D000000000000000000000000",
],
}
STEERING_BYTES = {12, 13, 14, 16, 17} # LCC_STEERING_ACTIVE_COPY (bit 99), STEER_ANGLE_REQ (104|16), LCC_RAMP (128|16)
# Real POWERTRAIN_STATE (0xB7) frames while driving with ACC engaged
REAL_POWERTRAIN_STATE = [
"450B04401004B42C000000800000000055E2048D5E2013000000000000000000",
"070C04401004B42C000000800000000055E204855E2A13000000000000000000",
]
# Real frames from the filmed figure-eights at the moments of hardest right and left turn, as measured by the
# comma's own gyro (livePose.angularVelocityDevice.z: +36.6 deg/s right, -44.6 deg/s left)
HARD_RIGHT = {0x18D: "0B0602CAE4009EC5869A5E012C2C0000D5128658A3E803000000000000000000", 0x233: "4C06C88947811100"}
HARD_LEFT = {0x18D: "130E02BA1D0F644386C24D010001000004128702A3E803000000000000000000", 0x233: "7E0A43A647AD3100"}
# Real ROAD_SIGNS (0x142) frames from the camera just before and during a forward collision warning the driver reported
FCW_FRAMES = {False: "F204F4F14002001C8032120000000000", True: "050E310D4402001C8032120000000000"}
class TestLeapmotorCan(unittest.TestCase):
def setUp(self):
self.msg = DBC("leapmotor_b10").addr_to_msg[0x83]
def unpack(self, dat: bytes) -> dict:
return {n: s.get_raw_value(dat) * s.factor + s.offset for n, s in self.msg.sigs.items()}
def test_fcw(self):
sig = DBC("leapmotor_b10").addr_to_msg[0x142].sigs["FCW"]
for fcw, hexdata in FCW_FRAMES.items():
dat = bytes.fromhex(hexdata)
self.assertEqual(sig.get_raw_value(dat), int(fcw))
self.assertEqual(dat[0], leapmotor_checksum(0x142, None, bytearray(dat)))
def test_sign_convention(self):
# openpilot expects positive = left for steering angle and yaw rate
dbc = DBC("leapmotor_b10")
def decode(addr, hexdata, name):
sig = dbc.addr_to_msg[addr].sigs[name]
return sig.get_raw_value(bytes.fromhex(hexdata)) * sig.factor + sig.offset
self.assertLess(decode(0x18D, HARD_RIGHT[0x18D], "STEER_ANGLE"), -400)
self.assertLess(decode(0x233, HARD_RIGHT[0x233], "YAW_RATE"), -30)
self.assertGreater(decode(0x18D, HARD_LEFT[0x18D], "STEER_ANGLE"), 400)
self.assertGreater(decode(0x233, HARD_LEFT[0x233], "YAW_RATE"), 30)
def test_dbc_covers_every_used_bit(self):
# unpacking then packing a real frame (with its own counter) must reproduce it exactly
packer = CANPacker("leapmotor_b10")
for frames in REAL_ADAS_LKA.values():
for hexdata in frames:
dat = bytes.fromhex(hexdata)
values = {k: v for k, v in self.unpack(dat).items() if k != "CHECKSUM"}
self.assertEqual(bytes(packer.pack(0x83, values)), dat)
def test_cancel_changes_only_stalk_and_counter(self):
msg = DBC("leapmotor_b10").addr_to_msg[0xB7]
for hexdata in REAL_POWERTRAIN_STATE:
dat = bytes.fromhex(hexdata)
vals = {n: s.get_raw_value(dat) * s.factor + s.offset for n, s in msg.sigs.items()}
addr, out, bus = leapmotorcan.create_cancel(CANPacker("leapmotor_b10"), vals)
self.assertEqual((addr, bus), (0xB7, 2))
self.assertEqual(out[0], leapmotor_checksum(0xB7, None, bytearray(out)))
self.assertEqual(out[1] & 0xF, (dat[1] + 1) & 0xF)
self.assertEqual(out[5] & 0x3, 3)
for i in range(2, len(dat)):
if i != 5:
self.assertEqual(out[i], dat[i], f"byte {i}")
self.assertEqual(out[5] & ~0x3, dat[5] & ~0x3)
def test_rebuild_changes_only_steering(self):
for kind, frames in REAL_ADAS_LKA.items():
for hexdata in frames:
dat = bytes.fromhex(hexdata)
camera = self.unpack(dat)
for lat_active, angle in ((False, camera["STEER_ANGLE_REQ"]), (True, -123.46), (True, 456.78)):
with self.subTest(kind=kind, lat_active=lat_active, angle=angle):
packer = CANPacker("leapmotor_b10")
ramp = 0x6B0F # a value in the middle of the stock ramp
addr, out, bus = leapmotorcan.create_steering_control(packer, camera, angle, lat_active, ramp)
self.assertEqual((addr, bus), (0x83, 0))
self.assertEqual(out[0], leapmotor_checksum(0x83, None, bytearray(out)))
for i in range(2, len(dat)):
if i not in STEERING_BYTES:
self.assertEqual(out[i], dat[i], f"byte {i}")
got = self.unpack(bytes(out))
self.assertAlmostEqual(got["STEER_ANGLE_REQ"], angle, delta=0.011)
self.assertEqual(got["LCC_STEERING_ACTIVE_COPY"], int(lat_active))
# LCC_RAMP: openpilot's ramp while steering, the camera's otherwise
self.assertEqual(got["LCC_RAMP"], ramp if lat_active else camera["LCC_RAMP"])
# the ACC fields pass through untouched
for sig in ("ACC_STATE", "ACC_ACCEL_REQ", "ACC_SET_SPEED", "ASSIST_OFF", "CONSTANT_72", "CONSTANT_152"):
self.assertEqual(got[sig], camera[sig], sig)
def test_lcc_ramp_matches_stock(self):
# stock LCC engagement: LCC_RAMP goes 0x7801, 0x7703, 0x7605, ... one 254 step per frame, then jumps back
straight_90 = leapmotorcan.lcc_ramp_target(0.15, 90.0) # a typical straight road: stock median there is 31 steps
self.assertEqual(straight_90, 0x593F)
word, seen = leapmotorcan.LCC_RAMP_IDLE, []
for _ in range(40):
word = leapmotorcan.lcc_ramp_next(word, True, straight_90)
seen.append(word)
# two ladder steps per frame up to 25 steps (stock: one), then one per frame as stock
self.assertEqual(seen[:3], [0x7605, 0x7409, 0x720D])
steps_seen = [(leapmotorcan.LCC_RAMP_IDLE - w) // leapmotorcan.LCC_RAMP_STEP for w in seen]
self.assertTrue(all((leapmotorcan.LCC_RAMP_IDLE - w) % leapmotorcan.LCC_RAMP_STEP == 0 for w in seen)) # on the ladder
self.assertEqual(steps_seen.index(26), 12) # 25 steps passed in 13 frames, about 0.26 s
self.assertTrue(all(b - a == 1 for a, b in zip(steps_seen[12:], steps_seen[13:], strict=False) if b != a))
self.assertEqual(seen.index(straight_90), 17) # 18 frames instead of stock's 31
self.assertEqual(seen[-1], straight_90)
# never past the target, even when a double step would overshoot it
shallow = leapmotorcan.LCC_RAMP_IDLE - 24 * leapmotorcan.LCC_RAMP_STEP
target_25 = leapmotorcan.LCC_RAMP_IDLE - 25 * leapmotorcan.LCC_RAMP_STEP
self.assertEqual(leapmotorcan.lcc_ramp_next(shallow, True, target_25), target_25)
self.assertEqual(leapmotorcan.lcc_ramp_next(seen[-1], False, straight_90), leapmotorcan.LCC_RAMP_IDLE)
# one step per frame toward a new target, both ways
deeper = leapmotorcan.lcc_ramp_target(1.5, 75.0)
self.assertEqual(leapmotorcan.lcc_ramp_next(straight_90, True, deeper), straight_90 - leapmotorcan.LCC_RAMP_STEP)
self.assertEqual(leapmotorcan.lcc_ramp_next(deeper, True, straight_90), deeper + leapmotorcan.LCC_RAMP_STEP)
# stock medians per lateral-acceleration band (about 90 km/h), within 2 steps, and the stock range 25-46 steps
for alat, stock in ((0.15, 0x593F), (0.45, 0x5547), (0.8, 0x534B), (1.25, 0x4F53)):
self.assertLessEqual(abs(leapmotorcan.lcc_ramp_target(alat, 90.0) - stock), 2 * leapmotorcan.LCC_RAMP_STEP, alat)
for alat, v in ((0.0, 0.0), (5.0, 150.0)):
steps = (leapmotorcan.LCC_RAMP_IDLE - leapmotorcan.lcc_ramp_target(alat, v)) // leapmotorcan.LCC_RAMP_STEP
self.assertTrue(leapmotorcan.LCC_RAMP_STEPS_MIN <= steps <= leapmotorcan.LCC_RAMP_STEPS_MAX)
# the real stock frames agree: idle when not steering, on the ladder within the stock range while steering
for hexdata in REAL_ADAS_LKA["acc"] + REAL_ADAS_LKA["off"]:
self.assertEqual(self.unpack(bytes.fromhex(hexdata))["LCC_RAMP"], leapmotorcan.LCC_RAMP_IDLE)
for hexdata in REAL_ADAS_LKA["lcc"]:
# stock occasionally sits 2 off the ladder (steps of -2/+2 also appear between frames)
steps = round((leapmotorcan.LCC_RAMP_IDLE - int(self.unpack(bytes.fromhex(hexdata))["LCC_RAMP"])) / leapmotorcan.LCC_RAMP_STEP)
self.assertLessEqual(abs(leapmotorcan.LCC_RAMP_IDLE - steps * leapmotorcan.LCC_RAMP_STEP - int(self.unpack(bytes.fromhex(hexdata))["LCC_RAMP"])), 2)
self.assertTrue(leapmotorcan.LCC_RAMP_STEPS_MIN <= steps <= leapmotorcan.LCC_RAMP_STEPS_MAX)
def test_ramp_boost(self):
deepest = leapmotorcan.LCC_RAMP_IDLE - leapmotorcan.LCC_RAMP_STEP * leapmotorcan.LCC_RAMP_STEPS_MAX
# extra steps go deeper, never beyond the deepest stock value
base = leapmotorcan.lcc_ramp_target(0.1, 15.0)
self.assertEqual(leapmotorcan.lcc_ramp_target(0.1, 15.0, 3), base - 3 * leapmotorcan.LCC_RAMP_STEP)
self.assertEqual(leapmotorcan.lcc_ramp_target(0.1, 15.0, 100), deepest)
self.assertEqual(leapmotorcan.lcc_ramp_target(3.0, 120.0, 5), deepest)
from types import SimpleNamespace
from opendbc.car.leapmotor.carcontroller import CarController, get_safety_CP
from opendbc.car.leapmotor.values import CarControllerParams, DBC as LEAPMOTOR_DBC
controller = CarController(LEAPMOTOR_DBC["LEAPMOTOR_B10"], get_safety_CP())
def cs(angle, kph, eps=0):
return SimpleNamespace(out=SimpleNamespace(steeringAngleDeg=angle, vEgoRaw=kph / 3.6, steeringTorqueEps=eps))
controller.apply_angle_last = 90.
for i in range(30): # wheel 10 deg behind at 15 km/h: one step deeper per frame, up to the stock maximum
controller.ramp_boost = controller.update_ramp_boost(True, cs(80., 15.))
self.assertEqual(controller.ramp_boost, min(i + 1, leapmotorcan.LCC_RAMP_STEPS_MAX - leapmotorcan.LCC_RAMP_STEPS_MIN))
controller.ramp_boost = controller.update_ramp_boost(True, cs(88., 15.)) # 2 deg behind: hold
self.assertEqual(controller.ramp_boost, 21)
controller.ramp_boost = controller.update_ramp_boost(True, cs(89.5, 15.)) # caught up: one step back
self.assertEqual(controller.ramp_boost, 20)
self.assertEqual(controller.update_ramp_boost(False, cs(80., 15.)), 0) # not steering
self.assertEqual(controller.update_ramp_boost(True, cs(80., CarControllerParams.RAMP_BOOST_MAX_SPEED + 1)), 0) # fast
# near the EPS torque at which it flags an override by itself: no deeper, then back off, even while lagging
hold, back = CarControllerParams.RAMP_BOOST_EPS_TORQUE_HOLD, CarControllerParams.RAMP_BOOST_EPS_TORQUE_BACK
controller.ramp_boost = 10
for eps in (hold, -hold, back - 1, -(back - 1)):
self.assertEqual(controller.update_ramp_boost(True, cs(80., 15., eps)), 10)
for eps in (back, -back, -218):
controller.ramp_boost = 10
self.assertEqual(controller.update_ramp_boost(True, cs(80., 15., eps)), 9)
self.assertEqual(controller.update_ramp_boost(True, cs(80., 15., hold - 1)), 11) # below the hold: deeper again
def test_driver_torque_lags_the_eps(self):
from opendbc.car.leapmotor.carstate import CarState
from opendbc.car.leapmotor.interface import CarInterface
def pressed(driver, eps):
CP = CarInterface.get_non_essential_params("LEAPMOTOR_B10")
CS = CarState(CP)
parsers = CS.get_can_parsers(CP)
packer = CANPacker("leapmotor_b10")
out = []
for i, (d, e) in enumerate(zip(driver, eps, strict=True)):
dat = packer.make_can_msg("EPS_STEERING", 0, {"STEER_TORQUE_DRIVER": d, "STEER_TORQUE_EPS": e, "COUNTER": i % 16})[1]
parsers[Bus.pt].update([(int((i + 1) * 1e7), [(0x18D, dat, 0)])])
parsers[Bus.cam].update([(int((i + 1) * 1e7), [])])
CS.update(parsers)
out.append(CS.driver_override)
return out
# hands off in a roundabout at 28 km/h (route 264): the EPS swings -99 -> +98 within 0.1 s while the reading barely
# moves; subtracting the EPS's share without its lag read above 3 for 8 of these frames and let go of the wheel
driver = [2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, -1, -1, -1, -1, -1, -1, -1, 0]
eps = [9, 1, -16, -14, -22, -28, -31, -38, -44, -37, -18, -1, 15, 25, 27, 20, 17, 13, 8, -9, -37, -73, -99, -84, -52,
-4, 58, 78, 98, 96, 75, 53, 35, 16, 0, -15]
self.assertFalse(any(pressed(driver, eps)))
# the driver's lane-change nudge at 126 km/h (route 25c): the EPS holds -57 against the hands, the reading stays at 0
driver = [1, 1, 1, 1, 1, 0, 0, 0, 0, 1] + [0] * 20
eps = [-12, -7, -7, -6, -8, -14, -28, -47, -57, -56] + [-57] * 20
self.assertTrue(any(pressed(driver, eps)))
def test_override_while_the_wheel_follows(self):
# route 0000000a 12:31:42.9, left bend at 33 km/h, the driver's hand resting on the wheel: the EPS holds about 130 into
# the turn, the reading follows less of it than assumed and the EPS sets its own flag. The previous rule let go and
# the wheel sprang back 14 deg; the tracking rule keeps steering. A driver turning against the EPS still counts.
from opendbc.car.leapmotor.carstate import CarState
from opendbc.car.leapmotor.interface import CarInterface
def run(frames, angle=-41.):
CP = CarInterface.get_non_essential_params("LEAPMOTOR_B10")
CS = CarState(CP)
parsers = CS.get_can_parsers(CP)
packer = CANPacker("leapmotor_b10")
for i, (driver, eps, flag) in enumerate(frames):
dat = packer.make_can_msg("EPS_STEERING", 0, {"STEER_TORQUE_DRIVER": driver, "STEER_TORQUE_EPS": eps, "DRIVER_OVERRIDE": flag,
"STEER_ANGLE": angle, "COUNTER": i % 16})[1]
parsers[Bus.pt].update([(int((i + 1) * 1e7), [(0x18D, dat, 0)])])
parsers[Bus.cam].update([(int((i + 1) * 1e7), [])])
CS.update(parsers)
return CS
hands_off = [(-4, 120, 0)] * 40 + [(-5, 133, 0)] * 3 + [(-3, 133, 1)] * 3
CS = run(hands_off)
self.assertTrue(CS.driver_override)
self.assertFalse(CS.driver_override_tracking)
# the driver straightens the wheel against the EPS: the reading goes well past the EPS's share
CS = run([(-4, 120, 0)] * 40 + [(-16, 133, 1)] * 8)
self.assertTrue(CS.driver_override)
self.assertTrue(CS.driver_override_tracking)
def test_tracking_rule_only_while_the_wheel_follows(self):
from types import SimpleNamespace
from opendbc.car import structs as car_structs
from opendbc.car.leapmotor.carcontroller import CarController as Controller, get_safety_CP as safety_CP
from opendbc.car.leapmotor.values import DBC as CAR_DBC
def steering(wheel, command=-43.):
controller = Controller(CAR_DBC["LEAPMOTOR_B10"], safety_CP())
CC = car_structs.CarControl()
CC.latActive = True
CC.actuators.steeringAngleDeg = command
CS = SimpleNamespace(driver_override=False, driver_override_tracking=False, adas_lka=None,
powertrain_state=None, out=SimpleNamespace(steeringAngleDeg=-43., vEgoRaw=33 / 3.6, steeringTorqueEps=130))
controller.lat_active_last, controller.apply_angle_last = True, command # steering, the wheel following
CS.driver_override = True
CS.out.steeringAngleDeg = wheel
controller.update(CC.as_reader(), CS, 0)
return controller.lat_active_last
self.assertTrue(steering(-41.)) # follows within 3 deg: the tracking rule, which sees no driver
self.assertTrue(steering(1., command=2.)) # also near straight ahead
self.assertFalse(steering(-36.)) # held 7 deg short: the previous rule lets go
self.assertFalse(steering(3., command=12.)) # held straight against a 12 deg command (route 00000010 23:18:35)
def test_accel_replaces_only_the_request(self):
# with openpilot longitudinal, only ACC_ACCEL_REQ changes besides the steering fields
for hexdata in REAL_ADAS_LKA["acc"]:
dat = bytes.fromhex(hexdata)
camera = self.unpack(dat)
for accel in (-3.5, -0.75, 0.0, 1.2):
_, out, _ = leapmotorcan.create_steering_control(CANPacker("leapmotor_b10"), camera, camera["STEER_ANGLE_REQ"], False,
accel=accel)
got = self.unpack(bytes(out))
self.assertAlmostEqual(got["ACC_ACCEL_REQ"], accel, delta=0.026)
for i in range(2, len(dat)):
if i not in STEERING_BYTES | {4}:
self.assertEqual(out[i], dat[i], f"byte {i}")
def test_long_accel(self):
CP = get_safety_CP()
CP.openpilotLongitudinalControl = True
CC = structs.CarControl()
controller = CarController(DBC_NAMES, CP)
limits = CarControllerParams
cases = [
# longActive, ACC_STATE, camera request, openpilot request -> sent (None = the camera's)
(False, 3, -1.0, -0.5, None), # openpilot not in control
(True, 2, 0.0, -0.5, None), # stock ACC not engaged
(True, 1, 1.5, -0.5, None), # accelerator override
(True, 3, -1.0, -0.5, -0.5), # openpilot may brake less than stock ACC's normal braking
(True, 3, -1.0, 5.0, limits.ACCEL_MAX),
(True, 3, -1.0, -9.0, limits.ACCEL_MIN),
(True, 3, -2.0, -0.5, -2.0), # but never less than the camera's hard braking
(True, 3, -2.6, -3.0, -3.0),
]
for long_active, acc_state, camera_accel, accel, expected in cases:
with self.subTest(long_active=long_active, acc_state=acc_state, camera_accel=camera_accel, accel=accel):
CC.longActive = long_active
CC.actuators.accel = accel
self.assertEqual(controller.long_accel(CC, {"ACC_STATE": acc_state, "ACC_ACCEL_REQ": camera_accel}), expected)
# without openpilot longitudinal the camera's request always goes through
CP.openpilotLongitudinalControl = False
CC.longActive = True
self.assertIsNone(CarController(DBC_NAMES, CP).long_accel(CC, {"ACC_STATE": 3, "ACC_ACCEL_REQ": -1.0}))
def test_take_back(self):
from types import SimpleNamespace
from opendbc.car import structs as car_structs
from opendbc.car.leapmotor.carcontroller import CarController as Controller, get_safety_CP as safety_CP
from opendbc.car.leapmotor.values import DBC as CAR_DBC
def steering_after_let_go(wanted, wheel, kph=25.):
controller = Controller(CAR_DBC["LEAPMOTOR_B10"], safety_CP())
CC = car_structs.CarControl()
CC.latActive = True
CC.actuators.steeringAngleDeg = wanted
CS = SimpleNamespace(driver_override=False, adas_lka=None, powertrain_state=None,
out=SimpleNamespace(steeringAngleDeg=wheel, vEgoRaw=kph / 3.6, steeringTorqueEps=0))
controller.update(CC.as_reader(), CS, 0)
return controller.lat_active_last
# right after the driver lets go in a bend the wheel is 11-27 deg from the model's angle: take it back at once
self.assertTrue(steering_after_let_go(100., 73.))
self.assertTrue(steering_after_let_go(100., 100. - 44.))
# the case the check was made for: wheel at +308 deg, model at +24, at walking pace
self.assertFalse(steering_after_let_go(24., 308., kph=5.))
def test_eps_status_bit_is_not_torque(self):
# Real EPS_STEERING frames from route 26e (22:19:39, openpilot steering at 60 km/h): bit 180 turns on for 1 s. Read
# as part of the torque it added 4096, which looked like a driver torque of +264 and let go of the wheel mid-turn.
frames = ["350B0265810000448EF25001070700002B02870FA30904000000000000000000",
"5E0C0265810103448EF75001070700002B02870FA30814000000000000000000"]
sigs = DBC("leapmotor_b10").addr_to_msg[0x18D].sigs
for hexdata, (torque, status) in zip(frames, ((33, 0), (32, 1)), strict=True):
dat = bytes.fromhex(hexdata)
self.assertEqual(dat[0], leapmotor_checksum(0x18D, None, bytearray(dat)))
eps = sigs["STEER_TORQUE_EPS"]
self.assertEqual(eps.get_raw_value(dat) * eps.factor + eps.offset, torque)
self.assertEqual(sigs["EPS_STATUS_180"].get_raw_value(dat), status)
from opendbc.car.leapmotor.carstate import CarState
from opendbc.car.leapmotor.interface import CarInterface
CP = CarInterface.get_non_essential_params("LEAPMOTOR_B10")
CS = CarState(CP)
parsers = CS.get_can_parsers(CP)
for i in range(20):
parsers[Bus.pt].update([(int((i + 1) * 1e7), [(0x18D, bytes.fromhex(frames[min(i, 1)]), 0)])])
parsers[Bus.cam].update([(int((i + 1) * 1e7), [])])
ret = CS.update(parsers)
self.assertLess(abs(ret.steeringTorqueEps), 100)
self.assertFalse(CS.driver_override)
def test_dashboard_speed_limit(self):
# the camera's posted limit is offered as the dashboard source, and expires with the camera's frames
from opendbc.car.dashboard_speed_limit import Status
from opendbc.car.leapmotor.carstate import CarState
from opendbc.car.leapmotor.interface import CarInterface
CP = CarInterface.get_non_essential_params("LEAPMOTOR_B10")
CS = CarState(CP)
parsers = CS.get_can_parsers(CP)
packer = CANPacker("leapmotor_b10")
def frame(i, limit):
t = int((i + 1) * 2e7)
parsers[Bus.pt].update([(t, [])])
parsers[Bus.cam].update([(t, [packer.make_can_msg("ROAD_SIGNS", 2, {"SPEED_LIMIT": limit, "COUNTER": i % 16})])])
CS.update(parsers)
return CS.dashboard_limit.observation, t
for i in range(60): # the parser learns the camera's frame rate, and so the expiry, after 1 s
observation, t = frame(i, 50)
self.assertEqual(observation.status, Status.VALID)
self.assertAlmostEqual(observation.speed_mps, 50 / 3.6)
self.assertEqual(observation.observed_ns, t)
self.assertGreater(observation.valid_until_ns, t)
episode = observation.episode
observation, _ = frame(60, 30)
self.assertAlmostEqual(observation.speed_mps, 30 / 3.6)
self.assertGreater(observation.episode, episode)
for i, limit in enumerate((0, 255), start=61):
observation, _ = frame(i, limit)
self.assertEqual(observation.status, Status.UNKNOWN)
def test_cancel_push_is_a_cancel_button(self):
# only the stalk pushed up (STALK_PUSH 3) is reported, as a cancel press and release; the engage pushes are not
from opendbc.car.leapmotor.carstate import CarState
from opendbc.car.leapmotor.interface import CarInterface
CP = CarInterface.get_non_essential_params("LEAPMOTOR_B10")
CS = CarState(CP)
parsers = CS.get_can_parsers(CP)
packer = CANPacker("leapmotor_b10")
def frame(i, stalk):
msgs = [packer.make_can_msg("POWERTRAIN_STATE", 0, {"ASSIST_ENGAGED": 1, "STALK_PUSH": stalk, "COUNTER": i % 16})]
parsers[Bus.pt].update([(int((i + 1) * 1e7), msgs)])
parsers[Bus.cam].update([(int((i + 1) * 1e7), [])])
return [(b.type, b.pressed) for b in CS.update(parsers).buttonEvents]
cancel = structs.CarState.ButtonEvent.Type.cancel
pushes = [frame(i, stalk) for i, stalk in enumerate((0, 1, 1, 0, 2, 0, 3, 3, 0))]
self.assertEqual(pushes, [[], [], [], [], [], [], [(cancel, True)], [], [(cancel, False)]])
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,133 @@
from dataclasses import dataclass, field
from enum import IntFlag
from opendbc.car import Bus, CarSpecs, DbcDict, PlatformConfig, Platforms
from opendbc.car.docs_definitions import CarDocs, CarHarness, CarParts
from opendbc.car.lateral import AngleSteeringLimitsVM
from opendbc.car.fw_query_definitions import FwQueryConfig, Request
from opendbc.car.structs import CarParams
Ecu = CarParams.Ecu
class CarControllerParams:
STEER_STEP = 2 # ADAS_LKA (0x83) is sent at 50 Hz
# Must match opendbc/safety/modes/leapmotor.h. openpilot's standard vehicle-model limits: lateral accel and
# lateral jerk of about 3.6 (m/s^2, m/s^3), so near-full lock is allowed up to about 15 km/h (U-turns) and
# about 50 deg at 50 km/h. Stock LCC stays below 2.3 m/s^2 on every recorded route.
ANGLE_LIMITS: AngleSteeringLimitsVM = AngleSteeringLimitsVM(
500, # deg; mechanical lock is about 522 deg, keep a margin so the EPS never drives into the end stop
MAX_ANGLE_RATE=5, # deg per 20 ms frame (250 deg/s): lock to lock in about 4 s. EPS fault rate untested
)
# EPS_STEERING.STEER_TORQUE_DRIVER (unit unknown) also follows the EPS's own effort: while openpilot steered and the
# EPS flagged no override it read -1 per 16.8 of STEER_TORQUE_EPS (r -0.88, 317k frames on 2 drives). Adding that
# share back leaves the driver's torque: above 3 on 0.14% of those frames but on 75% of frames the EPS flagged as
# overrides. With the 5-frame debounce in carstate it caught all 3 of the driver's lane-change nudges at 125 km/h,
# where the raw reading stayed at 1, and nothing else above 118 km/h over the 2 drives.
# The reading lags the EPS by a few frames: when the EPS swung its torque quickly in roundabouts (e.g. +76 to -120 in
# 0.1 s), subtracting the unlagged share left 4-6 with the driver's hands off and let go of the wheel mid-turn.
# Refitted on 665k hands-off frames of 7 drives as a first-order lag of 0.04 s and 1 per 15.5: frames above 3 during
# such swings fell from 18% to 2.6%. Replayed on the same drives, the false let-gos right after the EPS pushed 90 or
# more fell from 56 to 17; every takeover that lasted 0.5 s or more was still caught (35 of 35, at most 40 ms later),
# and so was every let-go above 110 km/h, including all of the 125 km/h nudges.
EPS_TORQUE_PER_DRIVER_TORQUE = 15.5
EPS_TORQUE_LAG = 0.04 # s
STEER_DRIVER_ALLOWANCE = 3
# While steering, the EPS often pushes 50-175, and the reading follows less of that than EPS_TORQUE_PER_DRIVER_TORQUE
# assumes: what is left over looks like the driver turning with the EPS (3-5), and the EPS's own DRIVER_OVERRIDE flag
# comes on with it. openpilot let go, the wheel sprang back 3-94 deg and the car drifted (route 0000000a, 12:30-12:31
# in bends, the driver's hand resting on the wheel on the driver camera). So while the wheel follows openpilot's
# angle within OVERRIDE_TRACKING_ERROR, torque in the EPS's own direction counts only as far as the raw reading shows
# it, and the flag needs the driver's torque against the EPS too. A driver who steers moves the wheel off openpilot's
# angle, and from there the previous rule applies: of 218 let-gos on 8 drives, all 101 that came with the wheel
# already 3 deg or more off (the driver holding it straight against a 12 deg command at route 00000010 23:18:35
# among them) are unchanged. Of the 38 after which the wheel sprang back, 37 no longer happen at that moment.
# A model of the EPS torque needed hands-off (from speed, lateral acceleration, angle and rate) did not tell them
# apart: at every kind of let-go the EPS was 60-70 above it.
OVERRIDE_TRACKING_ERROR = 3. # deg
OVERRIDE_OPPOSING_TORQUE = 1.
# Largest gap (deg) between openpilot's angle and the wheel's at which it takes the wheel back. It stops the case it was
# made for: at walking pace the driver let go with the wheel at +308 deg and the model at +24, and the EPS swung it to
# -203 deg. 10 deg was too tight: right after the driver lets go in a bend the gap is 11-27 deg, and on route 26b
# openpilot then did not steer for 0.8-1.7 s mid-turn (5 times), drifting wide. The command still starts from the
# wheel's angle and is rate limited, and the LCC ramp builds up the torque.
TAKE_BACK_MAX_ANGLE_ERROR = 45.
# The stock ramp depth follows lateral acceleration, which stays small in sharp turns at low speed: there the wheel
# fell > 5 deg behind with the EPS near its torque ceiling (25d, 260). While the wheel is RAMP_BOOST_LAG behind the
# command below RAMP_BOOST_MAX_SPEED, the ramp goes one step deeper per frame (up to the deepest stock value, 46 steps,
# about +/-70 torque), and back one step per frame once within RAMP_BOOST_CAUGHT_UP. Replayed on 3 drives: active
# 23-31% of the time below 30 km/h, 3-7% at 30-80 km/h. Not at speed, where such a lag was the driver's own nudge.
RAMP_BOOST_LAG = 3. # deg
RAMP_BOOST_CAUGHT_UP = 1.5 # deg
RAMP_BOOST_MAX_SPEED = 60. # km/h
# Past about 150 of STEER_TORQUE_EPS the EPS sets its own DRIVER_OVERRIDE flag with the driver's hands off, and
# openpilot lets go like the stock LCC does: engaged frames with the flag set were 0-1% below 130, 9% at 130-160
# and 50% above 160 (a test build ramping to 56 steps; 28% above 160 at 52 steps). In a tightening turn at 25 km/h
# the boost drove it to -167..-218 three times, the EPS let go each time and the wheel sprang back 25-30 deg.
# So the boost goes no deeper from RAMP_BOOST_EPS_TORQUE_HOLD and backs off from RAMP_BOOST_EPS_TORQUE_BACK. With
# it, the EPS peaked at 136 through a 72 deg turn at 33-47 km/h and never flagged an override above 100.
RAMP_BOOST_EPS_TORQUE_HOLD = 100
RAMP_BOOST_EPS_TORQUE_BACK = 120
# Longitudinal (alpha): ADAS_LKA.ACC_ACCEL_REQ, 0.05 m/s^2 per bit, raw 100 = 0. Must match opendbc/safety/modes/leapmotor.h.
# Stock ACC never asked for less than -2.7 m/s^2 in about 5 h of engaged driving; the car follows the request
# (-2.6 asked, -2.69 measured) and blends regen with light friction braking itself.
ACCEL_MIN = -3.5 # m/s^2
ACCEL_MAX = 2.0 # m/s^2
# When the camera asks for this much braking or more, openpilot never asks for less: the camera's emergency braking
# path is not yet known and may use this field. Stock ACC went below it on 0.02% of engaged frames.
STOCK_BRAKE_PASSTHROUGH = -2.0 # m/s^2
class LeapmotorSafetyFlags(IntFlag):
LONG_CONTROL = 1
@dataclass
class LeapmotorCarDocs(CarDocs):
package: str = "Adaptive Cruise Control (ACC) & Lane Centering Control (LCC)"
car_parts: CarParts = field(default_factory=CarParts.common([CarHarness.custom]))
@dataclass
class LeapmotorPlatformConfig(PlatformConfig):
dbc_dict: DbcDict = field(default_factory=lambda: {
Bus.pt: 'leapmotor_b10',
})
class CAR(Platforms):
# wheelbase: Italian brochure, B10 Life with the 56.2 kWh Pro battery.
# steerRatio 15.2 is measured from slow figure-eights (steering angle vs. yaw rate / speed).
LEAPMOTOR_B10 = LeapmotorPlatformConfig(
[LeapmotorCarDocs("Leapmotor B10 2025")],
CarSpecs(mass=1780, wheelbase=2.735, steerRatio=15.2),
)
# Part number (F187), physical request = reply minus 8: EPS 0x735, brake 0x736, front camera 0x756, all confirmed by a
# read-only UDS probe on the car. No tester present first: the camera did not answer openpilot's query when it led with
# one, but answers F187 directly. At ignition, before READY, only the brake answers (the EPS stays silent until READY,
# the camera is slow), so the EPS and camera are non-essential; their part numbers are still checked when present.
PART_NUMBER_REQUEST = bytes([0x22, 0xF1, 0x87])
PART_NUMBER_RESPONSE = bytes([0x62, 0xF1, 0x87])
FW_QUERY_CONFIG = FwQueryConfig(
requests=[
Request(
[PART_NUMBER_REQUEST],
[PART_NUMBER_RESPONSE],
whitelist_ecus=[Ecu.eps, Ecu.abs, Ecu.fwdCamera],
bus=0,
),
],
non_essential_ecus={
Ecu.eps: [CAR.LEAPMOTOR_B10],
Ecu.fwdCamera: [CAR.LEAPMOTOR_B10],
},
# part numbers such as 3401100-AG01, zero-padded to 19 bytes
fw_version_regex=br"\d{7}-[A-Z]{2}\d{2}\x00{7}",
)
DBC = CAR.create_dbc_map()
@@ -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'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-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-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'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'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', 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 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): class CarInterface(CarInterfaceBase):
CarState = CarState CarState = CarState
CarController = CarController CarController = CarController
@@ -18,14 +32,16 @@ class CarInterface(CarInterfaceBase):
ret.radarUnavailable = True ret.radarUnavailable = True
ret.deprecated.enableBsm = 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.steerActuatorDelay = 0.1
ret.steerLimitTimer = 0.8 ret.steerLimitTimer = 0.8
CarInterfaceBase.configure_torque_tune(candidate, ret.lateralTuning) 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.minSteerSpeed = LKAS_LIMITS.DISABLE_SPEED * CV.KPH_TO_MS
ret.centerToFront = ret.wheelbase * 0.41 ret.centerToFront = ret.wheelbase * 0.41
+1 -1
View File
@@ -1,7 +1,7 @@
from opendbc.car import structs from opendbc.car import structs
from opendbc.car.mazda.values import CAR, MazdaFlags 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): 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 opendbc.car.mazda.tests.test_stock_startup import complete_frames, exercise_startup
from openpilot.starpilot.car.mazda import dashboard 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)) @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 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): def test_ordinary_engagement_brake_actual_family_callers(identity, monkeypatch):
_exercise_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): def test_unassigned_cancel_retains_lateral_main_off_revokes_actual_callers(identity, monkeypatch):
_exercise_actual_family_callers(identity, monkeypatch, scenario='cancel', cancel_action=0) _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): def test_longitudinal_cancel_assignment_keeps_lateral_actual_callers(identity, monkeypatch):
_exercise_actual_family_callers(identity, monkeypatch, scenario='long_cancel', cancel_action=4) _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 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): 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) _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): 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) _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): 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) _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)) @pytest.mark.parametrize('cancel_action', (3, 9))
def test_mapped_cancel_pause_and_toggle_actual_callers(identity, cancel_action, monkeypatch, armed_intent_decoder): 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, _exercise_actual_family_callers(identity, monkeypatch, scenario='mapped_cancel', cancel_action=cancel_action,
armed_intent=armed_intent_decoder) 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)) @pytest.mark.parametrize('lateral_only', (False, True))
def test_eps_recovery_actual_callers(identity, lateral_only, monkeypatch, armed_intent_decoder): 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, _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)) 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): 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) _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): 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) _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): 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, _exercise_actual_family_callers(identity, monkeypatch, scenario='startup_stopped', cancel_action=9,
armed_intent=armed_intent_decoder) 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): def test_main_on_startup_disabled_aol_actual_card_controls_native(identity, monkeypatch):
from openpilot.cereal import messaging from openpilot.cereal import messaging
from openpilot.selfdrive.car import card as card_module 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) 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')) @pytest.mark.parametrize('warning', ('calibrationInvalid', 'lowMemory', 'processNotRunning', 'radarTempUnavailable'))
def test_ordinary_warning_retains_intent_actual_callers(identity, warning, monkeypatch, armed_intent_decoder): 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) _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')) @pytest.mark.parametrize('scenario', ('mapped_cancel', 'temporary'))
def test_unbelted_lateral_pause_recovery_actual_callers(identity, scenario, monkeypatch, armed_intent_decoder): 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, _exercise_actual_family_callers(identity, monkeypatch, scenario=scenario, cancel_action=3,
armed_intent=armed_intent_decoder, unbelted=True) 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')) @pytest.mark.parametrize('warning', ('calibrationInvalid', 'lowMemory', 'processNotRunning', 'radarTempUnavailable'))
def test_active_ordinary_warning_retains_intent_actual_callers(identity, warning, monkeypatch, armed_intent_decoder): 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) _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): class TestStockCancelEvents(unittest.TestCase):
def test_actual_parser_cancel_is_scoped_to_marked_profile(self): 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): for experience in (0, 32):
with self.subTest(identity=identity, experience=experience): with self.subTest(identity=identity, experience=experience):
cp = CarInterface.get_params(identity, gen_empty_fingerprint(), [], False, False, False) 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 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): 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) 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): def test_unchanged_dashcam_configuration_denies_independent_owner(identity):
from opendbc.car.mazda.stock_aol import qualified from opendbc.car.mazda.stock_aol import qualified
from openpilot.starpilot.car.mazda.aol import policy_for 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_REQUEST = 0x6BB
AVH_STATUS = 0x32B AVH_STATUS = 0x32B
@@ -10,7 +10,7 @@ def checksum(address, data):
def avh_request(template, step): 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") raise ValueError("Invalid AVH template or counter step")
data = bytearray(template) data = bytearray(template)
data[1] = (data[1] & 0xF0) | ((data[1] + step) & 0xF) data[1] = (data[1] & 0xF0) | ((data[1] + step) & 0xF)
@@ -27,6 +27,8 @@ class AvhStartup:
self.last_time = None self.last_time = None
self.stable_since = None self.stable_since = None
self.frames = {} self.frames = {}
self.avh_req_gap = None
self.avh_req_same_payload = False
self.done = False self.done = False
self.followup = None self.followup = None
@@ -85,6 +87,9 @@ class AvhStartup:
# checks their full counter stream; require consecutive head-unit frames here. # checks their full counter stream; require consecutive head-unit frames here.
sequential = bool(previous and (address not in (AVH_REQUEST, AVH_STATUS) or sequential = bool(previous and (address not in (AVH_REQUEST, AVH_STATUS) or
(data[1] & 15) == ((previous[1][1] + 1) & 15))) (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) self.frames[address] = (timestamp, data, sequential)
fresh = all(a in self.frames and self.frames[a][2] and fresh = all(a in self.frames and self.frames[a][2] and
@@ -104,31 +109,37 @@ class AvhStartup:
if self.stable_since is None: if self.stable_since is None:
self.stable_since = now self.stable_since = now
if self.followup is not None: 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: if now - sent > 0.075 or self.frames[AVH_REQUEST][0] != timestamp:
self.done = True self.done = True
elif now - sent >= 0.05: elif now - sent >= 0.05:
self.done = True next_step = step + 1
return [avh_request(template, 2)] 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 [] return []
if (now - self.started < 10 or now - self.stable_since < 3 or if (now - self.started < 10 or now - self.stable_since < 3 or
(self.configured_since is not None and now - self.configured_since < 10)): (self.configured_since is not None and now - self.configured_since < 10)):
return [] return []
timestamp, template, _ = self.frames[AVH_REQUEST] 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 [] return []
self.followup = (now, timestamp, template) self.followup = (now, timestamp, template, 1)
return [avh_request(template, 1)] return [avh_request(template, 1)]
def eligible(cp): def eligible(cp):
from opendbc.car.subaru.startup import supported from opendbc.car.subaru.stock_aol import qualified
return bool(supported(cp) and cp.carFingerprint == 'SUBARU_LEGACY_2025') 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): def selected(cp):
from opendbc.car.subaru.values import SubaruFlags 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): def prepare(cp, enabled):
@@ -143,6 +154,7 @@ class AvhSources:
def __init__(self): def __init__(self):
self.frames = {} self.frames = {}
self.sequential = {} self.sequential = {}
self.source_ns = {}
self.blocked = False self.blocked = False
def observe(self, packets, *, boot_ns, mono_ns): def observe(self, packets, *, boot_ns, mono_ns):
@@ -163,10 +175,12 @@ class AvhSources:
if data != previous[1]: if data != previous[1]:
self.blocked = True self.blocked = True
continue 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 self.blocked = True
continue continue
self.sequential[address] = previous is not None and counter == ((previous[1][1] + 1) & 15) 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 self.frames[address] = source / 1e9, data
def fresh(self, now): 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 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.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.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 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 # 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 from opendbc.car.subaru.avh import selected as avh_selected, AvhStartup
self.avh_startup = AvhStartup() if avh_selected(CP) else None self.avh_startup = AvhStartup() if avh_selected(CP) else None
self.apply_torque_last = 0 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.apply_angle_last = 0.
self.angle_was_active = False self.angle_was_active = False
self.angle_override_frames = 0 self.angle_override_frames = 0
self.eps_stall_count = 0
self.ascent_angle_initialized = False self.ascent_angle_initialized = False
self.ascent_es_distance_counter_last = None self.ascent_es_distance_counter_last = None
self.ascent_lkas_alert_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_driver_override = False
self.angle_handoff_active = False self.angle_handoff_active = False
self.VM = VehicleModel(CP) if CP.carFingerprint in GEN2_ANGLE_PORTS else None 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 self.angle_handoff_active = False
return False return False
high, low = (150, 100) if self.CP.carFingerprint in (CAR.SUBARU_CROSSTREK_2025, CAR.SUBARU_IMPREZA_2025) else (200, 150) 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 self.angle_driver_override:
if torque < low: if torque < low:
self.angle_driver_override = False self.angle_driver_override = False
@@ -85,12 +90,73 @@ class CarController(CarControllerBase):
return False return False
return True 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): 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 return None
dat = CS.es_lkas_alert_dat 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)) frogger_hud = self.CP.carFingerprint != CAR.SUBARU_ASCENT_2023
msg = subarucan.create_ascent_lkas_alert(dat, lateral_active, CC.hudControl.visualAlert) 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: if msg is None or (dat[1] & 0xf) == self.ascent_lkas_alert_counter_last:
return None return None
self.ascent_lkas_alert_counter_last = dat[1] & 0xf 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.frame % self.p.STEER_STEP) == 0:
if self.CP.carFingerprint in GEN2_ANGLE_PORTS: if self.CP.carFingerprint in GEN2_ANGLE_PORTS:
independent_lateral = subaru_aol_qualified(self.CP, marked_only=True) independent_lateral = subaru_aol_qualified(self.CP, marked_only=True)
# Preserve large-turn admission; active Jacobw ports retain their native angle envelope. if self.CP.carFingerprint == CAR.SUBARU_LEGACY_2025:
angle_continuation = (self.angle_was_active and self.angle_filter is not None and if CC.latActive and not CC.enabled:
abs(CS.out.steeringAngleDeg) < JACOBW_MAX_ANGLE) # Hold max AOL angle cleanly inside the 210 deg cutout ceiling instead of steering out of bounds.
aol_motion_ok = CC.enabled or (CS.out.vEgoRaw > 0.44704 and angle_target = float(np.clip(angle_target, -200., 200.))
(abs(CS.out.steeringAngleDeg) < 120. or angle_continuation)) 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 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 (independent_lateral or (CC.enabled and CS.out.cruiseState.enabled and not CS.out.brakePressed)) and
CS.out.gearShifter == structs.CarState.GearShifter.drive and gear_ok and
not legacy_lateral_off and
not CS.out.standstill and not CS.out.steerFaultTemporary and not CS.out.steerFaultPermanent) not CS.out.standstill and not CS.out.steerFaultTemporary and not CS.out.steerFaultPermanent)
angle_active = self.angle_active(CS, angle_available) 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: if self.CP.carFingerprint == CAR.SUBARU_ASCENT_2023 and not self.ascent_angle_initialized:
self.apply_angle_last = CS.out.steeringAngleDeg self.apply_angle_last = CS.out.steeringAngleDeg
self.ascent_angle_initialized = True self.ascent_angle_initialized = True
angle_active = False 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, apply_angle = apply_std_steer_angle_limits(actuators.steeringAngleDeg, self.apply_angle_last,
CS.out.vEgoRaw, CS.out.steeringAngleDeg, angle_active, CS.out.vEgoRaw, CS.out.steeringAngleDeg, angle_active,
self.p.FIXED_ANGLE_LIMITS) self.p.FIXED_ANGLE_LIMITS)
@@ -214,11 +307,20 @@ class CarController(CarControllerBase):
can_sends.extend(send_sng(self, CC, CS, now_nanos)) can_sends.extend(send_sng(self, CC, CS, now_nanos))
# *** alerts and pcm cancel *** # *** 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) lkas_alert_msg = self._ascent_lkas_alert(CC, CS)
if lkas_alert_msg is not None: if lkas_alert_msg is not None:
can_sends.append(lkas_alert_msg) can_sends.append(lkas_alert_msg)
if self.CP.flags & SubaruFlags.PREGLOBAL: 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 # 1 = main, 2 = set shallow, 3 = set deep, 4 = resume shallow, 5 = resume deep
# disengage ACC when OP is disengaged # disengage ACC when OP is disengaged
if pcm_cancel_cmd: 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, 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)) 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 if frogger_hud:
lkas_state_msg = CS.es_lkas_state_msg in_drive = CS.out.gearShifter in (structs.CarState.GearShifter.drive, structs.CarState.GearShifter.manumatic)
if self.CP.carFingerprint in GEN2_ANGLE_PORTS or subaru_aol_qualified(self.CP, marked_only=True): cruise_available = CS.out.cruiseState.available
if self.CP.carFingerprint not in GEN2_ANGLE_PORTS: lateral_off = self._legacy_2025_effective_lateral_off(CS, CC)
lkas_active = CC.latActive aol_enabled = bool(getattr(CS, "aol_enabled", True))
lkas_state_msg = dict(lkas_state_msg, LKAS_ACTIVE=int(lkas_active)) if self.CP.carFingerprint in FROGGER_ANGLE_SIBLINGS:
can_sends.append(subarucan.create_es_lkas_state(self.packer, self.frame // 10, lkas_state_msg, lkas_active, hud_control.visualAlert, aol_enabled = aol_enabled and subaru_aol_qualified(self.CP, marked_only=True)
hud_control.leftLaneVisible, hud_control.rightLaneVisible, wheel_ready = bool(cruise_available and aol_enabled)
hud_control.leftLaneDepart, hud_control.rightLaneDepart)) 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: 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.CP.openpilotLongitudinalControl:
if self.frame % 5 == 0: if self.frame % 5 == 0:
@@ -266,7 +404,7 @@ class CarController(CarControllerBase):
self.CP.openpilotLongitudinalControl, cruise_brake > 0, cruise_throttle)) self.CP.openpilotLongitudinalControl, cruise_brake > 0, cruise_throttle))
else: else:
cancel_frame_ready = True 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"] stock_counter = CS.es_distance_msg["COUNTER"]
cancel_frame_ready = stock_counter != self.ascent_es_distance_counter_last cancel_frame_ready = stock_counter != self.ascent_es_distance_counter_last
self.ascent_es_distance_counter_last = stock_counter self.ascent_es_distance_counter_last = stock_counter
+124 -6
View File
@@ -3,9 +3,18 @@ from opendbc.can import CANDefine, CANParser
from opendbc.car import Bus, structs, create_button_events from opendbc.car import Bus, structs, create_button_events
from opendbc.car.common.conversions import Conversions as CV from opendbc.car.common.conversions import Conversions as CV
from opendbc.car.interfaces import CarStateBase from opendbc.car.interfaces import CarStateBase
from opendbc.car.subaru.stock_aol import qualified as stock_aol_qualified
from opendbc.car.subaru.values import CAR, DBC, CanBus, SubaruFlags from opendbc.car.subaru.values import CAR, DBC, CanBus, SubaruFlags
from opendbc.car import CanSignalRateCalculator 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})
# Drive range with ratio zero, with either state of the manual-mode bit.
PADDLE_EXIT_GEARS = (1, 129)
PADDLE_EXIT_WINDOW_NS = 750_000_000
PADDLE_EXIT_PAUSE_NS = 150_000_000
class CarState(CarStateBase): class CarState(CarStateBase):
def __init__(self, CP): def __init__(self, CP):
@@ -16,6 +25,9 @@ class CarState(CarStateBase):
self.avh_sources = AvhSources() if avh_selected(CP) else None self.avh_sources = AvhSources() if avh_selected(CP) else None
can_define = CANDefine(DBC[CP.carFingerprint][Bus.pt]) can_define = CANDefine(DBC[CP.carFingerprint][Bus.pt])
self.shifter_values = can_define.dv["Transmission"]["Gear"] self.shifter_values = can_define.dv["Transmission"]["Gear"]
self.paddle_ratio_ns = 0
self.paddle_exit_pause_ns = 0
self.paddle_exit_in_drive = False
self.sng_sources = {} self.sng_sources = {}
self.sng_source_valid = {} self.sng_source_valid = {}
@@ -33,6 +45,62 @@ class CarState(CarStateBase):
from opendbc.car.subaru.high_angle_guard import HighAngleGuard, selected from opendbc.car.subaru.high_angle_guard import HighAngleGuard, selected
self.high_angle_guard = HighAngleGuard() if selected(CP) else None self.high_angle_guard = HighAngleGuard() if selected(CP) else None
self.high_angle_cut = False 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 _paddle_exit_paused(self, parser: CANParser) -> bool:
gear_ns = parser.ts_nanos["Transmission"]["Gear"]
now_ns = parser.last_nonempty_nanos
if parser.bus_timeout or not 0 < gear_ns <= now_ns:
self.paddle_ratio_ns = self.paddle_exit_pause_ns = 0
self.paddle_exit_in_drive = False
return False
for gear in parser.vl_all["Transmission"]["Gear"]:
position = self.shifter_values.get(int(gear))
if position in ("1", "2", "3", "4", "5", "6"):
self.paddle_ratio_ns = gear_ns
self.paddle_exit_in_drive = False
self.paddle_exit_pause_ns = 0
elif position == "D":
self.paddle_exit_in_drive = True
self.paddle_exit_pause_ns = 0
elif gear in PADDLE_EXIT_GEARS and self.paddle_exit_in_drive:
if not self.paddle_exit_pause_ns and 0 < self.paddle_ratio_ns <= gear_ns <= self.paddle_ratio_ns + PADDLE_EXIT_WINDOW_NS:
self.paddle_exit_pause_ns = gear_ns
self.paddle_ratio_ns = 0
else:
self.paddle_ratio_ns = self.paddle_exit_pause_ns = 0
self.paddle_exit_in_drive = False
# Report the transition as a paddle pause so both Card and SelfdriveD
# withdraw steering until the transmission reports Drive again.
return bool(0 < self.paddle_exit_pause_ns <= now_ns < self.paddle_exit_pause_ns + PADDLE_EXIT_PAUSE_NS and
stock_aol_qualified(self.CP, marked_only=True))
def update(self, can_parsers) -> structs.CarState: def update(self, can_parsers) -> structs.CarState:
cp = can_parsers[Bus.pt] cp = can_parsers[Bus.pt]
@@ -78,7 +146,17 @@ class CarState(CarStateBase):
cp_transmission = cp_alt if self.CP.flags & SubaruFlags.HYBRID else cp cp_transmission = cp_alt if self.CP.flags & SubaruFlags.HYBRID else cp
can_gear = int(cp_transmission.vl["Transmission"]["Gear"]) 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._paddle_exit_paused(cp_transmission) or
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): if not (self.CP.flags & SubaruFlags.LKAS_ANGLE):
ret.steeringAngleDeg = cp_angle.vl["Steering_Torque"]["Steering_Angle"] ret.steeringAngleDeg = cp_angle.vl["Steering_Torque"]["Steering_Angle"]
@@ -102,11 +180,14 @@ class CarState(CarStateBase):
cp_cruise = cp_alt if self.CP.flags & SubaruFlags.GLOBAL_GEN2 else cp 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 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, 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): 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.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): 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 # 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 # during user gas override and at standstill. ES_Status is missing on hybrid, so we use ES_Brake instead
@@ -115,10 +196,10 @@ class CarState(CarStateBase):
# brake while engaged at a stop. ES_Status and ES_DashStatus->Signal7 correctly fell, but is either missing or # 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. # 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.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: else:
ret.cruiseState.enabled = cp_cruise.vl["CruiseControl"]["Cruise_Activated"] != 0 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 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 \ if (self.CP.flags & SubaruFlags.PREGLOBAL and cp.vl["Dash_State2"]["UNITS"] == 1) or \
@@ -148,6 +229,34 @@ class CarState(CarStateBase):
self.es_lkas_state_msg = copy.copy(cp_cam.vl["ES_LKAS_State"]) 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"]) 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 # TODO: Hybrid cars don't have ES_Distance, need a replacement
if not (self.CP.flags & SubaruFlags.HYBRID): if not (self.CP.flags & SubaruFlags.HYBRID):
# 8 is known AEB, there are a few other values related to AEB we ignore # 8 is known AEB, there are a few other values related to AEB we ignore
@@ -190,8 +299,17 @@ class CarState(CarStateBase):
self.es_dashstatus_msg = copy.copy(cp_cam.vl["ES_DashStatus"]) self.es_dashstatus_msg = copy.copy(cp_cam.vl["ES_DashStatus"])
if self.CP.flags & SubaruFlags.ASCENT_LKAS_ALERT: if self.CP.flags & SubaruFlags.ASCENT_LKAS_ALERT:
alert = cp_cam.vl["ES_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))) + self.es_lkas_alert_dat = (
int(alert["Payload"]).to_bytes(6, "little")) 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: if self.CP.flags & SubaruFlags.SEND_INFOTAINMENT:
self.es_infotainment_msg = copy.copy(cp_cam.vl["ES_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.interfaces import CarInterfaceBase
from opendbc.car.subaru.carcontroller import CarController from opendbc.car.subaru.carcontroller import CarController
from opendbc.car.subaru.carstate import CarState 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, 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)) 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): class CarInterface(CarInterfaceBase):
CarState = CarState CarState = CarState
CarController = CarController CarController = CarController
DRIVABLE_GEARS = (structs.CarState.GearShifter.manumatic,)
def update(self, can_packets): def update(self, can_packets):
source = self.CS.startup_sources source = self.CS.startup_sources
@@ -58,7 +59,7 @@ class CarInterface(CarInterfaceBase):
if not (ret.flags & SubaruFlags.PREGLOBAL) and 0x323 in fingerprint[2]: if not (ret.flags & SubaruFlags.PREGLOBAL) and 0x323 in fingerprint[2]:
ret.flags |= SubaruFlags.SEND_INFOTAINMENT.value 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 ret.flags |= SubaruFlags.ASCENT_LKAS_ALERT.value
if ret.flags & SubaruFlags.PREGLOBAL: if ret.flags & SubaruFlags.PREGLOBAL:
@@ -75,6 +76,8 @@ class CarInterface(CarInterfaceBase):
ret.safetyConfigs[0].safetyParam |= SubaruSafetyFlags.LKAS_ANGLE.value ret.safetyConfigs[0].safetyParam |= SubaruSafetyFlags.LKAS_ANGLE.value
if candidate in (CAR.SUBARU_LEGACY_2025, CAR.SUBARU_ASCENT_2023, CAR.SUBARU_OUTBACK_2023): if candidate in (CAR.SUBARU_LEGACY_2025, CAR.SUBARU_ASCENT_2023, CAR.SUBARU_OUTBACK_2023):
ret.safetyConfigs[0].safetyParam |= SubaruSafetyFlags.FIXED_ANGLE_LIMITS.value 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: if candidate == CAR.SUBARU_OUTBACK_2023:
ret.safetyConfigs[0].safetyParam |= SubaruSafetyFlags.D_PLATFORM.value ret.safetyConfigs[0].safetyParam |= SubaruSafetyFlags.D_PLATFORM.value
if candidate == CAR.SUBARU_ASCENT_2023: 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.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]] 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.steerActuatorDelay = 0.4 # end-to-end angle controller
ret.lateralTuning.init('pid') ret.lateralTuning.init('pid')
ret.lateralTuning.pid.kf = 0.00005 ret.lateralTuning.pid.kf = 0.00005
@@ -131,7 +135,8 @@ class CarInterface(CarInterfaceBase):
ret.steerActuatorDelay = 0.15 ret.steerActuatorDelay = 0.15
elif candidate == CAR.SUBARU_OUTBACK_PREGLOBAL: elif candidate == CAR.SUBARU_OUTBACK_PREGLOBAL:
pass ret.dashcamOnly = False
ret.safetyConfigs[0].safetyParam = SubaruSafetyFlags.PREGLOBAL_OUTBACK_STOCK_ACC.value
else: else:
raise ValueError(f"unknown car: {candidate}") raise ValueError(f"unknown car: {candidate}")
+4 -2
View File
@@ -2,10 +2,10 @@
from opendbc.car import structs from opendbc.car import structs
from opendbc.car.subaru.stock_aol import IMPREZA_MAIN_AOL 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 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): def eligible(cp):
@@ -16,6 +16,8 @@ def eligible(cp):
return False return False
word &= ~IMPREZA_MAIN_AOL word &= ~IMPREZA_MAIN_AOL
words = (0, 8, 512, 520) if cp.carFingerprint == CAR.SUBARU_IMPREZA_2020 else (0, 8) 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( return bool(
cp.brand == 'subaru' cp.brand == 'subaru'
and cp.carFingerprint in SUPPORTED and cp.carFingerprint in SUPPORTED
@@ -26,5 +26,5 @@ def capture(interface, packets):
and data[0] == ((address & 255) + (address >> 8) + sum(data[1:])) & 255 and data[0] == ((address & 255) + (address >> 8) + sum(data[1:])) & 255
and (previous is None or source_ns > previous[0] and data[1] & 15 != previous[1][1] & 15) and (previous is None or source_ns > previous[0] and data[1] & 15 != previous[1][1] & 15)
): ):
state.sng_source_valid[address] = previous is not None and data[1] & 15 == ((previous[1][1] + 1) & 15) state.sng_source_valid[address] = previous is not None and data[1] & 15 != previous[1][1] & 15
state.sng_sources[address] = (source_ns, bytes(data)) state.sng_sources[address] = (source_ns, bytes(data))

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