Compare commits

...

430 Commits

Author SHA1 Message Date
nayan 9490bd02e4 feat(mici): parametric hearts, remove blush, and add gyro/yaw/pitch centrifugal turn squish 2026-11-27 17:39:04 -05:00
nayan 36a7b171aa feat(mici): add ambient music groove mode and 12-band OLED visualizer 2026-11-27 17:23:10 -05:00
nayan 9e897d67a4 fix(mici): add procedural robotic chirp fallback, reactive sounds, and livelier bubbly driving face 2026-11-27 16:51:12 -05:00
nayan 65ac41ddfd feat(sunnylink): add MiciRoboticUI toggle under Visuals 2026-11-27 14:55:08 -05:00
nayan 2dc82f346c feat(mici): add optional robotic companion onroad UI and voice pack 2026-11-27 14:36:37 -05:00
nayan 7f1a19389b esc long tuning 2026-11-27 08:39:19 -05:00
nayan d35ddcc83b pidd 2026-11-27 08:36:09 -05:00
nayan 2f9defc858 Merge remote-tracking branch 'origin/hkg-adas-ecu-drv-interceptor-sim-new' into nayan-interceptor
# Conflicts:
#	opendbc_repo
2026-11-26 23:28:32 -05:00
nayan 0a067e0ebb agnos bt 2026-11-26 16:45:19 -05:00
nayan c1a99f4425 fix modeld curvature calculation and CCNC HUD encoding 2026-11-26 16:44:39 -05:00
nayan 3d35957944 bump opendbc: reduce Hyundai radar tracks CPU lag 2026-11-26 16:44:39 -05:00
Jason Wen b91d9c8d2d bump opendbc 2026-11-26 01:06:46 -05:00
Jason Wen 3357930e6a bump opendbc 2026-11-26 00:45:43 -05:00
Jason Wen 76ed9dde5c minor event tidy 2026-11-26 00:41:49 -05:00
Jason Wen 5c1ce53716 Merge master 2026-11-26 00:41:31 -05:00
Jason Wen 54eb444dc2 bump opendbc 2026-11-25 00:29:44 -05:00
Jason Wen c2cc52d1ee bump opendbc 2026-11-24 22:31:27 -05:00
Jason Wen 90be6d8b11 bump opendbc 2026-11-24 19:42:52 -05:00
Jason Wen 08b2b1eb27 minor event cleanup 2026-11-24 19:42:52 -05:00
Jason Wen 9f0f4c6fb6 bump opendbc 2026-11-24 19:40:15 -05:00
Jason Wen d1dadbae6a bump opendbc 2026-11-24 19:24:03 -05:00
Jason Wen f279a3da40 minor cleanup 2026-11-24 19:24:03 -05:00
Jason Wen fabffc398f Merge master
# Conflicts:
#	opendbc_repo
2026-11-24 19:23:34 -05:00
nayan 98b98caf14 test curvature from model 2026-11-24 13:46:49 -05:00
Jason Wen 829d735f43 bump opendbc 2026-11-24 01:38:39 -05:00
nayan 51f6a95db7 bump opendbc 2026-11-23 17:37:19 -05:00
nayan 05674fa3a7 hyundai radar tracks 2026-11-23 17:33:51 -05:00
nayan 530e5ea5f6 models v26 2026-11-23 17:33:47 -05:00
nayan a1734b33b7 emu more 2026-11-23 17:33:47 -05:00
Jason Wen 781d697797 bump opendbc 2026-11-21 23:10:07 -05:00
Jason Wen 3d3fe06e04 Merge hkg-angle-steering-2025
# Conflicts:
#	opendbc_repo
2026-11-21 20:14:06 -05:00
Jason Wen 4075ae01e1 Merge master into hkg-angle-steering-2025
# Conflicts:
#	opendbc_repo
2026-11-21 20:14:05 -05:00
Jason Wen 80e4cc6897 bump opendbc 2026-11-21 19:04:41 -05:00
Jason Wen 7c2a4c4a91 bump opendbc 2026-11-20 22:19:18 -05:00
Jason Wen b3868923af bump opendbc 2026-11-20 22:06:43 -05:00
Jason Wen 0e6828d232 bump opendbc 2026-11-13 18:04:50 -05:00
Jason Wen e0b10b5a3a bump opendbc 2026-11-13 16:56:10 -05:00
Jason Wen 75a4a520a6 bump opendbc 2026-11-13 12:18:22 -05:00
Jason Wen 60d66ea0b2 Merge hkg-angle-steering-2025 2026-11-13 12:09:02 -05:00
Jason Wen 63eae41608 Merge master into hkg-angle-steering-2025 2026-11-13 10:57:29 -05:00
Jason Wen 6fd6a99293 explicit 2026-11-12 16:06:02 -05:00
Jason Wen 7597ab6db9 bump 2026-11-12 15:32:00 -05:00
Jason Wen 31d92c8c4f opendbc: bump for interceptor nav step B 2026-11-11 23:53:24 -05:00
Jason Wen 9d326c3640 test 2026-11-11 21:03:47 -05:00
Jason Wen c1f5aed4a5 bump 2026-11-11 14:37:26 -05:00
Jason Wen 3b1a67c499 Merge branch 'master' into hkg-angle-steering-2025
# Conflicts:
#	opendbc_repo
2026-11-11 11:20:40 -05:00
Jason Wen 8e750db9a0 bump 2026-11-10 23:59:47 -05:00
Jason Wen 4025f74eb6 bump 2026-11-10 16:07:32 -05:00
Jason Wen b025e8cd97 bump 2026-11-10 15:14:34 -05:00
Jason Wen 42ed6e041e bump 2026-11-08 03:01:12 -05:00
Jason Wen c9df1bc873 bump opendbc: auto DCU LFA 2026-11-07 22:34:40 -05:00
Jason Wen f8b3a37040 bump opendbc: drop interceptor LKAS_ALT 2026-11-07 22:31:12 -05:00
Jason Wen 41c1b705fc diff 6 2026-11-07 21:30:41 -05:00
Jason Wen bec467c262 let it 2026-11-07 21:27:55 -05:00
Jason Wen f542ce7da7 diff 5 2026-11-07 20:20:41 -05:00
Jason Wen 50bff0231b diff 4 2026-11-07 19:52:10 -05:00
Jason Wen 03d9e57cf5 all send 2026-11-07 19:46:34 -05:00
Jason Wen ed7e43bbcd diff 3 2026-11-07 19:43:25 -05:00
Jason Wen 727b4c9865 diff 2 2026-11-07 19:24:04 -05:00
Jason Wen f19c167e78 diff 2026-11-07 18:41:26 -05:00
Jason Wen 41e00f5e15 bump opendbc for interceptor popup filter 2026-11-07 17:28:35 -05:00
Jason Wen a378041e1b more 2026-11-07 13:07:53 -05:00
Jason Wen 2a4106d255 try 2026-11-07 13:04:20 -05:00
Jason Wen 3badfd3b6b bump 2026-11-07 12:04:54 -05:00
Jason Wen c2580fdbba bump 2026-11-06 21:49:06 -05:00
Jason Wen 603085420a bump 2026-11-06 21:03:06 -05:00
Jason Wen a9f252db8d bump 2026-11-06 17:20:45 -05:00
Jason Wen 411787f836 bump opendbc 2026-11-06 16:43:52 -05:00
Jason Wen 5f3b21858e Merge branch 'master' into hkg-angle-steering-2025
# Conflicts:
#	opendbc_repo
2026-11-06 16:42:42 -05:00
Jason Wen 520762ff38 opendbc: bump 2026-11-05 08:06:44 -05:00
Jason Wen c01f0cd41d Merge branch 'hkg-angle-steering-2025' into hkg-adas-ecu-drv-interceptor-new
# Conflicts:
#	opendbc_repo
2026-11-05 06:40:21 -05:00
Jason Wen 5999ccede8 bump 2026-11-05 06:36:13 -05:00
Jason Wen 5610e9733c Merge branch 'master' into hkg-angle-steering-2025 2026-11-05 06:35:07 -05:00
Jason Wen a93347e453 bump opendbc 2026-11-04 16:18:58 -05:00
Jason Wen 000bd5a637 bump opendbc 2026-11-02 14:53:35 -05:00
Jason Wen 6d7181132b send hda icon 2026-11-01 23:25:50 -05:00
Jason Wen c789ac0dff bump opendbc 2026-10-31 13:24:03 -04:00
Jason Wen f19f9d9b1d bump opendbc 2026-10-31 09:19:57 -04:00
Jason Wen a9901dd0fa bump opendbc 2026-10-31 08:52:18 -04:00
Jason Wen 091a36f2eb bump opendbc 2026-10-30 22:58:41 -04:00
Jason Wen d415348e81 bump opendbc 2026-10-30 17:21:20 -04:00
Jason Wen 1da526ad4c bump opendbc 2026-10-30 02:54:58 -04:00
Jason Wen 2761461dea bump opendbc 2026-10-29 23:40:17 -04:00
Jason Wen 2099cf035f all angle cars have ccnc 2026-10-29 23:18:09 -04:00
Jason Wen b9b043395b bump opendbc 2026-10-29 23:13:14 -04:00
Jason Wen ccbb7a171a bump 2026-10-29 20:15:35 -04:00
Jason Wen 28e9de33a9 Merge branch 'hkg-angle-steering-2025' into hkg-adas-ecu-drv-interceptor-new
# Conflicts:
#	opendbc_repo
2026-10-29 15:23:15 -04:00
Jason Wen 6484214fdd hyundai: gate interceptor long on alpha toggle 2026-10-29 12:51:01 -04:00
Jason Wen c8bc5858cf hyundai: send and check interceptor version 2026-10-29 12:28:09 -04:00
Jason Wen 30653bb0ab Merge branch 'master' into hkg-angle-steering-2025
# Conflicts:
#	opendbc_repo
2026-10-29 11:53:16 -04:00
Jason Wen 4e371fb488 Merge remote-tracking branch 'sunnypilot/sunnypilot/master' into hkg-angle-steering-2025 2026-10-25 09:53:27 -04:00
DevTekVE d021f6ca41 Sync and disable process replay temporarily 2026-09-24 13:49:44 +02:00
DevTekVE bbc97bc92a Merge remote-tracking branch 'origin/master' into hkg-angle-steering-2025 2026-09-24 13:12:56 +02:00
Jason Wen c6aef256df Merge remote-tracking branch 'sunnypilot/sunnypilot/master' into hkg-angle-steering-2025
# Conflicts:
#	opendbc_repo
2026-09-07 20:51:40 -04:00
Jason Wen cfb38312db Merge remote-tracking branch 'sunnypilot/sunnypilot/master' into hkg-angle-steering-2025 2026-08-27 16:57:56 -04:00
Jason Wen 6fd4278e02 Merge remote-tracking branch 'sunnypilot/sunnypilot/master' into hkg-angle-steering-2025
# Conflicts:
#	opendbc_repo
2026-08-25 02:03:09 -04:00
DevTekVE 451cc3445a Bump opendbc 2026-08-23 16:35:28 +02:00
Jason Wen 1daa2d9081 Merge remote-tracking branch 'sunnypilot/sunnypilot/master' into hkg-angle-steering-2025
# Conflicts:
#	opendbc_repo
2026-08-17 10:29:01 -04:00
Jason Wen 7a9099818f Merge remote-tracking branch 'sunnypilot/sunnypilot/master' into hkg-angle-steering-2025 2026-08-14 17:57:37 -04:00
Jason Wen ef4fa48f33 Merge remote-tracking branch 'sunnypilot/sunnypilot/master' into hkg-angle-steering-2025
# Conflicts:
#	opendbc_repo
2026-08-14 17:18:06 -04:00
Jason Wen e426ced4c0 bump 2026-08-11 17:47:18 -04:00
Jason Wen 7681ba763b Merge remote-tracking branch 'sunnypilot/sunnypilot/master' into hkg-angle-steering-2025 2026-08-11 17:47:12 -04:00
Jason Wen b04d666a68 Merge remote-tracking branch 'sunnypilot/sunnypilot/master' into hkg-angle-steering-2025
# Conflicts:
#	opendbc_repo
2026-08-10 04:27:58 -04:00
Jason Wen fb026b86a3 Merge remote-tracking branch 'sunnypilot/sunnypilot/master' into hkg-angle-steering-2025 2026-08-06 21:58:57 -04:00
Jason Wen cff4c5e589 Merge remote-tracking branch 'sunnypilot/sunnypilot/master' into hkg-angle-steering-2025
# Conflicts:
#	opendbc_repo
2026-08-06 21:58:50 -04:00
DevTekVE 2ce3a8e4d4 test with regular lkas behavior 2026-08-03 21:17:57 +02:00
Jason Wen 82bcaa01a2 just for you devtekve 2026-07-27 18:41:44 -04:00
Jason Wen 54b380e7f7 bruh 2026-07-27 14:50:10 -04:00
Jason Wen 8ba3beda5f pls allow 2026-07-27 14:14:17 -04:00
Jason Wen b347de77d0 hard code it 2026-07-27 13:56:49 -04:00
Jason Wen b16524b5aa this is why 2026-07-27 13:15:55 -04:00
Jason Wen 8df99a700c no radar interface for now 2026-07-27 12:37:49 -04:00
Jason Wen ee464cc797 fix 2026-07-27 12:20:52 -04:00
Jason Wen ecec79f7be Merge branch 'hkg-angle-steering-2025' into hkg-adas-ecu-drv-interceptor
# Conflicts:
#	common/params_keys.h
#	opendbc_repo
#	openpilot/system/manager/manager.py
2026-07-27 11:44:10 -04:00
Jason Wen e0cca951f3 Merge remote-tracking branch 'sunnypilot/sunnypilot/master' into hkg-angle-steering-2025
# Conflicts:
#	opendbc_repo
2026-07-25 08:52:04 -04:00
Jason Wen 2439c048ed Merge remote-tracking branch 'sunnypilot/sunnypilot/master' into hkg-angle-steering-2025 2026-07-20 15:12:17 -04:00
Jason Wen 7b54d7d7a0 bump 2026-07-20 09:51:59 -04:00
Jason Wen b2bdb5787f Merge remote-tracking branch 'sunnypilot/sunnypilot/master' into hkg-angle-steering-2025
# Conflicts:
#	opendbc_repo
#	openpilot/tools/plotjuggler/layouts/analyzing-panda-block-angle-hkg.xml
#	openpilot/tools/plotjuggler/layouts/analyzing-torque-angle-hkg.xml
#	openpilot/tools/plotjuggler/layouts/hkg_angle_control.xml
#	openpilot/tools/plotjuggler/layouts/safety-limits-angle-kkg.xml
#	pyproject.toml
#	scripts/lint/lint.sh
2026-07-20 09:50:52 -04:00
Jason Wen 282f517b78 upstream changes 2026-06-09 00:18:40 -04:00
Jason Wen 1779144ff9 Merge remote-tracking branch 'sunnypilot/sunnypilot/master' into hkg-angle-steering-2025
# Conflicts:
#	opendbc_repo
#	scripts/lint/lint.sh
2026-06-08 23:53:43 -04:00
Jason Wen 54fb2750ba Merge remote-tracking branch 'sunnypilot/sunnypilot/master' into hkg-angle-steering-2025 2026-05-09 11:47:25 -04:00
DevTekVE 14431ab77f Merge branch 'master' into hkg-angle-steering-2025 2026-05-05 10:37:34 +02:00
Jason Wen 9d45db41b3 Merge remote-tracking branch 'sunnypilot/sunnypilot/master' into hkg-angle-steering-2025
# Conflicts:
#	opendbc_repo
#	system/version.py
2026-05-03 16:08:40 -04:00
Jason Wen b57c593d92 bump 2026-04-20 23:31:05 -04:00
nayan 0674c42866 good bot
fix state
2026-04-19 08:52:19 +02:00
nayan 1f7bcf246a Bringing sl change to validate 2026-04-18 09:25:12 +02:00
DevTekVE b0512dc523 Revert "safety: dynamically relax lateral jerk limits during accel conflicts"
This reverts commit b0644a37e3b5a7b941bd4347f4c7ef0f25f44fbc.
2026-04-12 11:25:31 +02:00
DevTekVE cd88fd3850 Bringing shane's improvements on the angle steering branch 2026-04-10 12:09:12 +02:00
DevTekVE ff78eaeba1 Merge branch 'master' into hkg-angle-steering-2025
# Conflicts:
#	opendbc_repo
2026-04-10 11:38:19 +02:00
DevTekVE 92c8aeeb92 lint 2026-04-10 11:34:29 +02:00
DevTekVE ecaa20e7be Add source map configuration to VSCode launch settings
- Enables better debugging by mapping sources to `${workspaceFolder}/opendbc/safety`.
2026-04-05 15:10:21 +02:00
DevTekVE 859c98c9d8 Refactor PlotJuggler layouts and optimize custom math equations
- Introduced new tabs for `Smoothing and Torque ceilings`.
- Updated custom math equations for cleaner logic and added new snippets for angle smoothing, ceiling brackets, and roll compensation.
2026-04-05 12:14:13 +02:00
DevTekVE 69cbe8c6ed Enhance torque reduction logic with speed and steering error adjustments
- Introduced speed-dependent and error-sensitive dynamic torque ceilings.
- Improved interpolation for smoother torque application.
2026-04-04 11:55:14 +02:00
DevTekVE 1aafe92fc0 Remove hyundai_canfd_ccnc.dbc and update dependencies
- Deleted `_hyundai_canfd_ccnc.dbc` and its import references across related files.
- Merged relevant signals and comments into `hyundai_canfd_og.dbc` for consolidated usage.
- Cleaned up obsolete imports in `hyundai_canfd.dbc`.
2026-04-04 08:46:09 +02:00
DevTekVE adb6b9fb12 Test changing priority for reading dbc files to in memory first 2026-04-04 08:29:57 +02:00
DevTekVE f67a9f4624 Revised steering angle smoothing matrix and logic cleanup
- Adjusted `SMOOTHING_ANGLE_VEGO_MATRIX` to refine torque smoothing at mid-range speeds.
- Removed unused deadzone logic for cleaner and more consistent angle smoothing.
2026-04-03 18:10:05 +02:00
DevTekVE 094e834ac4 cleanup: remove unused datafile references and expand ignored patterns
- Deleted `<previouslyLoaded_Datafiles>` sections from PlotJuggler layouts to streamline configuration files.
- Added `.ipynb` files to the `pyproject.toml` ignore list for cleaner tooling.
2026-04-03 17:19:18 +02:00
DevTekVE e4067060b9 Adding ioniq 9 and updating ioniq 5 pe n-line fingerprint 2026-04-03 17:06:15 +02:00
DevTekVE 86a14640b5 Tune speed-dependent steering smoothing to eliminate EPS whine
Reimplemented an Exponential Moving Average (EMA) filter on the requested
steering angle (`apply_angle`). The model's raw high-frequency micro-corrections
at low speeds cause acoustic resonance (whine) in the EPS motor. This filter
dynamically adjusts the smoothing factor (alpha) based on vehicle speed to
silence the EPS at a crawl while maintaining zero-latency precision on the highway.

Key Behaviors & Speed Matrix:
* Deadzone: Ignores angle changes ≤ 0.1° to preserve straight-line tracking.
* 0 km/h (0 mph) -> Alpha: 0.05 (Max smoothing to eliminate stationary vibration)
* 30.6 km/h (19 mph) -> Alpha: 0.10 (Heavy smoothing for stable residential turning)
* 39.6 km/h (25 mph) -> Alpha: 0.30 (Moderate smoothing)
* 49.7 km/h (31 mph) -> Alpha: 0.60 (Light smoothing for responsive city driving)
* 80.0 km/h (50 mph) -> Alpha: 1.00 (Zero smoothing / raw signal for high-speed precision)
2026-04-03 16:13:05 +02:00
DevTekVE 59fb84f0d5 Remove HKG angle control tuning components and dependencies
- Deleted HKG-specific angle tuning settings and related UI elements.
    - Removed tuning parameter handling and smoothing logic from carcontroller.
    - Simplifies codebase and eliminates unused parameters.
2026-04-03 15:33:57 +02:00
DevTekVE 78de201ce7 Bring it back to 360 for hda1s 2026-04-03 15:14:37 +02:00
DevTekVE 17e49f69cc refactor: update parameterized tests and extend Hyundai Ioniq 5 PE model years
- Replaced `parameterized.expand` with new `parameterized` syntax for cleaner test definitions.
- Added 2026 model year to Hyundai Ioniq 5 PE in `car_list.json`.
2026-04-03 14:39:45 +02:00
DevTekVE bec75ebdd8 remove: TorqueReductionGainController and its associated tests
- Fully deprecates the no longer used torque reduction logic.
- Cleans up outdated functionality for clarity and maintainability.
2026-04-03 14:14:07 +02:00
DevTekVE 473832efa7 Merge branch 'master' into hkg-angle-steering-2025
# Conflicts:
#	opendbc_repo
2026-04-03 14:00:54 +02:00
DevTekVE 2cceeb3552 fix: clip steering angle to respect angle limits when latActive is off
- Prevents potential out-of-bound steering angle values.
- Ensures compliance with defined steering angle constraints.
2026-04-03 01:06:37 +02:00
DevTekVE 923a47f713 Reverting all the new control changes until we properly test them on a few variants to ensure it is safe.
Revert "upstream pending tune"

This reverts commit b51d9af9a0.

Revert "show torque reduction gain"

This reverts commit ded0b506d6.

Revert "must gate"

This reverts commit 8b60649eed.

Revert "bump"

This reverts commit 221c219fca.

Revert "temp: comment out blind-spot monitoring signals due to DBC changes"

This reverts commit 790a762a05.
2026-04-01 09:29:53 +02:00
DevTekVE 790a762a05 temp: comment out blind-spot monitoring signals due to DBC changes
- Avoided crash caused by missing signals in updated DBC definitions.
- Added a TODO to revisit and validate blind-spot logic.
2026-04-01 08:55:26 +02:00
Jason Wen 221c219fca bump 2026-03-31 21:57:58 -04:00
Jason Wen 8b60649eed must gate 2026-03-31 21:42:06 -04:00
Jason Wen ded0b506d6 show torque reduction gain 2026-03-31 07:46:13 -04:00
Jason Wen b51d9af9a0 upstream pending tune 2026-03-31 06:56:52 -04:00
Jason Wen 4460ce8166 Merge remote-tracking branch 'sunnypilot/sunnypilot/master' into hkg-angle-steering-2025
# Conflicts:
#	opendbc_repo
2026-03-18 03:43:10 -04:00
Jason Wen f1aa0c7f78 Merge remote-tracking branch 'sunnypilot/sunnypilot/master' into hkg-angle-steering-2025 2026-03-07 01:49:09 -05:00
Jason Wen e7c8126fd9 Merge remote-tracking branch 'sunnypilot/sunnypilot/master' into hkg-angle-steering-2025
# Conflicts:
#	opendbc_repo
2026-03-05 02:01:04 -05:00
Jason Wen 125999c364 Merge remote-tracking branch 'sunnypilot/sunnypilot/master' into hkg-angle-steering-2025
# Conflicts:
#	opendbc_repo
2026-03-01 16:34:41 -05:00
Jason Wen 5b25ea7f99 Merge remote-tracking branch 'sunnypilot/sunnypilot/master' into hkg-angle-steering-2025 2026-02-28 15:47:57 -05:00
Jason Wen b7e2631286 Merge remote-tracking branch 'sunnypilot/sunnypilot/master' into hkg-angle-steering-2025
# Conflicts:
#	opendbc_repo
2026-02-27 21:56:34 -05:00
Jason Wen a838871189 Merge remote-tracking branch 'sunnypilot/sunnypilot/master' into hkg-angle-steering-2025
# Conflicts:
#	opendbc_repo
2026-02-19 01:51:17 -05:00
Jason Wen 1827331599 Merge remote-tracking branch 'sunnypilot/sunnypilot/master' into hkg-angle-steering-2025
# Conflicts:
#	opendbc_repo
2026-02-17 20:12:13 -05:00
Jason Wen 5c777bbe01 Merge remote-tracking branch 'sunnypilot/sunnypilot/master' into hkg-angle-steering-2025 2026-02-13 23:41:06 -05:00
Jason Wen fb97f993d1 Merge remote-tracking branch 'sunnypilot/sunnypilot/master' into hkg-angle-steering-2025 2026-02-13 17:32:10 -05:00
Jason Wen 94b67077e3 Merge remote-tracking branch 'sunnypilot/sunnypilot/master' into hkg-angle-steering-2025
# Conflicts:
#	opendbc_repo
2026-02-12 23:35:46 -05:00
Jason Wen 14f17699b9 Merge remote-tracking branch 'sunnypilot/sunnypilot/master' into hkg-angle-steering-2025 2026-02-11 00:35:20 -05:00
Jason Wen 80e27d5cbb Merge remote-tracking branch 'sunnypilot/sunnypilot/master' into hkg-angle-steering-2025 2026-02-10 23:41:27 -05:00
Jason Wen 039dbcd877 Merge remote-tracking branch 'sunnypilot/sunnypilot/master' into hkg-angle-steering-2025 2026-02-09 01:46:00 -05:00
Jason Wen 8c134ae555 Merge remote-tracking branch 'sunnypilot/sunnypilot/master' into hkg-angle-steering-2025
# Conflicts:
#	opendbc_repo
2026-02-08 20:04:01 -05:00
Jason Wen 276c7a2b34 Merge remote-tracking branch 'sunnypilot/sunnypilot/master' into hkg-angle-steering-2025
# Conflicts:
#	opendbc_repo
2026-02-02 22:40:14 -05:00
Jason Wen 0e2dbcebfa Merge remote-tracking branch 'sunnypilot/sunnypilot/master' into hkg-angle-steering-2025
# Conflicts:
#	opendbc_repo
2026-01-26 11:45:29 -05:00
Jason Wen bbb7760a95 Merge remote-tracking branch 'sunnypilot/sunnypilot/master' into hkg-angle-steering-2025 2026-01-19 01:43:21 -05:00
Jason Wen 23a27b2fbf Merge remote-tracking branch 'sunnypilot/sunnypilot/master' into hkg-angle-steering-2025
# Conflicts:
#	opendbc_repo
2026-01-09 18:48:43 -05:00
Jason Wen 8b78107a40 Merge remote-tracking branch 'sunnypilot/sunnypilot/master' into hkg-angle-steering-2025 2025-12-31 00:49:56 -05:00
Jason Wen c27b6007de wrong bump? 2025-12-26 10:08:31 -05:00
Jason Wen 36c2dce247 Merge remote-tracking branch 'sunnypilot/sunnypilot/master' into hkg-angle-steering-2025 2025-12-26 10:08:23 -05:00
Jason Wen 8035039731 Merge remote-tracking branch 'sunnypilot/sunnypilot/master' into hkg-angle-steering-2025
# Conflicts:
#	opendbc_repo
2025-12-23 00:52:24 -05:00
Jason Wen 8aa6c9440f Merge remote-tracking branch 'sunnypilot/sunnypilot/master' into hkg-angle-steering-2025 2025-12-20 17:01:25 -05:00
Jason Wen 34ef40fd81 Merge remote-tracking branch 'sunnypilot/sunnypilot/master' into hkg-angle-steering-2025
# Conflicts:
#	opendbc_repo
2025-12-18 00:19:20 -05:00
Jason Wen 4d044d7618 Merge remote-tracking branch 'sunnypilot/sunnypilot/master' into hkg-angle-steering-2025 2025-12-15 02:25:04 -05:00
Jason Wen 6247e3dc84 Merge remote-tracking branch 'sunnypilot/sunnypilot/master' into hkg-angle-steering-2025
# Conflicts:
#	opendbc_repo
2025-12-13 01:59:06 -05:00
Jason Wen b1131289b7 Merge remote-tracking branch 'sunnypilot/sunnypilot/master' into hkg-angle-steering-2025 2025-12-07 01:37:16 -05:00
Jason Wen 35dc7d661e Merge remote-tracking branch 'sunnypilot/sunnypilot/master' into hkg-angle-steering-2025 2025-12-07 00:11:54 -05:00
DevTekVE c39b2dad94 Merge branch 'master' into hkg-angle-steering-2025 2025-11-29 10:12:31 +01:00
Jason Wen e6b769245c Merge remote-tracking branch 'sunnypilot/sunnypilot/master' into hkg-angle-steering-2025
# Conflicts:
#	opendbc_repo
#	selfdrive/ui/sunnypilot/SConscript
#	selfdrive/ui/sunnypilot/qt/offroad/settings/lateral_panel.cc
#	selfdrive/ui/sunnypilot/qt/offroad/settings/lateral_panel.h
#	selfdrive/ui/sunnypilot/qt/offroad/settings/longitudinal_panel.cc
2025-11-25 18:54:02 -05:00
DevTekVE 8b94f8b2f8 Merge branch 'master' into hkg-angle-steering-2025 2025-11-06 18:31:16 +01:00
Jason Wen dec014cd17 Merge remote-tracking branch 'sunnypilot/sunnypilot/master' into hkg-angle-steering-2025
# Conflicts:
#	sunnypilot/selfdrive/car/interfaces.py
2025-11-04 17:45:05 -05:00
DevTekVE 7b40272866 Add sunnypilot-specific stats logging and handling
- Introduced `StatLogSP` for sunnypilot-specific metrics.
- Integrated stats collection and submission pathways for sunnylink.
- Extended parameters and handlers to support additional metrics.
- Added gzip compression and base64 encoding for oversized payload handling.
2025-11-04 21:20:16 +01:00
DevTekVE 506456e7f0 Merge branch 'master' into hkg-angle-steering-2025 2025-11-01 13:31:23 +01:00
DevTekVE 4ea4b9d177 Merge branch 'master' into hkg-angle-steering-2025
# Conflicts:
#	opendbc_repo
2025-10-31 06:59:39 +01:00
DevTekVE 0e2313dc31 Merge branch 'master' into hkg-angle-steering-2025 2025-10-18 11:14:45 +02:00
Jason Wen 79ea7db103 Merge remote-tracking branch 'sunnypilot/sunnypilot/master' into hkg-angle-steering-2025 2025-10-17 23:42:01 -04:00
Jason Wen f9ae9192fa Merge branch 'ui-icbm-universal' into hkg-angle-steering-2025 2025-10-17 21:55:00 -04:00
Jason Wen 7ec23006c6 check this 2025-10-17 21:54:44 -04:00
Jason Wen 2be9447a6c Merge branch 'ui-icbm-universal' into hkg-angle-steering-2025 2025-10-17 21:19:09 -04:00
Jason Wen cfd926778e always init true 2025-10-17 21:19:03 -04:00
Jason Wen a97a67e3d0 need 2025-10-17 21:17:31 -04:00
Jason Wen 518b6de08d Merge branch 'ui-icbm-universal' into hkg-angle-steering-2025 2025-10-17 21:15:59 -04:00
Jason Wen 6933e3bcdb fix cruise toggles 2025-10-17 21:15:43 -04:00
Jason Wen 05e0ca8bee some more 2025-10-17 20:46:36 -04:00
Jason Wen 410614fcf3 single location 2025-10-17 20:26:18 -04:00
Jason Wen e2bc0996ef Merge branch 'ui-icbm-universal' into hkg-angle-steering-2025 2025-10-17 12:21:47 -04:00
Jason Wen 1be0c20cf5 oops 2025-10-17 12:21:37 -04:00
Jason Wen 839143b9ed oops 2025-10-17 12:20:23 -04:00
Jason Wen bce86637ae Merge branch 'ui-icbm-universal' into hkg-angle-steering-2025 2025-10-17 12:15:23 -04:00
Jason Wen b833d3ee89 ui: update ICBM-related settings handling 2025-10-17 12:14:44 -04:00
Jason Wen e0441dfb4b Merge branch 'sla-event' into hkg-angle-steering-2025 2025-10-17 11:58:42 -04:00
Jason Wen 62ec40bba6 Speed Limit Assist: update active event handling 2025-10-17 11:58:19 -04:00
Jason Wen 15c6d38028 bump 2025-10-16 17:05:58 -04:00
Jason Wen 56eb9f555c Merge remote-tracking branch 'sunnypilot/sunnypilot/master' into hkg-angle-steering-2025
# Conflicts:
#	sunnypilot/selfdrive/controls/lib/e2e_alerts_helper.py
2025-10-16 01:12:10 -04:00
Jason Wen 2f9951df02 Merge branch 'e2e-alert-state-machine' into hkg-angle-steering-2025 2025-10-15 23:55:40 -04:00
Jason Wen 6030bf4da3 less 2025-10-15 23:52:03 -04:00
Jason Wen 074694d660 lead depart: only arm if we have a confirmed close lead for over a second after allowing alert 2025-10-15 23:48:13 -04:00
Jason Wen df35f48f3b magic 2025-10-15 22:56:08 -04:00
Jason Wen 4fb9704540 time based 2025-10-15 22:51:40 -04:00
Jason Wen 48cbe266fc 10 frames for both 2025-10-15 22:50:42 -04:00
Jason Wen 21aa7ff367 rename 2025-10-15 22:47:08 -04:00
Jason Wen 7caf05dd51 not used 2025-10-15 22:41:00 -04:00
Jason Wen 2d779f5db9 E2E Helper: universal state machine 2025-10-15 22:38:57 -04:00
Jason Wen 18208f1da0 Merge remote-tracking branch 'sunnypilot/sunnypilot/master' into hkg-angle-steering-2025 2025-10-15 17:41:56 -04:00
Jason Wen 5a3c6ddf57 gate lka angle steering out of alpha long 2025-10-14 23:25:00 -04:00
Jason Wen eaa8732ab0 Merge branch 'e2e-alerts-cooldown' into hkg-angle-steering-2025 2025-10-14 14:44:00 -04:00
Jason Wen 6f0284c84f try preventing startup false trigger 2025-10-14 14:43:47 -04:00
Jason Wen 999ea03f23 try preventing startup false trigger 2025-10-14 14:42:42 -04:00
Jason Wen 0975db3ff1 Merge branch 'e2e-alerts-cooldown' into hkg-angle-steering-2025 2025-10-14 14:31:59 -04:00
Jason Wen 8d70a8b80a only when long not engaged 2025-10-14 14:31:48 -04:00
Jason Wen da93f92887 rename 2025-10-14 14:26:57 -04:00
Jason Wen 9117f6c071 Merge branch 'e2e-alerts-cooldown' into hkg-angle-steering-2025 2025-10-14 14:23:46 -04:00
Jason Wen 3567ff9691 introduce recent moving check 2025-10-14 14:22:41 -04:00
Jason Wen f44ae2ced9 too complicated 2025-10-14 14:08:40 -04:00
Jason Wen 376e0ca615 only allow one trigger per standstill session 2025-10-14 14:07:16 -04:00
Jason Wen 32b7686468 Merge branch 'master' into e2e-alerts-cooldown 2025-10-14 11:40:58 -04:00
nayan b9e0f52ea9 E2E Alert Cooldown 2025-10-14 07:43:15 -04:00
Jason Wen a3163b680f Merge branch 'sla-chimes' into hkg-angle-steering-2025 2025-10-14 02:01:05 -04:00
Jason Wen 8a927d808f Merge remote-tracking branch 'sunnypilot/sunnypilot/master' into hkg-angle-steering-2025
# Conflicts:
#	opendbc_repo
2025-10-14 02:00:36 -04:00
Jason Wen bc7d5e474d Speed Limit Assist: audible alerts for certain states 2025-10-14 01:45:13 -04:00
Jason Wen 36f192b5fe Merge remote-tracking branch 'sunnypilot/sunnypilot/master' into hkg-angle-steering-2025 2025-10-13 03:10:47 -04:00
Jason Wen ffd5cd4ac2 Merge remote-tracking branch 'sunnypilot/sunnypilot/master' into hkg-angle-steering-2025 2025-10-11 02:29:47 -04:00
Jason Wen e4a00fcd6c Merge remote-tracking branch 'sunnypilot/sunnypilot/master' into hkg-angle-steering-2025 2025-10-10 17:28:16 -04:00
Jason Wen 0bdcb41103 Merge remote-tracking branch 'sunnypilot/sunnypilot/master' into hkg-angle-steering-2025
# Conflicts:
#	common/params_keys.h
#	opendbc_repo
#	selfdrive/ui/sunnypilot/qt/offroad/settings/lateral_panel.cc
2025-10-10 17:02:14 -04:00
DevTekVE 78051085ca Merge branch 'master' into hkg-angle-steering-2025 2025-09-23 07:54:32 +02:00
DevTekVE 4910d5809a bump opendbc 2025-09-23 07:45:39 +02:00
DevTekVE 8dd862ff28 yikes, becoming picky huh? 2025-09-14 22:50:21 +02:00
DevTekVE 1b57497da9 Merge remote-tracking branch 'origin/master' into hkg-angle-steering-2025
# Conflicts:
#	opendbc_repo
2025-09-14 22:48:00 +02:00
DevTekVE 8d8d1ffc7a bump opendbc again 2025-09-14 22:46:20 +02:00
DevTekVE c5919d5495 wrong dbc lol 2025-09-14 22:42:19 +02:00
DevTekVE da71951c95 This is no longer in use nor needed. Bai! 2025-09-14 12:56:28 +02:00
DevTekVE 25a152cd8b Merge remote-tracking branch 'origin/master' into hkg-angle-steering-2025
# Conflicts:
#	opendbc_repo
2025-09-14 12:44:23 +02:00
DevTekVE 9077a1082a Sorry for C3 :( but moving you out to a last working branch before I sync it up 2025-09-14 06:52:24 +02:00
DevTekVE 7ae7000254 Rework override behavior and feeling 2025-09-14 06:38:00 +02:00
DevTekVE 7029455706 better juggle 2025-09-13 08:32:27 +02:00
DevTekVE 3a71a62215 Merge branch 'master' into hkg-angle-steering-2025 2025-09-12 10:14:52 +02:00
DevTekVE 00622e8c33 Merge remote-tracking branch 'origin/master' into hkg-angle-steering-2025
# Conflicts:
#	opendbc_repo
2025-09-05 09:46:41 +02:00
DevTekVE 549da3ee92 Merge branch 'master' into hkg-angle-steering-2025 2025-09-04 20:20:37 +02:00
DevTekVE e038a65ef8 Merge branch 'master' into hkg-angle-steering-2025 2025-08-31 13:14:33 +02:00
DevTekVE 8d0513c657 dbc: update CHECKSUM format for multiple messages to improve data integrity 2025-08-30 19:56:21 +02:00
DevTekVE 2cea48f4cd Merge remote-tracking branch 'origin/master' into hkg-angle-steering-2025
# Conflicts:
#	opendbc_repo
2025-08-30 15:27:45 +02:00
DevTekVE 8855a9ab65 Improve surprise jerk by safety blocks 2025-08-26 14:47:26 +02:00
DevTekVE 32321c01cc A bit more helpful safety block investigation help 2025-08-26 10:09:11 +02:00
DevTekVE 52cd65fefb lint dont bother me 2025-08-25 08:24:24 +02:00
DevTekVE 1fcdeccd40 Merge branch 'master' into hkg-angle-steering-2025
# Conflicts:
#	common/params_keys.h
#	opendbc_repo
2025-08-25 08:01:51 +02:00
DevTekVE 3517c36978 Revert "Add HkgAngleDebug structure and enhance angle debugging in car controller" 2025-08-24 19:02:48 +02:00
DevTekVE fb30c3c1e8 cleanup and honour params 2025-08-23 15:42:47 +02:00
DevTekVE 1c25e568d5 Update steering pressed logic to include hands-on-wheel detection for improved safety 2025-08-23 15:11:07 +02:00
DevTekVE f172122b7c Update steering pressed logic to include hands-on-wheel detection for improved safety 2025-08-22 19:55:16 +02:00
Jason Wen 67d6cdc7cd Merge remote-tracking branch 'sunnypilot/sunnypilot/hkg-angle-steering-2025' into hkg-angle-steering-2025 2025-08-21 16:39:36 -04:00
DevTekVE 6724085cfd Refactor angle limit calculations and adjust average road roll for improved steering dynamics 2025-08-21 20:09:57 +02:00
DevTekVE 6774f34eee Refine non-linear mapping in torque reduction gain calculation for improved steering response 2025-08-21 00:21:46 +02:00
DevTekVE 6d0402896d Adjust STEER_THRESHOLD and refine non-linear mapping in torque reduction gain calculation for improved steering response 2025-08-20 23:16:04 +02:00
DevTekVE 344021a3d9 Adjust non-linear mapping in torque reduction gain calculation for improved response 2025-08-20 19:54:31 +02:00
DevTekVE a9b85ab27d Refactor HkgAngleDebug structure to include current and baseline limits for angle parameters 2025-08-20 19:54:10 +02:00
DevTekVE 17204a46e4 Add HkgAngleDebug structure and enhance angle debugging in car controller 2025-08-20 18:39:53 +02:00
DevTekVE 7c4d415462 Enhance torque reduction gain calculation with non-linear mapping and smoothing 2025-08-20 00:12:43 +02:00
DevTekVE b8985b6d72 Enhance torque reduction gain calculation with non-linear mapping and smoothing 2025-08-19 19:50:13 +02:00
DevTekVE c669473f88 Refine torque reduction parameters and update UI for angle error analysis 2025-08-19 19:35:34 +02:00
DevTekVE 8751435bf5 Improving tq redc gain and override behavior 2025-08-19 10:08:51 +02:00
DevTekVE 30ae210761 Merge branch 'master' into hkg-angle-steering-2025 2025-08-19 10:07:42 +02:00
Jason Wen 3eb693f58b Merge remote-tracking branch 'sunnypilot/sunnypilot/hkg-angle-steering-2025' into hkg-angle-steering-2025 2025-08-18 12:30:29 -04:00
DevTekVE 7b4a31c5ac bugfix 2025-08-17 16:07:45 +02:00
DevTekVE 1527c8cf88 bump opendbc 2025-08-17 15:31:31 +02:00
DevTekVE ab0a7ae666 no joystick on this branch, causing issues 2025-08-17 15:25:40 +02:00
DevTekVE 11ec2f1f21 Apply suggestions from code review 2025-08-17 15:10:17 +02:00
DevTekVE 2c6808d37e Merge branch 'master' into hkg-angle-steering-2025
# Conflicts:
#	opendbc_repo
2025-08-17 15:02:28 +02:00
Jason Wen 2e96382c49 notebook init 2025-08-17 00:34:01 -04:00
DevTekVE 0239e440ca Adjust replay 2025-08-15 10:32:07 +02:00
Jason Wen 76b972daff Hyundai angle steering: STEERING_ANGLE_2 available on all cars 2025-08-14 01:56:46 -04:00
Jason Wen bc3ef3e7dd Hyundai angle steering: hugging no more - use the true steering angle signal from MDPS 2025-08-13 23:08:32 -04:00
DevTekVE 9839291dd0 Merge remote-tracking branch 'origin/master' into hkg-angle-steering-2025 2025-08-13 20:13:42 +02:00
DevTekVE 17cba328d6 refactor: update torque tuning configuration for angle steering
- Adjusted torque tuning configuration to avoid reliance on torque controller for Hyundai angle steering.
- Simplified control logic by removing unnecessary checks for torque control type.
refactor: clean up code formatting and improve test structure for torque reduction gain
2025-08-13 20:03:51 +02:00
DevTekVE 86093765d8 Merge branch 'master' into hkg-angle-steering-2025
# Conflicts:
#	opendbc_repo
2025-08-13 07:55:46 +02:00
DevTekVE 05fa1c8ae8 Adjust default params and cleanup 2025-08-12 21:36:22 +02:00
DevTekVE e8a40d6b85 Merge branch 'master' into hkg-angle-steering-2025
# Conflicts:
#	opendbc_repo
#	system/manager/process_config.py
2025-08-10 14:24:10 +02:00
DevTekVE c265e0bb85 Merge remote-tracking branch 'origin/master' into hkg-angle-steering-2025
# Conflicts:
#	common/params_keys.h
#	opendbc_repo
#	system/manager/manager.py
2025-08-02 09:56:58 +02:00
DevTekVE c6b118788b Merge branch 'master-new' into hkg-angle-steering-2025 2025-07-31 18:25:08 +02:00
DevTekVE b004f6dbdc Merge branch 'master-new' into hkg-angle-steering-2025 2025-07-31 18:17:34 +02:00
DevTekVE cd4930b680 Bump opendbc 2025-07-26 10:56:49 +02:00
DevTekVE f861aca628 Refactor vehicle model initialization and adjust angle limits for baseline model 2025-07-26 08:12:06 +02:00
DevTekVE 1ff0d8e2ee please don't bother me anymore! 2025-07-26 08:09:51 +02:00
DevTekVE d76d70764e Update slip factor precision for Hyundai steering parameters
- Adjusted `slip_factor` in Hyundai CANFD safety modes for improved consistency and accuracy.
- Ensured proper representation of `slip_factor` output in test logs.
2025-07-25 20:17:19 +02:00
DevTekVE dc73ce0b71 save tools replay 2025-07-25 19:47:31 +02:00
DevTekVE 3f666748af bump opendbc 2025-07-25 14:16:02 +02:00
DevTekVE 8de8a8838c bumo opendbc 2025-07-25 14:08:53 +02:00
DevTekVE f563b7eb71 Refactor steering angle limit application for improved safety and model compliance 2025-07-25 12:12:42 +02:00
DevTekVE 3c18b83708 save temp 2025-07-25 09:56:30 +02:00
DevTekVE bd35f5904b Enhance steering angle rate limiting and safety enforcement logic
- Introduced explicit post-rate limiting using model-specific dynamics.
- Improved low-speed smoothing and precision of applied angles.
2025-07-25 08:12:41 +02:00
DevTekVE 474f2737f6 Refactor steering angle limit logic for conservative seleion
- Removed unused lateral accel/jerk logic for simplicity.
- Updated angle limit calculations to choose the smallest delta for safer control.
2025-07-24 21:48:24 +02:00
DevTekVE ea1ac4a212 Revert "Add configurable max lateral accel and jerk parameters for Hyundai vehicles"
This reverts commit b95f8c5929.

Revert "Add baseline safety model and improve steering angle limiting logic"

This reverts commit b53cbb2e18.

Revert "Disable lateral accel/jerk params and ensure float consistency in angle limits"

This reverts commit 165d7c7b36.
2025-07-24 10:02:48 +02:00
DevTekVE 165d7c7b36 Disable lateral accel/jerk params and ensure float consistency in angle limits
- Commented out unused lateral accel/jerk parameters for clarity.
- Ensured `np.clip` always returns a float for precision.
2025-07-24 09:41:52 +02:00
DevTekVE b53cbb2e18 Add baseline safety model and improve steering angle limiting logic
- Introduced a baseline safety model (`GENESIS_GV80_2025`) for comparison.
- Enhanced steer angle limit calculation using both baseline and current limits for improved safety and precision.
2025-07-24 09:38:03 +02:00
DevTekVE b95f8c5929 Add configurable max lateral accel and jerk parameters for Hyundai vehicles
- Introduced user-configurable options for max lateral acceleration and jerk.
- Enables fine-tuning of vehicle handling for smoother control.
2025-07-24 08:39:10 +02:00
DevTekVE e564bb0b85 bumo openbc 2025-07-23 18:46:52 +02:00
DevTekVE e2ec8a7b13 Refine lateral control limits and simplify safety model handling
- Reduced max lateral acceleration and jerk by 20% for smoother handling.
- Removed unused `get_safety_CP` function, simplifying `VehicleModel` initialization.
2025-07-22 08:07:51 +02:00
DevTekVE 75c6f0f10e Test with gv80 as baseline for limits 2025-07-20 22:14:18 +02:00
DevTekVE af38044b42 Merge branch 'master-new' into hkg-angle-steering-2025 2025-07-20 10:14:46 +02:00
DevTekVE 684fa846d8 Merge branch 'master-new' into hkg-angle-steering-2025
# Conflicts:
#	.codespellignore
#	opendbc_repo
#	system/manager/manager.py
2025-07-19 21:51:46 +02:00
DevTekVE 416e722855 Update baseline model to IONIQ 5 PE for improved angle safety tuning
- Replaced conservative GENESIS_GV80_2025 model with IONIQ 5 PE parameters.
- Adjusted steering parameters (ratio, slip factor, wheelbase) for better lateral control performance.
2025-07-19 21:46:17 +02:00
DevTekVE 52ab3c5a73 feat(hyundai): add interceptor message integration for ADAS CAN
- Added `HYUNDAI_CANFD_ADAS_INTERCEPTOR_MESSAGES` definition for improved ADAS feature support.
- Integrated interceptor message into various Hyundai CAN FD message sets.
2025-07-15 08:06:41 +02:00
DevTekVE 5636681e69 refactor(hyundai): remove redundant superclass initialization
- Eliminates unnecessary `super().__init__()` call in `MadsCarController`.
- Simplifies initialization logic.
2025-07-14 23:34:51 +02:00
DevTekVE f3d2a83542 refactor(hyundai): reorder MadsCarController in inheritance chain
- Reorganized class hierarchy to adjust initialization and behavior.
- Ensures better compatibility with existing controllers and ADAS features.
2025-07-14 23:34:18 +02:00
DevTekVE 7675076636 feat(hyundai): enable alpha longitudinal availability in stock_cp
- Sets `alphaLongitudinalAvailable` to `True` for improved ADAS capabilities.
- Supports future enhancements around ADAS ECU interceptor toggling.
2025-07-14 23:30:38 +02:00
DevTekVE ee2e0789e5 lint 2025-07-14 23:25:56 +02:00
DevTekVE ddd8d777b6 feat(hyundai): add constructors for ADAS ECU interceptor classes
- Added `__init__` methods to initialize parent class with CarParams.
- Improves consistency and readiness for extended functionality.
2025-07-14 23:24:39 +02:00
DevTekVE e3f8ec6d7a lint 2025-07-14 23:22:33 +02:00
DevTekVE fcb864d0c1 feat(hyundai): add base classes for ECU interceptors
- Added abstract base classes for ECU interceptors, car state, car controller, and radar interface.
- Introduced `AdasDrvEcuInterceptor` implementation for specific Hyundai ADAS ECU needs.
2025-07-14 23:20:30 +02:00
DevTekVE 83de699f8b i cant....... 2025-07-13 17:08:36 +02:00
DevTekVE 00f90f7d76 aa2 2025-07-13 17:05:19 +02:00
DevTekVE 4dea3869eb aa2 2025-07-13 17:02:03 +02:00
DevTekVE 73b828d5ca aa2 2025-07-13 16:54:43 +02:00
DevTekVE eb66ac4f72 aa 2025-07-13 16:51:31 +02:00
DevTekVE 6db184eb37 Update ADAS driver intercept message to utilize CC.latActive instead of CC.enabled for testing 2025-07-13 15:06:02 +02:00
DevTekVE c408d96f79 Standardize naming of status field in ADAS driver intercept message
- Renamed `Status` to `status` in `_hyundai_canfd_sunnypilot.dbc` for consistency.
- Updated corresponding field in `create_adas_drv_intercept_msg`.
2025-07-13 15:03:37 +02:00
DevTekVE c830420450 Update ADAS driver intercept message with additional signals and enable flag handling
- Added `CHECKSUM`, `COUNTER`, and `Status` signals to `_hyundai_canfd_sunnypilot.dbc`.
- Enabled flag support in `create_adas_drv_intercept_msg` within `hyundaicanfd.py`.
2025-07-13 14:38:52 +02:00
DevTekVE 9fd4613bbb Add 2025 Kia EV6 support with updated radar and camera fingerprints 2025-07-09 09:47:31 +02:00
DevTekVE a0362e3c5f "Refined UI labels and tooltips for HKG tuning options to improve clarity and user understanding." 2025-06-29 16:48:53 +02:00
DevTekVE e32ef1cdc0 Fix incorrect torque sign usage in torque reduction calculation
Ensure `actuators.torque` uses its absolute value in the `calculate_angle_torque_reduction_gain` method to prevent sign-related issues during Hyundai steering angle control.
2025-06-29 14:33:30 +02:00
DevTekVE 20673ec8a6 Adjust warning font size in angle tuning settings panel. 2025-06-29 13:35:09 +02:00
DevTekVE 53fbdf7329 Rename "IdleTorque" to "ActiveTorque" for clarity.
The parameter name "HkgTuningAngleIdleTorqueReductionGain" was updated to "HkgTuningAngleActiveTorqueReductionGain" across multiple files for better clarity and alignment with its functionality. This change ensures consistency in naming conventions and improves code readability.
2025-06-29 13:23:56 +02:00
DevTekVE 6f72b74fac Add idle torque reduction for Hyundai lateral control
Introduced `ANGLE_IDLE_TORQUE_REDUCTION_GAIN` to manage torque when the vehicle is stationary, ensuring smoother handling and better lane centering. Updated parsing, parameters, and UI settings to support this new idle torque parameter. Adjusted torque calculation logic and smoothing factor behavior for enhanced control flexibility.
2025-06-29 13:22:18 +02:00
DevTekVE e83705a32e Merge branch 'master-new' into hkg-angle-steering-2025
# Conflicts:
#	opendbc_repo
2025-06-29 09:44:01 +02:00
DevTekVE 95d36b9ba2 Refactor and enhance HKG angle tuning logic.
Introduced a toggle for angle smoothing factor and renamed related parameters for clarity. Refactored backend settings to use new parameter names and expanded smoothing matrices for better tuning granularity. Updated UI elements to reflect these changes, emphasizing usability and consistency.
2025-06-28 21:25:44 +02:00
DevTekVE b9e74254bd Merge branch 'master-new' into hkg-angle-steering-2025 2025-06-27 10:46:22 +02:00
DevTekVE b4405b200d Merge remote-tracking branch 'origin/master-new' into hkg-angle-steering-2025 2025-06-25 09:27:21 +02:00
DevTekVE a8a3fdac54 Rename parameter in calculate_target_torque for clarity. 2025-06-23 22:53:45 +02:00
DevTekVE 4eddc622a7 Refactor torque calculations in Hyundai controller
Rename methods and variables for clarity in torque reduction and override calculations. Adjust logic to streamline handling of steering inputs and improve maintainability.
2025-06-23 22:51:40 +02:00
DevTekVE 4e42ada240 Refactor torque management in Hyundai controller for cleaner override and ramp logic
Extract torque ramping and override functionality into dedicated methods within `LkasTorqueManager` to improve maintainability and reduce redundancy. Simplify `update` logic by delegating state-specific operations to new methods.
2025-06-23 22:47:51 +02:00
DevTekVE 6266217655 Introduce LkasTorqueManager for LKAS torque handling in Hyundai controller
Encapsulate LKAS torque calculations, ramping, and override logic into the new `LkasTorqueManager` class to improve modularity and maintainability. Replace existing torque logic with calls to the manager.
2025-06-23 22:20:10 +02:00
DevTekVE ea09d32e98 Remove lateral acceleration logic from Hyundai steering controller 2025-06-23 21:55:17 +02:00
DevTekVE 15958c88d3 Refactor lateral acceleration scaling logic in Hyundai controller
Move scaling of `max_angle_delta` under high lateral acceleration to improve clarity and prevent redundant operations.
2025-06-23 20:22:03 +02:00
DevTekVE b80d7fb5ea Adding GV70 electrified 2026 2025-06-22 14:30:59 +02:00
DevTekVE 1c3d25c6ff Refine lateral acceleration handling in Hyundai steering logic
Enforce absolute check for `real_a_lat` against `MAX_LATERAL_ACCEL` to improve angle scaling under high lateral acceleration conditions.
2025-06-22 11:03:35 +02:00
rav4kumar c9f22b32c7 Revert "Incorporate lateral acceleration in Hyundai angle steering logic"
This reverts commit c0524985bb.
2025-06-21 11:40:58 -07:00
DevTekVE c0524985bb Incorporate lateral acceleration in Hyundai angle steering logic
Add handling for IMU lateral acceleration to refine steering angle limits in CAN FD configurations. Parse and utilize `IMU_LatAccelVal` signal for enhanced lateral control accuracy.
2025-06-21 17:34:13 +02:00
DevTekVE 83839c7ea7 Add angle steering support and refactor related logic for Hyundai CAN FD.
Introduced support for CAN FD angle steering, including updated parameters, signal parsing, and new tests. Refactored related steering logic for clarity, reducing unused code and enhancing maintainability.
2025-06-21 13:38:50 +02:00
DevTekVE c1a1d4b4c3 Update lint script to exclude .xml files in layouts directory
Added `layouts/.*\.xml` to `IGNORED_FILES` in `lint.sh` to prevent linting of layout XML files.
2025-06-20 10:50:45 +02:00
DevTekVE b5af7a905a Merge branch 'master-new' into hkg-angle-steering-2025 2025-06-18 20:13:45 +02:00
DevTekVE 96b1b2f55f Update steering request logic in Hyundai controller
Ensure steering request activation depends on lateral control being active. This adds clarity and aligns better with control logic requirements.
2025-06-17 18:51:54 +02:00
DevTekVE 9361ba5d70 Refactor Hyundai steering angle handling logic
Streamline steering angle calculations and fault avoidance logic by removing redundant comments and unused code. Simplified `round_angle` implementation for clarity and consistency.
2025-06-17 12:08:06 +02:00
DevTekVE 4e9014311e Refactor steeringPressed logic in Hyundai carstate.py.
Revised the determination of `steeringPressed` to account for both hands-on-wheel detection and torque overriding in CAN FD setups. Simplified fallback logic for non-CAN FD configurations for better code clarity and maintainability.
2025-06-12 00:31:07 +02:00
DevTekVE 232873fc70 Refine steering press detection logic.
Adjusted the sensitivity and threshold values for `HOD_Dir_Status` in steering press updates, improving accuracy in detecting steering input. This change aligns with updated parameter requirements for better responsiveness.
2025-06-12 00:14:05 +02:00
DevTekVE 0a61fca9c9 Fix steering press detection for Hyundai models.
Updated the condition to detect steering press by changing HOD_Dir_Status threshold from `> 2` to `>= 2`. This ensures the detection logic aligns correctly with expected behavior.
2025-06-12 00:06:52 +02:00
DevTekVE 480bdc34dc Add support for CANFD angle steering in Hyundai cars
Introduced handling for the `HOD_FD_01_100ms` message when the CANFD angle steering flag is enabled. This ensures proper message parsing and extends compatibility for specific Hyundai vehicle configurations.
2025-06-12 00:04:44 +02:00
DevTekVE 716b475a13 Update Hyundai controls for HOD status and steer limits
Adjusted the steering override frame window and incorporated new HOD_Dir_Status to improve hands-on detection. Added parsing for new signals in Hyundai CAN FD, enhancing steering override responsiveness and reliability.
2025-06-12 00:01:31 +02:00
DevTekVE b1ec5ec034 Adjust override angle cap in Hyundai car controller
Increased the minimum override angle cap from 0.01 to 0.1 and explicitly cast the maximum cap to a float. This change improves consistency and ensures proper handling of steering limits.
2025-06-11 23:20:19 +02:00
DevTekVE 470613c2b7 Adjust Hyundai steer override parameters for improved control.
Reduced the override frame window and updated the angle cap logic to use MAX_ANGLE_RATE. These changes aim to enhance steering responsiveness and safety by fine-tuning steer angle limits.
2025-06-11 23:07:49 +02:00
DevTekVE 336c5b4154 Remove smoothing_factor from Hyundai car controller logic
The `smoothing_factor` parameter and related logic have been removed to simplify the steering angle smoothing approach. All references and usage of this parameter have been eliminated, relying solely on speed-based dynamic interpolation. This change streamlines the code while maintaining functionality.
2025-06-11 23:04:32 +02:00
DevTekVE abdb9dc750 Adjust Hyundai steering override frame logic
Reduced `OVERRIDE_FRAME_WINDOW` and updated condition to properly respect override frame limits. This ensures smoother handling and more precise steering adjustments under certain driving scenarios.
2025-06-11 22:49:04 +02:00
DevTekVE ab98683973 Refactor steering override logic in Hyundai carcontroller
Replaced `recently_overridden` with `frames_since_override` for better granularity and added dynamic override angle limits using interpolation. These changes enhance steering control accuracy during user overrides and improve overall code readability.
2025-06-11 22:42:05 +02:00
DevTekVE 186c24dbe6 Refine Hyundai steering override handling logic
Adjusted logic for recently overridden steering to improve angle limits and torque smoothing. Removed unused or redundant code, optimizing the functionality and maintaining cleaner readability.
2025-06-11 21:49:18 +02:00
DevTekVE 9cdf6340a1 Refactor steering angle smoothing for clarity and reuse.
Extracted the steering angle smoothing logic into a standalone function `sp_smooth_angle` to enhance readability and reusability. Adjusted angle smoothing parameters and introduced a maximum vehicle speed threshold for applying smoothing. Minor updates improve maintainability and ensure consistent behavior across speed ranges.
2025-06-11 10:07:44 +02:00
DevTekVE 2855b1341c Adjust steering thresholds for Hyundai CAN FD vehicles
Updated `STEER_THRESHOLD` to 350 and `NO_LONGER_OVERRIDING_THRESHOLD` to 150 for better alignment with Hyundai CAN FD steering behavior. These changes ensure improved compatibility and more accurate steering response.
2025-06-10 09:53:08 +02:00
DevTekVE cf28f99976 Revert "Add twilsonco's LKAS torque calculator for improved lateral control"
This reverts commit b1770fb0e7aece0e160b1b083cb260edbbdc53dd.
2025-06-10 09:40:59 +02:00
DevTekVE a39d67dc47 Fix apply_angle_last reset logic in Hyundai carcontroller
Re-enables resetting `apply_angle_last` to `steering_angle` when steering is recently overridden. This ensures proper handling of steering angle limits during transitions.
2025-06-08 19:04:02 +02:00
DevTekVE 7e75257f12 Refine Hyundai steering control logic.
Simplified torque ramp-up logic by combining conditions and adjusted `STEER_THRESHOLD` for CANFD angle steering. These changes aim to enhance control precision and maintain consistency in overrides.
2025-06-08 19:02:49 +02:00
DevTekVE df38449553 Reduce override timeout for Hyundai carcontroller
Decrease the override timeout from 100 to 50 frames, ensuring quicker recognition of driver input override. This improves responsiveness and aligns with refined control behavior.
2025-06-08 18:22:44 +02:00
DevTekVE 1385ef3bc5 Fix steering control behavior during user override
Removed restrictive rate limiting during recent user overrides to improve steering response. Adjusted logic to ensure correct handling of steering angle when lateral control is inactive or overridden.
2025-06-08 18:01:47 +02:00
DevTekVE 7c23c11c51 Refine steering logic with override detection.
Adjust steering behavior to account for recent user overrides, improving safety and control. Introduced a "recently_overridden" check to limit angle rates and torque adjustments when user intervention is detected.
2025-06-08 17:52:16 +02:00
DevTekVE aeff2e12ec Refine steering logic with user override handling.
Added logic to use the current steering angle when the steering wheel is pressed, ensuring smoother transitions during user overrides. Updated function parameters and implementation to reflect this enhancement.
2025-06-08 17:38:34 +02:00
DevTekVE 7274899671 Refactor Hyundai override logic for steering thresholds
Removed redundant `recently_overridden` logic and introduced a more robust approach for tracking user steering overrides. Added `NO_LONGER_OVERRIDING_THRESHOLD` and updated conditions to improve steer override handling. Adjustments ensure smoother torque transitions and more accurate steering state detection.
2025-06-08 17:00:44 +02:00
DevTekVE 6c00fd608f pass tests? 2025-06-08 12:28:11 +02:00
DevTekVE df6a034c11 Bump opendbc 2025-06-08 12:26:09 +02:00
DevTekVE acb109c290 adding plotjuggler stuff 2025-06-08 10:02:44 +02:00
DevTekVE b227b00249 Update torque clamping to use parameterized min torque
Replaced hardcoded `angle_min_active_torque` with `ANGLE_MIN_TORQUE` from params for better configurability and consistency. This ensures the torque clamping logic aligns with defined parameters.
2025-06-07 19:43:01 +02:00
DevTekVE 3ec9d6c18a Merge branch 'master-new' into hkg-angle-steering-2025
# Conflicts:
#	common/params_keys.h
2025-06-07 15:04:16 +02:00
DevTekVE 86db8b95f0 Refactor torque calculation and deactivate live tuning.
Updated torque calculation logic with a new optional parameter for minimum active torque, streamlining control behavior. Deactivated and cleaned up references to HkgAngleLiveTuning, simplifying configuration and reducing runtime complexities. Updated relevant UI and parameter descriptions for clarity.
2025-06-07 11:55:57 +02:00
DevTekVE 4cfff8a35f Merge branch 'master-new' into hkg-angle-steering-2025 2025-06-06 23:08:37 +02:00
DevTekVE 962fedf48c Merge branch 'master-new' into hkg-angle-steering-2025
# Conflicts:
#	opendbc/car/tests/routes.py
2025-06-06 20:49:06 +02:00
DevTekVE 04494414d1 Merge branch 'master-new' into hkg-angle-steering-2025
# Conflicts:
#	opendbc_repo
2025-06-05 09:18:53 +02:00
DevTekVE 0b83576e9b Adjust torque ramping logic and update steering thresholds
Increase the override window and refine torque ramp-up behavior to avoid conflicts during recent overrides. Updated steering driver allowance and threshold values for CANFD angle steering to improve compatibility and performance.
2025-06-02 09:49:31 +02:00
DevTekVE ce4ef0f817 Refine steering override logic in Hyundai car controller
Added logic to track recent steering overrides and adjust LKAS torque behavior accordingly. This ensures smoother transitions when the steering is overridden and reduces potential conflicts with driver input. Updated CANFD-specific steering thresholds for enhanced compatibility.
2025-06-02 09:12:03 +02:00
DevTekVE f0b15c1c56 Adding twil's torque calculation 2025-06-01 19:04:34 +02:00
DevTekVE f898e9fdfe Merge branch 'master-new' into hkg-angle-steering-2025
# Conflicts:
#	opendbc_repo
2025-06-01 09:46:45 +02:00
DevTekVE 8ee7804b0e Bump opendbc (no tesla controls, no twil yet) 2025-05-29 16:31:42 +02:00
DevTekVE 923228194e bump opendbc to prior tesla changes until i can pass safety validations 2025-05-28 12:44:44 +02:00
DevTekVE 8837b2e3f6 Merge branch 'master-new' into hkg-angle-steering-2025
# Conflicts:
#	opendbc_repo
2025-05-28 12:36:02 +02:00
DevTekVE f48c9dc1c2 bump opendbc 2025-05-25 17:34:24 +02:00
DevTekVE 74aa07a8cd Ingore something i dont control thx 2025-05-25 17:31:37 +02:00
DevTekVE 5236e4860f Make lint happy, maybe 2025-05-25 17:31:37 +02:00
DevTekVE 3d174da1c3 adding some of my tests and validaitons 2025-05-25 17:31:25 +02:00
DevTekVE 8faa40f3a3 clean 2025-05-25 17:31:25 +02:00
DevTekVE 3e03275f28 Add PlotJuggler layout for analyzing torque and angle data
This new layout visualizes actuator data, CAN steering messages, and car state variables. It provides multiple time-series plots to aid in debugging and analysis. Plugin configurations are also included for extended functionality.
2025-05-25 17:31:22 +02:00
DevTekVE 7595cf8a25 Refine Hyundai angle and torque control logic.
Simplified control flag handling for angle steering, adjusted torque calculations for smoother ramp rates, and updated tuning parameters for the Hyundai Ioniq 5 PE. Minor adjustment to return value handling in lateral control functions.
2025-05-25 17:31:22 +02:00
DevTekVE 2675d43adb bump opendbc
Remove duplicate STEER_ANGLE_SATURATION_THRESHOLD import

Cleaned up an unnecessary duplicate import of STEER_ANGLE_SATURATION_THRESHOLD from latcontrol_angle_torque. This simplifies the module imports and prevents potential redundancy or confusion.

Refactor lateral control to combine torque and angle logic

Merged functionalities of LatControlTorque and LatControlAngle into a single LatControlAngleTorque class. Refactored code to utilize methods from both parent classes, reducing duplication and improving maintainability.

Add angle-torque hybrid lateral control for Hyundai CAN FD

Introduces `LatControlAngleTorque` to enable hybrid angle and torque-based steering for specific Hyundai models. Updates related logic in carcontroller, interface, and controlsd to accommodate this new lateral control method. Adjusts torque parameters for enhanced control in supported models.
2025-05-25 17:31:21 +02:00
DevTekVE d9f4ce82e6 clean 2025-05-25 17:31:21 +02:00
DevTekVE 648a1845d8 cleanup the mess 2025-05-25 17:31:21 +02:00
DevTekVE a87eff6d1c Add HKG Angle Live Tuning parameter and update related handling 2025-05-25 17:31:21 +02:00
DevTekVE dd6ad37e23 Absolutely zero clue on this, I did it with AI and it's for me to play. Don't take this notebook seriously please 2025-05-25 17:31:21 +02:00
DevTekVE c5e778b939 How annoying the linter on a comment lol 2025-05-25 17:31:21 +02:00
DevTekVE a9ab81a77a useless but should keep linter happy 2025-05-25 17:31:21 +02:00
DevTekVE 2d40e1d8e5 Refactor torque parameter handling in Hyundai carcontroller
Replaced direct access to `params` with instance variables for torque parameters to improve code clarity and maintainability. Updated smoothing factor description in angle tuning settings to include speed-related behavior. This enhances readability and prepares for further tuning adjustments.
2025-05-25 17:31:20 +02:00
DevTekVE 7c8f367a5d Fix data type for HkgTuningOverridingCycles value
Updated the value of HkgTuningOverridingCycles to a string for consistency with other parameters in the tuning configuration. This ensures proper handling and avoids potential issues with type mismatches.

Add overriding cycles parameter for torque adjustment

Introduced "HkgTuningOverridingCycles" for configurable user override torque ramp-down cycles. Updated relevant logic in torque control and UI settings to handle the new parameter. This improves flexibility in adjusting steering torque override behavior.
2025-05-25 17:31:20 +02:00
DevTekVE ff4cf558aa Add HKG angle tuning settings with min/max torque parameters
Introduce separate angle tuning controls for HKG vehicles, including smoothing factor, min torque, and max torque parameters. Refactor developer panel to integrate the new settings into a dedicated UI panel, enhancing modularity and customization capabilities.
2025-05-25 17:31:20 +02:00
DevTekVE 0e151e51bc Update HKG Angle Smoothing Factor description in Developer Panel
Enhanced the description to clarify its effect on steering behavior. Included details on how the smoothing factor impacts steering smoothness using EMA, aiding user understanding.
2025-05-25 17:31:20 +02:00
DevTekVE 60cc0031b0 Revert "Revert "Revert the EMA calculation on the curvature to test another approach""
This reverts commit 58fcda8c
2025-05-25 17:31:20 +02:00
DevTekVE d24cac0998 Refactor steering angle logic for smoother control adjustments
Refactored the calculation and application of the steering angle to improve code clarity and ensure smoother transitions. Removed unused parameter update logic in `latcontrol_angle.py` and enhanced handling of driver overrides in `carcontroller.py`.
2025-05-25 17:31:20 +02:00
DevTekVE 45d110830c Fix typo in parameter access method.
Replaced `self._params` with `self.params` to correctly access the parameter `HkgTuningAngleSmoothingFactor`. This ensures the smoothing factor is updated as intended during the control loop.
2025-05-25 17:31:20 +02:00
DevTekVE ea3a9ae911 Improve angle smoothing by integrating dynamic parameter tuning
Introduced a dynamic smoothing factor using the `HkgTuningAngleSmoothingFactor` parameter. This allows more granular control over curvature smoothing based on customizable user input, enhancing driving smoothness. Added necessary logic to process and apply this parameter efficiently.
2025-05-25 17:31:19 +02:00
DevTekVE 6bff8c0e7c Revert "Revert the EMA calculation on the curvature to test another approach"
This reverts commit bd471b3498.
2025-05-25 17:31:19 +02:00
DevTekVE bc6b8802b8 Add HKG angle smoothing factor for steering adjustments
Introduced a new parameter, `HkgTuningAngleSmoothingFactor`, to apply exponential moving average (EMA) smoothing to steering angle changes, reducing sudden adjustments. Added associated UI controls, parameter persistence, and integration into Hyundai carcontroller logic for improved steering stability.
2025-05-25 17:31:19 +02:00
DevTekVE 252ef572d3 Revert the EMA calculation on the curvature to test another approach 2025-05-25 17:31:19 +02:00
DevTekVE 414d397e3f Handle missing pygame import gracefully
Wrap the pygame import in a try-except block to catch ImportError. This prevents the script from crashing and provides a clear message prompting the user to install pygame if it's missing.

Remove "inputs" package and update "pygame" dependency

The "inputs" package has been removed from the lockfile and dependency list, while "pygame" is now included universally without the "dev" extra marker. This change simplifies dependencies and ensures consistency across environments.

Update dependencies: replace 'inputs' with 'pygame'

Replaced the 'inputs' library with 'pygame' for joystickd dependencies in `pyproject.toml`. Additionally, removed a redundant 'pygame' entry from the general dependencies.

Ugly, I know, but soundd is unhappy with joystick

Allowing lat with mads

Invert steering input for joystick control

The steering axis input is now multiplied by -1 to reverse its direction. This ensures correct handling of the left stick's horizontal input, aligning behavior with expected control dynamics.

Refactor joystick control to use pygame for broader support

Replaced the `inputs` library with `pygame` for joystick handling, providing improved compatibility with Xbox and PlayStation controllers. Added initialization, adaptive mappings, deadzone handling, and enhanced event processing for robust joystick operation. Updated README with dependencies and usage information for Xbox controllers.
2025-05-25 17:31:19 +02:00
DevTekVE 11b7b3789d Adjust speed thresholds in filter_speed_matrox.
Updated the `filter_speed_matrox` values to improve curvature filtering behavior at different speeds. This change ensures better handling and stability across a wider range of driving conditions.
2025-05-25 17:31:19 +02:00
DevTekVE 871ac53717 Optimize curvature filtering by adding speed-dependent logic.
Introduced speed-based dynamic alpha adjustment using interpolation for smoother curvature filtering. This improves steering angle calculations by adapting filter sensitivity to vehicle speed, enhancing control performance.
2025-05-25 17:31:19 +02:00
DevTekVE 64ea66b6e6 chsnge alpha to nicer value 2025-05-25 17:31:19 +02:00
DevTekVE 6d7c6759b3 Adjust curvature handling and filtering parameters
Updated curvature breakpoints and torque scaling for improved control in sharp turns. Increased filter alpha for faster curvature response while maintaining system stability.
2025-05-25 17:31:18 +02:00
DevTekVE 4cea013570 Adjust curvature handling and filtering parameters
Updated curvature breakpoints in Hyundai carcontroller to improve torque scaling for curved driving. Slightly refined the filter coefficient in lateral control for smoother curvature filtering and more accurate steering adjustments.
2025-05-25 17:31:18 +02:00
DevTekVE eb375c0587 Refactor curvature-based steering angle and torque logic.
Introduced dynamic torque scaling based on curvature for smoother and more adaptive steering control. Replaced raw curvature inputs with filtered curvature for enhanced stability and reduced noise in steering angle calculations. Removed unused speed scaling logic to simplify the lateral control flow.
2025-05-25 17:31:18 +02:00
DevTekVE 7fd8a5a4bd Reapply "Significant improvement on the jerkiness"
This reverts commit 85ce84e7b7.
2025-05-25 17:31:18 +02:00
DevTekVE b3c90216bb Revert "Significant improvement on the jerkiness"
This reverts commit ea1af879ba2905b076ccfe65993a9db701d689dd.

Revert "More improvement but still not quite"

This reverts commit ad95493c5c61b2ace7c459d2ebc151ddaa80040f.

Revert "Adjust low-speed scaling for lateral control angle"

This reverts commit 6f789ac1ebb66b0239b4028303573c2d7d386b39.

Revert "Refactor speed-based steering scaling logic."

This reverts commit 1d40735ab8db8d470ff3b287a6b42847beffff7d.
2025-05-25 17:31:18 +02:00
DevTekVE 10f345f956 Refactor speed-based steering scaling logic.
Updated the steering angle computation to use a clearer and more descriptive speed-scaling configuration. Replaced low-speed-specific logic with a generalized approach based on speed breakpoints and corresponding influence factors. This improves maintainability and ensures smoother steering adjustments at varying speeds.
2025-05-25 17:31:18 +02:00
DevTekVE 956d2c36d0 Adjust low-speed scaling for lateral control angle
Refined the low-speed scaling parameters by modifying speed breakpoints and factors. This improves handling at lower speeds for smoother and more predictable behavior.
2025-05-25 17:31:18 +02:00
DevTekVE 55e688b6f2 More improvement but still not quite 2025-05-25 17:31:17 +02:00
DevTekVE f017954027 Significant improvement on the jerkiness 2025-05-25 17:31:17 +02:00
DevTekVE 7e992d11b1 bump panda and opendbc 2025-05-25 17:31:15 +02:00
136 changed files with 17344 additions and 189 deletions
+1
View File
@@ -2,5 +2,6 @@ Wen
REGIST
PullRequest
cancelled
indeces
FOF
NoO
@@ -34,6 +34,11 @@ on:
required: false
type: string
default: 'qcom'
on_device:
description: 'Compile on the tici / chestnut runner instead of on a hosted runner with tinygrad''s qcom / amd mock'
required: false
type: boolean
default: false
hf_repo:
description: 'Hugging Face dataset repository (e.g. sunnypilot/sunnypilot_models_v1)'
required: false
@@ -107,6 +112,11 @@ on:
options:
- qcom
- chestnut
on_device:
description: 'Compile on the tici / chestnut runner instead of on a hosted runner with tinygrad''s qcom / amd mock'
required: false
type: boolean
default: false
hf_repo:
description: 'Hugging Face dataset repository'
required: false
@@ -130,6 +140,7 @@ jobs:
is_20hz: ${{ inputs.is_20hz }}
artifact_suffix: ${{ inputs.artifact_suffix }}
target_hardware: ${{ inputs.target_hardware }}
on_device: ${{ inputs.on_device || false }}
secrets: inherit
publish_model:
@@ -0,0 +1,61 @@
name: Chestnut mock build parity
description: >-
Convert one commaai precompiled chestnut model (LS2) on this runner under tinygrad's amd mock, as a hosted chestnut build does, and require the
exact bytes the chestnut runner built (the published artifact). Needs setup-amd-mock, numpy and zstandard; tinygrad_repo checked out.
runs:
using: composite
steps:
- name: Key this check by everything its result depends on
id: key
shell: bash
env:
SOURCES: ${{ hashFiles('tinygrad_repo/tinygrad/**/*.py', 'tinygrad_repo/test/mockgpu/**', 'openpilot/sunnypilot/modeld_v2/*.py', '.github/workflows/chestnut-build-parity/action.yml') }}
run: echo "key=chestnut-build-parity-$SOURCES-$(sha256sum "$LLVM_PATH" | cut -c1-16)-$(python3 -c 'import platform; print(platform.python_version())')" >> "$GITHUB_OUTPUT"
- name: Passed before with all of it identical?
id: passed
uses: actions/cache/restore@v4
with:
path: ~/.chestnut_build_parity.passed
key: ${{ steps.key.outputs.key }}
- name: Rebuild LS2 on the mock and require the chestnut runner's artifact byte for byte
if: steps.passed.outputs.cache-hit != 'true'
shell: bash
env:
REF: b92fc4828664f8767bce5e92f1630ed319cbe509 # commaai/openpilot: precompiled big_driving_tinygrad.pkl, pins tinygrad ec91b74b5b
PKL_OID: b4dead3ee091d66ab002a6b8e716c26f4f79e3c931e4be5f48e017ba92f6e960
PKL_SIZE: "767228907"
TG_SHA: ec91b74b5b6b0fc924b72d3f27689679ca2438b9
WANT: 680a8d629785f2b1d1a2b0e40d0dfbcd0f7291c21e20c51259f1d768a22ec217 # driving_light_speed_2_november_04_2026_tinygrad.pkl, recompiled46
run: |
set -euo pipefail
work="$RUNNER_TEMP/chestnut_parity" && rm -rf "$work" && mkdir -p "$work"
href=$(curl -fsSL --retry 3 -X POST -H "Accept: application/vnd.git-lfs+json" -H "Content-Type: application/vnd.git-lfs+json" \
https://huggingface.co/commaai/openpilot-lfs.git/info/lfs/objects/batch \
-d "{\"operation\":\"download\",\"transfer\":[\"basic\"],\"objects\":[{\"oid\":\"$PKL_OID\",\"size\":$PKL_SIZE}]}" | jq -r '.objects[0].actions.download.href')
curl -fsSL --retry 3 -o "$work/big_driving_tinygrad.pkl" "$href"
echo "$PKL_OID $work/big_driving_tinygrad.pkl" | sha256sum -c -
tg="$work/tinygrad" && git init -q "$tg" && git -C "$tg" fetch -q --depth 1 https://github.com/tinygrad/tinygrad "$TG_SHA" && git -C "$tg" checkout -q FETCH_HEAD
CHECK_OOB=0 GMMU=0 PYTHONPATH="$GITHUB_WORKSPACE/tinygrad_repo" python3 tinygrad_repo/test/mockgpu/usb_server.py \
env DEV=USB+AMD PYTHONPATH="$tg:$GITHUB_WORKSPACE" python3 openpilot/sunnypilot/modeld_v2/convert_upstream_pkl.py "$work/big_driving_tinygrad.pkl" "$work/LS2.pkl"
got=$(sha256sum "$work/LS2.pkl" | cut -d' ' -f1)
if [ "$got" != "$WANT" ]; then
echo "::error::the mock's LS2 build ($got) is not the chestnut runner's ($WANT): this runner's LLVM or the mock no longer builds what the chestnut does"
exit 1
fi
echo "LS2 rebuilt on the mock: byte-identical to the chestnut runner's build"
touch ~/.chestnut_build_parity.passed
- name: Remember the pass
if: steps.passed.outputs.cache-hit != 'true'
uses: actions/cache/save@v4
with:
path: ~/.chestnut_build_parity.passed
key: ${{ steps.key.outputs.key }}
- name: Already passed
if: steps.passed.outputs.cache-hit == 'true'
shell: bash
run: |
echo "LS2 rebuild skipped: it already matched the chestnut runner's build with this exact mock, converter, LLVM and python"
@@ -0,0 +1,60 @@
name: Set up tinygrad's amd mock
description: LLVM 20 and ROCm comgr, as tinygrad_repo/.github/actions/setup-tinygrad installs them for the mock gpu
inputs:
emu_cache:
description: >-
Keep tinygrad's cache db (the emulator's compiled kernels and gate results) between runs under this name, e.g. the model's file name.
Empty: no cache.
default: ''
runs:
using: composite
steps:
- name: Install LLVM 20 and ROCm comgr
shell: bash
run: |
. /etc/os-release
curl -fsSL https://apt.llvm.org/llvm-snapshot.gpg.key | sudo tee /etc/apt/trusted.gpg.d/apt.llvm.org.asc > /dev/null
echo "deb http://apt.llvm.org/$VERSION_CODENAME/ llvm-toolchain-$VERSION_CODENAME-20 main" | sudo tee /etc/apt/sources.list.d/llvm.list
sudo mkdir -p /etc/apt/keyrings
curl -fsSL https://repo.radeon.com/rocm/rocm.gpg.key | gpg --dearmor | sudo tee /etc/apt/keyrings/rocm.gpg > /dev/null
echo "deb [arch=amd64 signed-by=/etc/apt/keyrings/rocm.gpg] https://repo.radeon.com/rocm/apt/7.1 $VERSION_CODENAME main" | sudo tee /etc/apt/sources.list.d/rocm.list
printf 'Package: *\nPin: release o=repo.radeon.com\nPin-Priority: 600\n' | sudo tee /etc/apt/preferences.d/rocm-pin-600
sudo apt-get -qq update && sudo apt-get -qq install -y --no-install-recommends libllvm20 clang-20 lld-20 comgr
printf '/opt/rocm/lib\n/opt/rocm/lib64\n' | sudo tee /etc/ld.so.conf.d/rocm.conf && sudo ldconfig
echo "/usr/lib/llvm-20/bin" >> "$GITHUB_PATH"
llvm=$(ls /usr/lib/llvm-20/lib/libLLVM*.so* /usr/lib/*-linux-gnu/libLLVM-20.so* 2>/dev/null | head -1 || true)
[ -n "$llvm" ] || { echo "::error::libLLVM 20 not found"; exit 1; }
echo "LLVM_PATH=$llvm" >> "$GITHUB_ENV"
- name: Cache the chestnut's firmware
uses: actions/cache@v4
with:
path: ~/.cache/tinygrad/downloads/fw
key: chestnut-fw-${{ hashFiles('tinygrad_repo/tinygrad/runtime/autogen/am/fw.py') }}
- name: Fetch the chestnut's firmware (gitlab times out now and then; the mock boots from it)
shell: bash
run: |
for i in 1 2 3 4 5; do
PYTHONPATH="$GITHUB_WORKSPACE/tinygrad_repo" python3 -c "
from tinygrad.helpers import fetch_fw
from tinygrad.runtime.autogen.am import fw
for n, h in fw.hashes.items():
if n.startswith(('psp_14_0_2_', 'smu_14_0_2.', 'sdma_7_0_0.', 'gc_12_0_0_')): fetch_fw('amdgpu', n, h)" && exit 0
sleep $((i * 10))
done
echo "::error::could not fetch the chestnut's firmware from gitlab"; exit 1
- name: runner cpu
if: inputs.emu_cache != ''
id: cpu
shell: bash
run: echo "cpu=$( (grep -m1 '^model name' /proc/cpuinfo; grep -m1 '^flags' /proc/cpuinfo) | sha256sum | cut -c1-16)" >> "$GITHUB_OUTPUT"
- name: Keep the emulator's compiled kernels between runs
if: inputs.emu_cache != ''
uses: actions/cache@v4
with:
path: ~/.cache/tinygrad/cache.db
key: emu-${{ steps.cpu.outputs.cpu }}-${{ hashFiles('tinygrad_repo/tinygrad/**/*.py', 'tinygrad_repo/test/mockgpu/**') }}-${{ inputs.emu_cache }}
restore-keys: emu-${{ steps.cpu.outputs.cpu }}-${{ hashFiles('tinygrad_repo/tinygrad/**/*.py', 'tinygrad_repo/test/mockgpu/**') }}-
+96 -14
View File
@@ -35,6 +35,11 @@ on:
required: false
type: string
default: 'qcom'
on_device:
description: 'Compile on the tici / chestnut runner instead of on a hosted runner with tinygrad''s qcom / amd mock'
required: false
type: boolean
default: false
workflow_dispatch:
inputs:
upstream_branch:
@@ -59,6 +64,11 @@ on:
- qcom
- chestnut
default: 'qcom'
on_device:
description: 'Compile on the tici / chestnut runner instead of on a hosted runner with tinygrad''s qcom / amd mock'
required: false
type: boolean
default: false
run-name: Build model [${{ inputs.custom_name || inputs.upstream_branch }}] from ref [${{ inputs.upstream_branch }}]
@@ -111,7 +121,12 @@ jobs:
grep -qs "^version https://git-lfs" "$f" || continue
OID=$(awk -F'sha256:' '/^oid/{print $2}' "$f"); SIZE=$(awk '/^size/{print $2}' "$f")
HREF=$(curl -fsSL --retry 3 -X POST -H "Accept: application/vnd.git-lfs+json" -H "Content-Type: application/vnd.git-lfs+json" "$LFS_URL/objects/batch" \
-d "{\"operation\":\"download\",\"transfer\":[\"basic\"],\"objects\":[{\"oid\":\"$OID\",\"size\":$SIZE}]}" | jq -r '.objects[0].actions.download.href')
-d "{\"operation\":\"download\",\"transfer\":[\"basic\"],\"objects\":[{\"oid\":\"$OID\",\"size\":$SIZE}]}" | jq -r '.objects[0].actions.download.href // empty')
if [ -z "$HREF" ]; then
HF_PATH=$(curl -fsSL --retry 3 "https://huggingface.co/api/models/commaai/openpilot_driving_models/tree/main?recursive=true" | jq -r --arg oid "$OID" 'map(select(.lfs.oid == $oid))[0].path // empty')
[ -n "$HF_PATH" ] || { echo "::error::$f ($OID) is in neither openpilot's LFS nor commaai/openpilot_driving_models"; exit 1; }
HREF="https://huggingface.co/commaai/openpilot_driving_models/resolve/main/$HF_PATH"
fi
aria2c -x 16 -s 16 -k 16M --max-tries=5 --retry-wait=5 --file-allocation=none --summary-interval=30 --allow-overwrite=true \
-d "$(dirname "$f")" -o "$(basename "$f")" "$HREF"
echo "$OID $f" | sha256sum -c -
@@ -119,8 +134,9 @@ jobs:
}
UPSTREAM_PKL=selfdrive/modeld/models/big_driving_tinygrad.pkl
if [ "${{ inputs.target_hardware }}" != "chestnut" ]; then
git lfs pull -X "**/selfdrive/modeld/models/big_*.onnx,**/selfdrive/modeld/models/dmonitoring_*.onnx,**/selfdrive/modeld/models/big_*.pkl,**/selfdrive/modeld/models/dmonitoring_*.pkl"
git lfs pull -X "**/selfdrive/modeld/models/big_*.onnx,**/selfdrive/modeld/models/dmonitoring_*.onnx,**/selfdrive/modeld/models/big_*.pkl,**/selfdrive/modeld/models/dmonitoring_*.pkl" || true
rm -f selfdrive/modeld/models/big_*.onnx selfdrive/modeld/models/dmonitoring_*.onnx selfdrive/modeld/models/big_*.pkl selfdrive/modeld/models/dmonitoring_*.pkl
fetch_lfs selfdrive/modeld/models/*.onnx
elif compgen -G "selfdrive/modeld/models/big_*.onnx" > /dev/null; then
fetch_lfs selfdrive/modeld/models/big_*.onnx selfdrive/modeld/models/big_*.pkl
find selfdrive/modeld/models -type f \( -name "*.onnx" -o -name "*.pkl" \) ! -name "big_*.onnx" ! -name "big_*.pkl" -delete
@@ -153,18 +169,67 @@ jobs:
if-no-files-found: error
build_model:
runs-on: [self-hosted, "${{ inputs.target_hardware == 'chestnut' && 'chestnut' || 'tici' }}"]
runs-on: ${{ inputs.on_device && fromJSON(inputs.target_hardware == 'chestnut' && '["self-hosted","chestnut"]' || '["self-hosted","tici"]') || 'ubuntu-24.04' }}
needs: get_model
env:
MODEL_NAME: ${{ inputs.custom_name || inputs.upstream_branch }} (${{ needs.get_model.outputs.model_date }})
REF: ${{ inputs.upstream_branch }}
MOCK_BUILD: ${{ !inputs.on_device }}
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 1
submodules: recursive
- name: Set up the hosted mock build
if: env.MOCK_BUILD == 'true'
uses: actions/setup-python@v5
with:
python-version: '3.12'
- name: Install LLVM 20 and ROCm comgr for the amd mock
if: env.MOCK_BUILD == 'true' && inputs.target_hardware == 'chestnut'
uses: ./.github/workflows/setup-amd-mock
with:
emu_cache: build
- name: Install the amd mock build dependencies
if: env.MOCK_BUILD == 'true' && inputs.target_hardware == 'chestnut'
run: |
python3 -m pip install -q numpy zstandard
- name: Install the qcom mock build dependencies
if: env.MOCK_BUILD == 'true' && inputs.target_hardware != 'chestnut'
id: qcom_deps
run: |
sudo apt-get -qq update && sudo apt-get -qq install -y --no-install-recommends qemu-user-static aria2
python3 -m pip install -q numpy zstandard tinymesa==25.2.7.2
echo "qemu=$(dpkg-query -W -f='${Version}' qemu-user-static)" >> "$GITHUB_OUTPUT"
- name: Compiler check passed before with all of it identical?
if: env.MOCK_BUILD == 'true' && inputs.target_hardware != 'chestnut'
id: qcom_compiler
uses: actions/cache/restore@v4
with:
path: ~/.qcom_compiler_parity.passed
key: qcom-compiler-parity-${{ steps.qcom_deps.outputs.qemu }}-${{ hashFiles('tinygrad_repo/test/device/qcom/compiler_parity.py', 'tinygrad_repo/test/mockgpu/qcom/a630_compiled.pkl.xz', 'tinygrad_repo/tinygrad/runtime/support/compiler_qcom.py') }}
- name: Check the off-device qcom compiler builds the a630's bytes
if: env.MOCK_BUILD == 'true' && inputs.target_hardware != 'chestnut' && steps.qcom_compiler.outputs.cache-hit != 'true'
run: |
# every kernel an a630 has compiled must compile to the same bytes here before a model is built here
PYTHONPATH="$TINYGRAD_PATH" python3 "$TINYGRAD_PATH/test/device/qcom/compiler_parity.py" check "$TINYGRAD_PATH/test/mockgpu/qcom/a630_compiled.pkl.xz"
touch ~/.qcom_compiler_parity.passed
- name: Remember the compiler check passed
if: env.MOCK_BUILD == 'true' && inputs.target_hardware != 'chestnut' && steps.qcom_compiler.outputs.cache-hit != 'true'
uses: actions/cache/save@v4
with:
path: ~/.qcom_compiler_parity.passed
key: ${{ steps.qcom_compiler.outputs.cache-primary-key }}
- name: Set environment variables
if: env.MOCK_BUILD != 'true'
id: set-env
run: |
# Set up common environment
@@ -177,6 +242,7 @@ jobs:
printenv >> $GITHUB_ENV
- name: Setup build environment
if: env.MOCK_BUILD != 'true'
run: |
mkdir -p "${BUILD_DIR}/"
sudo find $BUILD_DIR/ -mindepth 1 -delete
@@ -198,21 +264,28 @@ jobs:
- name: Build Model
run: |
source /etc/profile
export UV_PROJECT_ENVIRONMENT=${HOME}/venv
export VIRTUAL_ENV=$UV_PROJECT_ENVIRONMENT
source ${UV_PROJECT_ENVIRONMENT}/bin/activate
if [ "$MOCK_BUILD" = "true" ]; then
TASKSET=""
export CHECK_OOB=0 GMMU=0 # as test/mockgpu runs the amd mock
else
source /etc/profile
export UV_PROJECT_ENVIRONMENT=${HOME}/venv
export VIRTUAL_ENV=$UV_PROJECT_ENVIRONMENT
source ${UV_PROJECT_ENVIRONMENT}/bin/activate
TASKSET="taskset -c 7"
fi
export PYTHONPATH="${PYTHONPATH}:${{ env.TINYGRAD_PATH }}:${{ github.workspace }}"
COMPILE_MODELD="${{ github.workspace }}/openpilot/sunnypilot/modeld_v2/compile_modeld.py"
MODEL_SIZE=$(python3 -c "from openpilot.common.transformations.model import MEDMODEL_INPUT_SIZE as s; print(f'{s[0]}x{s[1]}')")
CAMERA_RES=$(python3 -c "from openpilot.common.transformations.camera import _ar_ox_fisheye as a, _os_fisheye as o; print(f'{a.width}x{a.height} {o.width}x{o.height}')")
TG_FLAGS_QCOM="DEV=QCOM IMAGE=1 FLOAT16=1 NOLOCALS=1 OPENPILOT_HACKS=1"
MOCK=$([ "$MOCK_BUILD" = "true" ] && echo MOCK || true)
TG_FLAGS_QCOM="DEV=${MOCK:+MOCK+}QCOM IMAGE=1 FLOAT16=1 NOLOCALS=1 OPENPILOT_HACKS=1"
if [ "${{ inputs.target_hardware }}" == "chestnut" ]; then
echo "CHESTNUT build"
export CHESTNUT=1
TG_FLAGS="DEBUG=1 DEV=USB+AMD:LLVM FRAME_DEV=CPU FLOAT16=1 GMMU=0 TC_OPT=2 TC_MIN_GLOBALS=32"
TG_FLAGS="DEBUG=1 DEV=${MOCK}USB+AMD:LLVM FRAME_DEV=CPU FLOAT16=1 GMMU=0 TC_OPT=2 TC_MIN_GLOBALS=32"
OUTPUT_PKL="${{ env.MODELS_DIR }}/big_driving_tinygrad.pkl"
else
echo "QCOM build"
@@ -227,14 +300,16 @@ jobs:
echo "Converting commaai's precompiled model with tinygrad $TG_SHA"
UPSTREAM_TG="${{ runner.temp }}/upstream_tinygrad"
rm -rf "$UPSTREAM_TG" && git init -q "$UPSTREAM_TG" && git -C "$UPSTREAM_TG" fetch -q --depth 1 "$TG_URL" "$TG_SHA" && git -C "$UPSTREAM_TG" checkout -q FETCH_HEAD
ON_MOCK=""
if [ "$MOCK_BUILD" = "true" ]; then ON_MOCK="env PYTHONPATH=$TINYGRAD_PATH python3 $TINYGRAD_PATH/test/mockgpu/usb_server.py"; fi
CONVERTED="${{ runner.temp }}/big_driving_tinygrad_plain.pkl"
env DEV=USB+AMD PYTHONPATH="$UPSTREAM_TG:${{ github.workspace }}" taskset -c 7 python3 openpilot/sunnypilot/modeld_v2/convert_upstream_pkl.py \
$ON_MOCK env DEV=USB+AMD PYTHONPATH="$UPSTREAM_TG:${{ github.workspace }}" $TASKSET python3 openpilot/sunnypilot/modeld_v2/convert_upstream_pkl.py \
"${{ env.MODELS_DIR }}/big_driving_tinygrad.pkl" "$CONVERTED"
mv "$CONVERTED" "$OUTPUT_PKL"
elif NEW_ARCH_ONNX=$(find "${{ env.MODELS_DIR }}" -maxdepth 1 -name "${{ inputs.target_hardware == 'chestnut' && 'big_' || '' }}*driving*.onnx" -print -quit) &&
[ -n "$NEW_ARCH_ONNX" ] && grep -qa new_img "$NEW_ARCH_ONNX"; then # the new architecture: one ONNX taking the warped frames as new_img
echo "Compiling new architecture ONNX: $NEW_ARCH_ONNX"
env ${TG_FLAGS} taskset -c 7 python3 openpilot/sunnypilot/modeld_v2/compile_modeld_v2.py \
env ${TG_FLAGS} $TASKSET python3 openpilot/sunnypilot/modeld_v2/compile_modeld_v2.py \
"$NEW_ARCH_ONNX" "$OUTPUT_PKL" --device-input "*" --benchmark-runs 1
else
echo "Detected onnx architecture. Routing to native compile_modeld.py."
@@ -284,7 +359,7 @@ jobs:
if [ -n "$MODEL_TYPE" ]; then
echo "Detected: $MODEL_TYPE -> $OUTPUT_PKL"
env ${TG_FLAGS} taskset -c 7 python3 "$COMPILE_MODELD" \
env ${TG_FLAGS} $TASKSET python3 "$COMPILE_MODELD" \
--model-type $MODEL_TYPE \
--model-size $MODEL_SIZE \
--camera-resolutions $CAMERA_RES \
@@ -293,6 +368,13 @@ jobs:
fi
fi
- name: Replay its check frame on the mock and require the result bit for bit
if: env.MOCK_BUILD == 'true'
env:
DEV: ${{ inputs.target_hardware == 'chestnut' && 'MOCKUSB+AMD' || 'MOCK+QCOM' }}
PYTHONPATH: ${{ env.TINYGRAD_PATH }}:${{ github.workspace }}
run: python3 -m openpilot.sunnypilot.modeld_v2.mock_parity check "${{ env.MODELS_DIR }}/${{ inputs.target_hardware == 'chestnut' && 'big_' || '' }}driving_tinygrad.pkl"
- name: Prepare Output
run: |
sudo rm -rf ${{ env.OUTPUT_DIR }}
@@ -304,7 +386,7 @@ jobs:
--include='/${{ inputs.target_hardware == 'chestnut' && 'big_' || '' }}driving_tinygrad.pkl' \
--exclude='*' \
--delete-excluded \
--chown=comma:comma \
$([ "$MOCK_BUILD" = "true" ] || echo --chown=comma:comma) \
${{ env.MODELS_DIR }}/ ${{ env.OUTPUT_DIR }}/
python3 "${{ github.workspace }}/release/ci/model_generator.py" \
@@ -333,7 +415,7 @@ jobs:
path: ${{ env.OUTPUT_DIR }}/artifact_name.txt
- name: Re-enable powersave
if: always()
if: always() && env.MOCK_BUILD != 'true'
run: |
source ${UV_PROJECT_ENVIRONMENT}/bin/activate
PYTHONPATH=$PYTHONPATH:${{ github.workspace }}/ ${{ github.workspace }}/scripts/manage-powersave.py --enable
+88 -13
View File
@@ -28,18 +28,7 @@ jobs:
env:
DEV: CPU
run: tools/op.sh test -v openpilot/sunnypilot/modeld_v2/tests/test_plain_artifact.py
- name: Install LLVM 20 and ROCm comgr for the amd mock, as tinygrad_repo/.github/actions/setup-tinygrad does
run: |
. /etc/os-release
curl -fsSL https://apt.llvm.org/llvm-snapshot.gpg.key | sudo tee /etc/apt/trusted.gpg.d/apt.llvm.org.asc > /dev/null
echo "deb http://apt.llvm.org/$VERSION_CODENAME/ llvm-toolchain-$VERSION_CODENAME-20 main" | sudo tee /etc/apt/sources.list.d/llvm.list
sudo mkdir -p /etc/apt/keyrings
curl -fsSL https://repo.radeon.com/rocm/rocm.gpg.key | gpg --dearmor | sudo tee /etc/apt/keyrings/rocm.gpg > /dev/null
echo "deb [arch=amd64 signed-by=/etc/apt/keyrings/rocm.gpg] https://repo.radeon.com/rocm/apt/7.1 $VERSION_CODENAME main" | sudo tee /etc/apt/sources.list.d/rocm.list
printf 'Package: *\nPin: release o=repo.radeon.com\nPin-Priority: 600\n' | sudo tee /etc/apt/preferences.d/rocm-pin-600
sudo apt-get -qq update && sudo apt-get -qq install -y --no-install-recommends libllvm20 clang-20 lld-20 comgr
printf '/opt/rocm/lib\n/opt/rocm/lib64\n' | sudo tee /etc/ld.so.conf.d/rocm.conf && sudo ldconfig
echo "/usr/lib/llvm-20/bin" >> "$GITHUB_PATH"
- uses: ./.github/workflows/setup-amd-mock
- name: Convert a pickled USB+AMD jit and replay it under tinygrad's amd mock
env:
DEV: MOCKUSB+AMD
@@ -80,6 +69,8 @@ jobs:
runs-on: ubuntu-latest
outputs:
models: ${{ steps.set-matrix.outputs.models }}
chestnut: ${{ steps.set-matrix.outputs.chestnut }}
qcom: ${{ steps.set-matrix.outputs.qcom }}
steps:
- uses: actions/checkout@v4
- name: Fetch and Parse json
@@ -91,16 +82,22 @@ jobs:
with open("openpilot/sunnypilot/models/fetcher.py", "r") as f:
urls = re.findall(r"MODEL_URL(?:_CHESTNUT)?\s*=\s*[\"'"'"']([^\"'"'"']+)[\"'"'"']", f.read())
artifacts = []
artifacts, chestnut, qcom = [], [], []
for url in urls:
data = json.loads(urllib.request.urlopen(url).read())
for bundle in data.get("bundles", []):
for model in bundle.get("models", []):
if "artifact" in model:
artifacts.append(model["artifact"])
if "chestnut" in url:
chestnut.append(model["artifact"])
elif "tinygrad" in model["artifact"]["file_name"]:
qcom.append(model["artifact"])
with open(os.environ["GITHUB_OUTPUT"], "a") as f:
f.write(f"models={json.dumps(artifacts)}\n")
f.write(f"chestnut={json.dumps(chestnut)}\n")
f.write(f"qcom={json.dumps(qcom)}\n")
'
test-model:
@@ -137,3 +134,81 @@ jobs:
export PYTHONPATH="$GITHUB_WORKSPACE/tinygrad_repo:$GITHUB_WORKSPACE:$PYTHONPATH"
python3 -m pip uninstall -y tinygrad || uv pip uninstall -y tinygrad --system || true
python3 -m pytest openpilot/sunnypilot/modeld_v2/tests/test_models.py
chestnut-mock-parity:
name: Mock parity ${{ matrix.artifact.file_name }}
needs: generate-matrix
runs-on: ubuntu-24.04
strategy:
fail-fast: false
matrix:
artifact: ${{ fromJson(needs.generate-matrix.outputs.chestnut) }}
steps:
- uses: actions/checkout@v4
with:
submodules: true
- uses: ./.github/workflows/setup-amd-mock
with:
emu_cache: ${{ matrix.artifact.file_name }}
- run: python3 -m pip install -q numpy
- name: Download model
env:
HF_TOKEN: ${{ secrets.HF_TOKEN }}
MODEL_URL: ${{ matrix.artifact.download_uri.url }}
MODEL_SHA: ${{ matrix.artifact.download_uri.sha256 }}
shell: bash
run: |
AUTH=()
if [ -n "$HF_TOKEN" ]; then AUTH=(-H "Authorization: Bearer $HF_TOKEN"); fi
curl --retry 3 --retry-all-errors -s -S -f -L "${AUTH[@]}" -o "$RUNNER_TEMP/model.pkl" "$MODEL_URL"
if [ -n "$MODEL_SHA" ]; then echo "$MODEL_SHA $RUNNER_TEMP/model.pkl" | sha256sum -c -; fi
- name: Replay its check frame on the amd mock and require the chestnut's result bit for bit
env:
PYTHONPATH: ${{ github.workspace }}/tinygrad_repo:${{ github.workspace }}
run: python3 -m openpilot.sunnypilot.modeld_v2.mock_parity check "$RUNNER_TEMP/model.pkl"
qcom-mock-parity:
name: QCOM mock parity ${{ matrix.artifact.file_name }}
needs: generate-matrix
runs-on: ubuntu-24.04
strategy:
fail-fast: false
matrix:
artifact: ${{ fromJson(needs.generate-matrix.outputs.qcom) }}
steps:
- uses: actions/checkout@v4
with:
submodules: true
- uses: actions/setup-python@v5
with:
python-version: '3.12'
- run: python3 -m pip install -q numpy tinymesa==25.2.7.2
- name: Download model
env:
HF_TOKEN: ${{ secrets.HF_TOKEN }}
MODEL_URL: ${{ matrix.artifact.download_uri.url }}
MODEL_SHA: ${{ matrix.artifact.download_uri.sha256 }}
shell: bash
run: |
AUTH=()
if [ -n "$HF_TOKEN" ]; then AUTH=(-H "Authorization: Bearer $HF_TOKEN"); fi
curl --retry 3 --retry-all-errors -s -S -f -L "${AUTH[@]}" -o "$RUNNER_TEMP/model.pkl" "$MODEL_URL"
if [ -n "$MODEL_SHA" ]; then echo "$MODEL_SHA $RUNNER_TEMP/model.pkl" | sha256sum -c -; fi
- name: Replay its check frame on the qcom mock and require the comma device's result bit for bit
env:
DEV: MOCK+QCOM
PYTHONPATH: ${{ github.workspace }}/tinygrad_repo:${{ github.workspace }}
run: python3 -m openpilot.sunnypilot.modeld_v2.mock_parity check "$RUNNER_TEMP/model.pkl"
chestnut-mock-build-parity:
name: Chestnut build on the amd mock = chestnut runner build
runs-on: ubuntu-24.04
steps:
- uses: actions/checkout@v4
with:
submodules: true
- uses: ./.github/workflows/setup-amd-mock
with:
emu_cache: chestnut-build-parity
- run: python3 -m pip install -q numpy zstandard
- uses: ./.github/workflows/chestnut-build-parity
+1
View File
@@ -149,6 +149,7 @@ jobs:
process_replay:
name: process replay
if: false #process replay disabled for angle steering until we are ready to merge it
runs-on: ${{
(github.repository == 'commaai/openpilot') &&
((github.event_name != 'pull_request') ||
+7
View File
@@ -21,5 +21,12 @@
</clean>
</configuration>
</target>
<target id="f2590b2b-9b93-49f9-8510-da3f3724a2ae" name="replay" defaultType="TOOL">
<configuration id="d475264f-6f4c-4092-9b4e-6773309f38b7" name="replay" toolchainName="Default">
<build type="TOOL">
<tool actionId="Tool_External Tools_uv build tools replay" />
</build>
</configuration>
</target>
</component>
</project>
+7
View File
@@ -20,4 +20,11 @@
<option name="WORKING_DIRECTORY" value="$ProjectFileDir$" />
</exec>
</tool>
<tool name="uv build tools replay" showInMainMenu="false" showInEditor="false" showInProject="false" showInSearchPopup="false" disabled="false" useConsole="true" showConsoleOnStdOut="false" showConsoleOnStdErr="false" synchronizeAfterRun="true">
<exec>
<option name="COMMAND" value="bash" />
<option name="PARAMETERS" value="-c &quot;source .venv/bin/activate &amp;&amp; scons -u -j$(nproc) tools/replay/&quot;" />
<option name="WORKING_DIRECTORY" value="$ProjectFileDir$" />
</exec>
</tool>
</toolSet>
+1 -1
View File
@@ -1,5 +1,5 @@
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="Build Debug" type="CLionExternalRunConfiguration" factoryName="Application" REDIRECT_INPUT="false" ELEVATE="false" USE_EXTERNAL_CONSOLE="false" EMULATE_TERMINAL="false" WORKING_DIR="file://$ProjectFileDir$/selfdrive/ui" PASS_PARENT_ENVS_2="true" PROJECT_NAME="sunnypilot" TARGET_NAME="uv Scons Build Debug" CONFIG_NAME="uv Scons Build Debug" RUN_PATH="ui">
<configuration default="false" name="Build Debug" type="CLionExternalRunConfiguration" factoryName="Application" REDIRECT_INPUT="false" ELEVATE="false" USE_EXTERNAL_CONSOLE="false" EMULATE_TERMINAL="false" WORKING_DIR="file://$ProjectFileDir$/selfdrive/ui" PASS_PARENT_ENVS_2="true" PROJECT_NAME="openpilot-special" TARGET_NAME="uv Scons Build Debug" CONFIG_NAME="uv Scons Build Debug" RUN_PATH="ui">
<envs>
<env name="QT_DBL_CLICK_DIST" value="150" />
</envs>
+27
View File
@@ -0,0 +1,27 @@
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="Debug Route Controls" type="PythonConfigurationType" factoryName="Python">
<module name="openpilot-special" />
<option name="ENV_FILES" value="" />
<option name="INTERPRETER_OPTIONS" value="" />
<option name="PARENT_ENVS" value="true" />
<envs>
<env name="PYTHONUNBUFFERED" value="1" />
<env name="FINGERPRINT" value="KIA_EV9" />
<env name="SKIP_FW_QUERY" value="1" />
</envs>
<option name="SDK_HOME" value="" />
<option name="WORKING_DIRECTORY" value="$PROJECT_DIR$/selfdrive/car" />
<option name="IS_MODULE_SDK" value="true" />
<option name="ADD_CONTENT_ROOTS" value="true" />
<option name="ADD_SOURCE_ROOTS" value="true" />
<EXTENSION ID="PythonCoverageRunConfigurationExtension" runner="coverage.py" />
<option name="SCRIPT_NAME" value="$PROJECT_DIR$/selfdrive/car/card.py" />
<option name="PARAMETERS" value="" />
<option name="SHOW_COMMAND_LINE" value="false" />
<option name="EMULATE_TERMINAL" value="true" />
<option name="MODULE_MODE" value="false" />
<option name="REDIRECT_INPUT" value="false" />
<option name="INPUT_FILE" value="" />
<method v="2" />
</configuration>
</component>
+7
View File
@@ -0,0 +1,7 @@
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="Replay for controls + ui" type="Multirun" separateTabs="false" reuseTabsWithFailures="false" startOneByOne="true" markFailedProcess="true" hideSuccessProcess="false" delayTime="0.0">
<runConfiguration name="replay for controls" type="Native Application" />
<runConfiguration name="Build Debug" type="Custom Build Application" />
<method v="2" />
</configuration>
</component>
+7
View File
@@ -0,0 +1,7 @@
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="replay for controls" type="CLionNativeAppRunConfigurationType" focusToolWindowBeforeRun="true" PROGRAM_PARAMS="&quot;$Prompt$&quot; --block &quot;sendcan,carState,carParams,carOutput,liveTracks,carParamsSP,carStateSP,bookmarkButton&quot;" REDIRECT_INPUT="false" ELEVATE="false" USE_EXTERNAL_CONSOLE="false" EMULATE_TERMINAL="true" WORKING_DIR="file://$ProjectFileDir$/tools/replay" PASS_PARENT_ENVS_2="true" PROJECT_NAME="openpilot-special" TARGET_NAME="replay" CONFIG_NAME="replay" version="1" RUN_PATH="replay">
<method v="2">
<option name="CLION.COMPOUND.BUILD" enabled="true" />
</method>
</configuration>
</component>
+1 -1
View File
@@ -16,7 +16,7 @@ export VECLIB_MAXIMUM_THREADS=1
export QCOM_PRIORITY=12
if [ -z "$AGNOS_VERSION" ]; then
export AGNOS_VERSION="19.9"
export AGNOS_VERSION="19.9-sunnypilot.3"
fi
export STAGING_ROOT="/data/safe_staging"
+3
View File
@@ -360,6 +360,7 @@ struct OnroadEventSP @0xda96579883444c35 {
e2eChime @23;
laneChangeRoadEdge @24;
bigModelReady @25;
stockSteerIntervention @26;
}
}
@@ -389,6 +390,7 @@ struct CarControlSP @0xa5cd762cd951a455 {
leadOne @2 :LeadData;
leadTwo @3 :LeadData;
intelligentCruiseButtonManagement @4 :IntelligentCruiseButtonManagement;
pathCurvature @5 :Float32;
struct Param {
key @0 :Text;
@@ -453,6 +455,7 @@ struct BackupManagerSP @0xf98d843bfd7004a3 {
struct CarStateSP @0xb86e6369214c01c8 {
speedLimit @0 :Float32;
stockSteerIntervention @1 :Bool;
}
struct LiveMapDataSP @0xf416ec09499d9d19 {
+16 -16
View File
@@ -1,7 +1,7 @@
[
{
"name": "xbl",
"url": "https://commadist.azureedge.net/agnosupdate/xbl-e8acf2a9cc7f0ce84cb803bfea9477f765c0d7b4daf26048e59651b9e6a7bfbb.img.xz",
"url": "https://huggingface.co/sunnypilot/agnos/resolve/main/xbl-e8acf2a9cc7f0ce84cb803bfea9477f765c0d7b4daf26048e59651b9e6a7bfbb.img.xz",
"hash": "e8acf2a9cc7f0ce84cb803bfea9477f765c0d7b4daf26048e59651b9e6a7bfbb",
"hash_raw": "e8acf2a9cc7f0ce84cb803bfea9477f765c0d7b4daf26048e59651b9e6a7bfbb",
"size": 3282256,
@@ -12,7 +12,7 @@
},
{
"name": "xbl_config",
"url": "https://commadist.azureedge.net/agnosupdate/xbl_config-758552ecf92b5569677197783bf0ccb73d7f961685308e45d3276ac9dd974f85.img.xz",
"url": "https://huggingface.co/sunnypilot/agnos/resolve/main/xbl_config-758552ecf92b5569677197783bf0ccb73d7f961685308e45d3276ac9dd974f85.img.xz",
"hash": "758552ecf92b5569677197783bf0ccb73d7f961685308e45d3276ac9dd974f85",
"hash_raw": "758552ecf92b5569677197783bf0ccb73d7f961685308e45d3276ac9dd974f85",
"size": 98124,
@@ -23,7 +23,7 @@
},
{
"name": "abl",
"url": "https://commadist.azureedge.net/agnosupdate/abl-29fd7ed1c012e599420764840f9f11286d34dbff4adaf102a447f06d8c5e0b35.img.xz",
"url": "https://huggingface.co/sunnypilot/agnos/resolve/main/abl-29fd7ed1c012e599420764840f9f11286d34dbff4adaf102a447f06d8c5e0b35.img.xz",
"hash": "29fd7ed1c012e599420764840f9f11286d34dbff4adaf102a447f06d8c5e0b35",
"hash_raw": "29fd7ed1c012e599420764840f9f11286d34dbff4adaf102a447f06d8c5e0b35",
"size": 274432,
@@ -34,7 +34,7 @@
},
{
"name": "aop",
"url": "https://commadist.azureedge.net/agnosupdate/aop-78b2287ca219a0811b3004c523fa0f4749e4d1fd92be3aba61699305b7943ad1.img.xz",
"url": "https://huggingface.co/sunnypilot/agnos/resolve/main/aop-78b2287ca219a0811b3004c523fa0f4749e4d1fd92be3aba61699305b7943ad1.img.xz",
"hash": "78b2287ca219a0811b3004c523fa0f4749e4d1fd92be3aba61699305b7943ad1",
"hash_raw": "78b2287ca219a0811b3004c523fa0f4749e4d1fd92be3aba61699305b7943ad1",
"size": 184364,
@@ -45,7 +45,7 @@
},
{
"name": "devcfg",
"url": "https://commadist.azureedge.net/agnosupdate/devcfg-f71df3a86958c093ba3969254c4db025187eef9385427f1ade946742939b43cc.img.xz",
"url": "https://huggingface.co/sunnypilot/agnos/resolve/main/devcfg-f71df3a86958c093ba3969254c4db025187eef9385427f1ade946742939b43cc.img.xz",
"hash": "f71df3a86958c093ba3969254c4db025187eef9385427f1ade946742939b43cc",
"hash_raw": "f71df3a86958c093ba3969254c4db025187eef9385427f1ade946742939b43cc",
"size": 40336,
@@ -56,28 +56,28 @@
},
{
"name": "boot",
"url": "https://commadist.azureedge.net/agnosupdate/boot-b9c9b9261fca0cef9e6d9b198fa4b563767e6342afc7a61ab137b2b519260615.img.xz",
"hash": "b9c9b9261fca0cef9e6d9b198fa4b563767e6342afc7a61ab137b2b519260615",
"hash_raw": "b9c9b9261fca0cef9e6d9b198fa4b563767e6342afc7a61ab137b2b519260615",
"size": 46962688,
"url": "https://huggingface.co/sunnypilot/agnos/resolve/main/boot-2dbccc9ba3ef6e3f6fa95a100fe73340e5ea526ce6d64685605226d25066035b.img.xz",
"hash": "2dbccc9ba3ef6e3f6fa95a100fe73340e5ea526ce6d64685605226d25066035b",
"hash_raw": "2dbccc9ba3ef6e3f6fa95a100fe73340e5ea526ce6d64685605226d25066035b",
"size": 47859712,
"sparse": false,
"full_check": true,
"has_ab": true,
"ondevice_hash": "3ef4769bb1cc73bfc31f96f073b46af42dcc0bad4ab2dde32d11929745d0cd28"
"ondevice_hash": "43739cdc82df6616ecaa1360bfb36e0eaf92f53bdd6fbc033f30e2830e7452a4"
},
{
"name": "system",
"url": "https://commadist.azureedge.net/agnosupdate/system-80d9373348ddff2a5d1f534fab3420383939c96f3eba60baab6b15339fc602c7.img.xz",
"hash": "9aebca09b9d142718e71efbfe44b723010eec6e70067c043c63186067291739d",
"hash_raw": "80d9373348ddff2a5d1f534fab3420383939c96f3eba60baab6b15339fc602c7",
"url": "https://huggingface.co/sunnypilot/agnos/resolve/main/system-d2ee705bfb45ce9a7ca70840a3cf9563ef30946d3e26d0233d63d8a7439a3a93.img.xz",
"hash": "a40883c96fbb0460b7f8d18ccf37e2d94fdd43aaa02cb477526f1008d430217b",
"hash_raw": "d2ee705bfb45ce9a7ca70840a3cf9563ef30946d3e26d0233d63d8a7439a3a93",
"size": 4718592000,
"sparse": true,
"full_check": false,
"has_ab": true,
"ondevice_hash": "270b76c5c5568828e3883390b83ea445425a104dd42119d68f06093ce6b6fcef",
"ondevice_hash": "17aec6e1a6570613cf795e2e23f743b946201202633306bdc30b935c805bc3fd",
"alt": {
"hash": "80d9373348ddff2a5d1f534fab3420383939c96f3eba60baab6b15339fc602c7",
"url": "https://commadist.azureedge.net/agnosupdate/system-80d9373348ddff2a5d1f534fab3420383939c96f3eba60baab6b15339fc602c7.img",
"hash": "d2ee705bfb45ce9a7ca70840a3cf9563ef30946d3e26d0233d63d8a7439a3a93",
"url": "https://huggingface.co/sunnypilot/agnos/resolve/main/system-d2ee705bfb45ce9a7ca70840a3cf9563ef30946d3e26d0233d63d8a7439a3a93.img",
"size": 4718592000
}
}
+11 -1
View File
@@ -156,6 +156,8 @@ inline static std::unordered_map<std::string, ParamKeyAttributes> keys = {
{"BlinkerLateralReengageDelay", {PERSISTENT | BACKUP, INT, "0"}}, // seconds
{"BlinkerMinLateralControlSpeed", {PERSISTENT | BACKUP, INT, "20"}}, // MPH or km/h
{"BlinkerPauseLateralControl", {PERSISTENT | BACKUP, INT, "0"}},
{"BluetoothAllowed", {PERSISTENT, BOOL, "1"}},
{"BluetoothEnabled", {CLEAR_ON_MANAGER_START, BOOL, "0"}},
{"Brightness", {PERSISTENT | BACKUP, INT, "0"}},
{"CarList", {PERSISTENT, JSON}},
{"CarParamsSP", {CLEAR_ON_MANAGER_START | CLEAR_ON_ONROAD_TRANSITION, BYTES}},
@@ -169,6 +171,7 @@ inline static std::unordered_map<std::string, ParamKeyAttributes> keys = {
{"CustomAccShortPressIncrement", {PERSISTENT | BACKUP, INT, "1"}},
{"DeviceBootMode", {PERSISTENT | BACKUP, INT, "0"}},
{"DevUIInfo", {PERSISTENT | BACKUP, INT, "0"}},
{"DrawRadarTracks", {PERSISTENT | BACKUP, BOOL, "0"}},
{"EnableCopyparty", {PERSISTENT | BACKUP, BOOL}},
{"EnableGithubRunner", {PERSISTENT | BACKUP, BOOL}},
{"GreenLightAlert", {PERSISTENT | BACKUP, BOOL, "0"}},
@@ -181,6 +184,7 @@ inline static std::unordered_map<std::string, ParamKeyAttributes> keys = {
{"LastGPSPositionFused", {PERSISTENT, STRING}},
{"LeadDepartAlert", {PERSISTENT | BACKUP, BOOL, "0"}},
{"MaxTimeOffroad", {PERSISTENT | BACKUP, INT, "1800"}},
{"MiciRoboticUI", {PERSISTENT | BACKUP, BOOL, "0"}},
{"ModelRunnerTypeCache", {CLEAR_ON_ONROAD_TRANSITION, INT}},
{"OffroadMode", {CLEAR_ON_MANAGER_START, BOOL}},
{"Offroad_TiciSupport", {CLEAR_ON_MANAGER_START, JSON}},
@@ -191,6 +195,7 @@ inline static std::unordered_map<std::string, ParamKeyAttributes> keys = {
{"OnroadUploads", {PERSISTENT | BACKUP, BOOL, "1"}},
{"QuickBootToggle", {PERSISTENT | BACKUP, BOOL, "0"}},
{"QuietMode", {PERSISTENT | BACKUP, BOOL, "0"}},
{"RadarTracks", {PERSISTENT | BACKUP, INT, "0"}},
{"RainbowMode", {PERSISTENT | BACKUP, BOOL, "0"}},
{"RoadEdgeLaneChangeEnabled", {PERSISTENT | BACKUP, BOOL, "0"}},
{"RocketFuel", {PERSISTENT | BACKUP, BOOL, "0"}},
@@ -232,6 +237,11 @@ inline static std::unordered_map<std::string, ParamKeyAttributes> keys = {
{"SunnylinkDongleId", {PERSISTENT, STRING}},
{"SunnylinkdPid", {PERSISTENT, INT}},
{"SunnylinkEnabled", {PERSISTENT, BOOL, "1"}},
{"SunnylinkLocalConnectPhoneRequest", {CLEAR_ON_MANAGER_START | DONT_LOG, JSON}},
{"SunnylinkLocalConnectPhoneWindow", {CLEAR_ON_MANAGER_START | DONT_LOG, JSON}},
{"SunnylinkLocalBleGrants", {PERSISTENT | DONT_LOG, JSON}},
{"SunnylinkLocalBleKey", {PERSISTENT | DONT_LOG, BYTES}},
{"SunnylinkLocalBluetoothStatus", {CLEAR_ON_MANAGER_START | DONT_LOG, JSON}},
{"SunnylinkTempFault", {CLEAR_ON_MANAGER_START | CLEAR_ON_OFFROAD_TRANSITION, BOOL, "0"}},
// Backup Manager params
@@ -239,7 +249,7 @@ inline static std::unordered_map<std::string, ParamKeyAttributes> keys = {
{"BackupManager_RestoreVersion", {PERSISTENT, STRING}},
// sunnypilot car specific params
{"HyundaiLongitudinalTuning", {PERSISTENT | BACKUP, INT, "0"}},
{"HyundaiLongitudinalTuning", {PERSISTENT | BACKUP, BOOL, "0"}},
{"SubaruStopAndGo", {PERSISTENT | BACKUP, BOOL, "0"}},
{"SubaruStopAndGoManualParkingBrake", {PERSISTENT | BACKUP, BOOL, "0"}},
{"TeslaCoopSteering", {PERSISTENT | BACKUP, BOOL, "0"}},
+2
View File
@@ -37,6 +37,8 @@ SP_BRANCH_MIGRATIONS = {
("tizi", "release3-staging"): "release-tizi-staging",
("mici", "release3"): "release-mici",
("mici", "release3-staging"): "release-mici-staging",
("tici", "hkg-angle-steering-2025"): "hkg-angle-steering-2025-tici",
("tici", "hkg-angle-steering-2025-prebuilt"): "hkg-angle-steering-2025-tici-prebuilt"
}
BUILD_METADATA_FILENAME = "build.json"
+17
View File
@@ -179,6 +179,8 @@ class Car:
self.is_metric = self.params.get_bool("IsMetric")
self.initial_cruise_speed = self.params.get("InitialCruiseSpeedKph", return_default=True)
self.radar_tracks = int(self.params.get("RadarTracks", return_default=True))
self._applied_radar_tracks = getattr(self.RI, "radar_mode", self.radar_tracks)
# card is driven by can recv, expected at 100Hz
self.rk = Ratekeeper(100, print_delay_threshold=None)
@@ -193,6 +195,8 @@ class Car:
CS, CS_SP = self.CI.update(can_list)
CS_SP = convert_to_capnp(CS_SP)
self._update_radar_tracks()
# Update radar tracks from CAN
RD: structs.RadarDataT | None = self.RI.update(can_list)
@@ -219,6 +223,18 @@ class Car:
return CS, CS_SP, RD
def _update_radar_tracks(self) -> None:
if self.CP.brand != "hyundai" or self.radar_tracks == self._applied_radar_tracks:
return
if self.RI.set_radar_mode(self.radar_tracks):
self.CP_SP_capnp = convert_to_capnp(self.CP_SP)
cp_sp_bytes = self.CP_SP_capnp.to_bytes()
self.params.put("CarParamsSP", cp_sp_bytes)
self.params.put("CarParamsSPCache", cp_sp_bytes)
self.params.put("CarParamsSPPersistent", cp_sp_bytes)
self._applied_radar_tracks = self.radar_tracks
def state_publish(self, CS: car.CarState, CS_SP: custom.CarStateSP, RD: structs.RadarDataT | None):
"""carState and carParams publish loop"""
@@ -297,6 +313,7 @@ class Car:
while not evt.is_set():
self.is_metric = self.params.get_bool("IsMetric")
self.initial_cruise_speed = self.params.get("InitialCruiseSpeedKph", return_default=True)
self.radar_tracks = int(self.params.get("RadarTracks", return_default=True))
# sunnypilot
self.v_cruise_helper.read_custom_set_speed_params()
@@ -28,6 +28,8 @@ class DesireHelper:
self.alc = AutoLaneChangeController(self)
self.lane_turn_controller = LaneTurnController(self)
self.lane_turn_direction = TurnDirection.none
self.turn_frames = 0
self.turn_repulse = 98
@staticmethod
def get_lane_change_direction(CS):
@@ -95,8 +97,10 @@ class DesireHelper:
self.prev_one_blinker = one_blinker and lateral_active
if self.lane_turn_direction != TurnDirection.none:
self.desire = TURN_DESIRES[self.lane_turn_direction]
self.turn_frames += 1
self.desire = TURN_DESIRES[self.lane_turn_direction] if self.turn_frames % self.turn_repulse else log.Desire.none
else:
self.turn_frames = 0
self.desire = log.Desire.none
if self.lane_change_state == LaneChangeState.laneChangeStarting:
if self.lane_change_direction == LaneChangeDirection.left:
+14 -2
View File
@@ -26,6 +26,8 @@ SPEED, ACCEL = 0, 1 # Kalman filter states enum
# stationary qualification parameters
V_EGO_STATIONARY = 4. # no stationary object flag below this speed
DBC_MOTION_STATIONARY = 1
DBC_MOTION_MOVING = 2
RADAR_TO_CAMERA = 1.52 # RADAR is ~ 1.5m ahead from center of mesh frame
@@ -191,8 +193,14 @@ def get_custom_yrel(CP: structs.CarParams, CP_SP: structs.CarParamsSP, lead_dict
return lead_dict
def radar_point_eligible_for_fusion(CP: structs.CarParams, CP_SP: structs.CarParamsSP,
point: car.RadarData.RadarPoint) -> bool:
use_dbc_motion = CP.brand == "hyundai" and CP_SP.flags & HyundaiFlagsSP.RADAR_FULL_RADAR
return not use_dbc_motion or point.motionState in (DBC_MOTION_STATIONARY, DBC_MOTION_MOVING)
class RadarD:
def __init__(self, CP: structs.CarParams, CP_SP: structs.CarParams, delay: float = 0.0):
def __init__(self, CP: structs.CarParams, CP_SP: structs.CarParamsSP, delay: float = 0.0):
self.CP = CP
self.CP_SP = CP_SP
@@ -218,7 +226,11 @@ class RadarD:
self.v_ego_hist.append(self.v_ego)
self.last_v_ego_frame = sm.recv_frame['carState']
ar_pts = {pt.trackId: [pt.dRel, pt.yRel, pt.vRel] for pt in rr.points}
ar_pts = {
pt.trackId: [pt.dRel, pt.yRel, pt.vRel]
for pt in rr.points
if radar_point_eligible_for_fusion(self.CP, self.CP_SP, pt)
}
# *** remove missing points from meta data ***
for ids in list(self.tracks.keys()):
@@ -1,3 +1,3 @@
version https://git-lfs.github.com/spec/v1
oid sha256:65a08adc31d5c456219687d99b7bf5e44d61dae2d49ea67850e76105c7248cce
size 60918562
oid sha256:416c99bbd5563b01518be6de91b856986f66ffa03451ea9c451736dcc99896fd
size 83976077
@@ -100,7 +100,24 @@ class TogglesLayout(Widget):
icon="speed_limit.png"
)
self._radar_tracks_setting = None
self._toggles = {}
if gui_app.sunnypilot_ui():
self._radar_tracks_setting = multiple_button_item(
lambda: tr("Radar Tracks"),
"",
buttons=[lambda: tr("Off"), lambda: tr("Lead Only"), lambda: tr("Full Radar")],
button_width=250,
callback=self._set_radar_tracks,
selected_index=self._params.get("RadarTracks", return_default=True),
)
self._toggles["RadarTracks"] = self._radar_tracks_setting
self._toggle_defs["DrawRadarTracks"] = (
lambda: tr("Draw Radar Tracks"),
tr_noop("Show radar tracks on the driving screen. Disabling this does not disable radar processing."),
"",
False,
)
self._initial_cruise_speed = ListItem(
title=lambda: tr("Initial Max Speed"),
description=lambda: tr("Max speed when engaging openpilot. If you are already driving faster, your current speed is used. " +
@@ -169,6 +186,8 @@ class TogglesLayout(Widget):
# refresh toggles from params to mirror external changes
for param in self._toggle_defs:
self._toggles[param].action_item.set_state(self._params.get_bool(param))
if self._radar_tracks_setting is not None:
self._radar_tracks_setting.action_item.set_selected_button(self._params.get("RadarTracks", return_default=True))
# these toggles need restart, block while engaged
for toggle_def in self._toggle_defs:
@@ -188,3 +207,6 @@ class TogglesLayout(Widget):
def _set_longitudinal_personality(self, button_index: int):
self._params.put("LongitudinalPersonality", button_index, block=True)
def _set_radar_tracks(self, button_index: int):
self._params.put("RadarTracks", button_index, block=True)
@@ -101,6 +101,8 @@ class Sidebar(Widget, SidebarSP):
self._draw_buttons(rect)
self._draw_network_indicator(rect)
if gui_app.sunnypilot_ui():
SidebarSP._draw_bluetooth_indicator(self, rect)
self._draw_metrics(rect)
def _update_state(self):
+34 -9
View File
@@ -14,6 +14,7 @@ from openpilot.system.ui.lib.application import gui_app
if gui_app.sunnypilot_ui():
from openpilot.selfdrive.ui.sunnypilot.mici.layouts.settings import SettingsLayoutSP as SettingsLayout
from openpilot.selfdrive.ui.sunnypilot.mici.layouts.home import MiciHomeLayoutSP as MiciHomeLayout
from openpilot.selfdrive.ui.sunnypilot.mici.onroad.robotic import RoboticOnroadView
ONROAD_DELAY = 2.5 # seconds
@@ -34,24 +35,35 @@ class MiciMainLayout(Scroller):
self._alerts_layout = MiciOffroadAlerts()
self._settings_layout = SettingsLayout()
self._car_onroad_layout = AugmentedRoadView(bookmark_callback=self._on_bookmark_clicked)
self._robotic_onroad_layout = RoboticOnroadView(bookmark_callback=self._on_bookmark_clicked) if gui_app.sunnypilot_ui() else None
self._body_onroad_layout = BodyLayout()
self._prev_robotic_ui = bool(gui_app.sunnypilot_ui() and ui_state.mici_robotic_ui)
# Initialize widget rects
for widget in (self._home_layout, self._alerts_layout, self._settings_layout,
self._car_onroad_layout, self._body_onroad_layout):
all_widgets = [self._home_layout, self._alerts_layout, self._settings_layout,
self._car_onroad_layout, self._body_onroad_layout]
if self._robotic_onroad_layout is not None:
all_widgets.append(self._robotic_onroad_layout)
for widget in all_widgets:
# TODO: set parent rect and use it if never passed rect from render (like in Scroller)
widget.set_rect(rl.Rectangle(0, 0, gui_app.width, gui_app.height))
self._scroller.add_widgets([
scroller_widgets = [
self._alerts_layout,
self._home_layout,
self._car_onroad_layout,
self._body_onroad_layout,
])
]
if self._robotic_onroad_layout is not None:
scroller_widgets.append(self._robotic_onroad_layout)
scroller_widgets.append(self._body_onroad_layout)
self._scroller.add_widgets(scroller_widgets)
self._scroller.set_reset_scroll_at_show(False)
# Disable scrolling when onroad is interacting with bookmark
self._scroller.set_scrolling_enabled(lambda: not self._car_onroad_layout.is_swiping_left())
self._scroller.set_scrolling_enabled(
lambda: not (self._car_onroad_layout.is_swiping_left() or
(self._robotic_onroad_layout is not None and self._robotic_onroad_layout.is_swiping_left()))
)
# Set callbacks
self._setup_callbacks()
@@ -70,7 +82,11 @@ class MiciMainLayout(Scroller):
@property
def _onroad_layout(self) -> Widget:
# For scroll_to
return self._body_onroad_layout if ui_state.is_body else self._car_onroad_layout
if ui_state.is_body:
return self._body_onroad_layout
if self._robotic_onroad_layout is not None and ui_state.mici_robotic_ui:
return self._robotic_onroad_layout
return self._car_onroad_layout
def _setup_callbacks(self):
self._alerts_layout.set_enabled(lambda: self.enabled)
@@ -81,7 +97,10 @@ class MiciMainLayout(Scroller):
alert_count_callback=self._alerts_layout.active_alerts,
alert_icon_callback=self._alerts_layout.highest_severity_icon,
)
for layout in (self._car_onroad_layout, self._body_onroad_layout):
onroad_layouts = [self._car_onroad_layout, self._body_onroad_layout]
if self._robotic_onroad_layout is not None:
onroad_layouts.append(self._robotic_onroad_layout)
for layout in onroad_layouts:
layout.set_click_callback(lambda: self._scroll_to(self._home_layout))
device.add_interactive_timeout_callback(self._on_interactive_timeout)
@@ -95,6 +114,9 @@ class MiciMainLayout(Scroller):
super()._update_state()
# TODO: Hack to run alert updates while not in view. Add a nav stack tick?
self._alerts_layout._update_state()
if self._robotic_onroad_layout is not None and ui_state.mici_robotic_ui != self._prev_robotic_ui:
self._prev_robotic_ui = ui_state.mici_robotic_ui
self._on_body_changed()
def _render(self, _):
if not self._setup:
@@ -153,5 +175,8 @@ class MiciMainLayout(Scroller):
self._pm.send(service, msg)
def _on_body_changed(self):
self._car_onroad_layout.set_visible(not ui_state.is_body)
use_robotic = self._robotic_onroad_layout is not None and ui_state.mici_robotic_ui
self._car_onroad_layout.set_visible(not ui_state.is_body and not use_robotic)
if self._robotic_onroad_layout is not None:
self._robotic_onroad_layout.set_visible(not ui_state.is_body and use_robotic)
self._body_onroad_layout.set_visible(bool(ui_state.is_body))
@@ -20,9 +20,9 @@ class SettingsLayout(NavScroller):
super().__init__()
self._params = Params()
toggles_panel = TogglesLayoutMici()
self._toggles_panel = TogglesLayoutMici()
toggles_btn = SettingsBigButton("toggles", "", gui_app.texture("icons_mici/settings.png", 64, 64))
toggles_btn.set_click_callback(lambda: gui_app.push_widget(toggles_panel))
toggles_btn.set_click_callback(lambda: gui_app.push_widget(self._toggles_panel))
network_panel = NetworkLayoutMici()
network_btn = SettingsBigButton("network", "", gui_app.texture("icons_mici/settings/network/wifi_strength_full.png", 76, 56))
@@ -36,9 +36,19 @@ class TogglesLayoutMici(NavScroller):
enable_openpilot = BigParamControl("enable sunnypilot", "OpenpilotEnabledToggle", toggle_callback=restart_needed_callback,
description="Enable to use sunnypilot driver assistance.\n" +
"Disable to use your car's stock driver assistance.")
radar_tracks = BigMultiParamToggle("radar tracks", "RadarTracks", ["off", "lead only", "full radar"])
draw_radar_tracks = BigParamControl("draw radar tracks", "DrawRadarTracks")
robotic_ui_toggle = BigParamControl(
"robotic companion UI",
"MiciRoboticUI",
description="Replace the onroad camera view with an expressive EMO-inspired robotic face and robotic alert voices.",
)
self._radar_tracks_toggle = radar_tracks
self._scroller.add_widgets([
robotic_ui_toggle,
radar_tracks,
draw_radar_tracks,
self._personality_toggle,
self._initial_cruise_speed,
is_metric_toggle,
@@ -51,6 +61,8 @@ class TogglesLayoutMici(NavScroller):
# Toggle lists
self._refresh_toggles = (
("MiciRoboticUI", robotic_ui_toggle),
("DrawRadarTracks", draw_radar_tracks),
("IsMetric", is_metric_toggle),
("IsLdwEnabled", ldw_toggle),
("AlwaysOnDM", always_on_dm_toggle),
@@ -96,3 +108,4 @@ class TogglesLayoutMici(NavScroller):
# Refresh toggles from params to mirror external changes
for key, item in self._refresh_toggles:
item.set_checked(ui_state.params.get_bool(key))
self._radar_tracks_toggle._load_value()
@@ -15,6 +15,7 @@ from openpilot.system.ui.lib.shader_polygon import draw_polygon, Gradient
from openpilot.system.ui.widgets import Widget
from openpilot.selfdrive.ui.sunnypilot.mici.onroad.model_renderer import LANE_LINE_COLORS_SP, ModelRendererSP
from openpilot.selfdrive.ui.sunnypilot.onroad.radar_tracks import draw_radar_lead_connectors, radar_lead_track_colors
CLIP_MARGIN = 500
MIN_DRAW_DISTANCE = 10.0
@@ -46,6 +47,9 @@ class ModelPoints:
class LeadVehicle:
def __init__(self):
self.bar = np.empty((0, 2), dtype=np.float32)
self.position: tuple[float, float] | None = None
self.radar_track_id: int = -1
self.radar: bool = False
self.d_filter = FirstOrderFilter(0.0, 0.2, 1 / gui_app.target_fps, initialized=False)
self.y_filter = FirstOrderFilter(0.0, 0.2, 1 / gui_app.target_fps, initialized=False)
self.fade_filter = FirstOrderFilter(0.0, 0.1, 1 / gui_app.target_fps)
@@ -126,7 +130,8 @@ class ModelRenderer(Widget, ModelRendererSP):
# Update model data when needed
model_updated = sm.updated['modelV2']
if model_updated or sm.updated['radarState'] or self._transform_dirty:
transform_updated = self._transform_dirty
if model_updated or sm.updated['radarState'] or transform_updated:
if model_updated:
self._update_raw_points(model)
@@ -143,8 +148,33 @@ class ModelRenderer(Widget, ModelRendererSP):
self._draw_path()
self.blendful.draw(self._rect)
radar_matched_positions = {}
radar_highlighted_tracks = {}
if ui_state.draw_radar_tracks and sm.valid['radarTracks'] and sm.recv_frame['radarTracks'] >= ui_state.started_frame:
if (sm.updated['radarTracks'] or sm.updated['extrinsicsCalibration'] or transform_updated or
not self.radar_tracks.projection_initialized):
self.radar_tracks.update_radar_tracks(
sm['radarTracks'], self._map_to_screen, self._path_offset_z,
)
radar_highlighted_tracks = radar_lead_track_colors(radar_state) if render_lead_indicator else {}
radar_matched_positions = self.radar_tracks.draw_cached_radar_tracks(
screen_offset=(self._rect.x, self._rect.y),
highlighted_tracks=radar_highlighted_tracks,
)
else:
self.radar_tracks.clear_projection()
if render_lead_indicator:
self._update_leads(sm)
plan = sm['longitudinalPlan']
if plan.longitudinalPlanSource != log.LongitudinalPlan.LongitudinalPlanSource.e2e:
for lead_vehicle, lead in zip(self._lead_vehicles, (radar_state.leadOne, radar_state.leadTwo), strict=True):
lead_vehicle.radar_track_id = int(lead.radarTrackId)
lead_vehicle.radar = lead.radar
draw_radar_lead_connectors(
self._lead_vehicles, radar_matched_positions, radar_highlighted_tracks,
screen_offset=(self._rect.x, self._rect.y),
)
self._draw_lead_indicator()
else:
self._lead_vehicles = [LeadVehicle(), LeadVehicle()]
@@ -188,6 +218,7 @@ class ModelRenderer(Widget, ModelRendererSP):
lead.fade_filter.update(opacity if visible else 0.0)
if visible:
lead.bar = self._get_lead_bar(lane, lead.d_filter.update(d_rel), lead.y_filter.update(y_rel))
lead.position = tuple(lead.bar.mean(axis=0))
def _get_lead_bar(self, lane, d_rel, y_rel):
# bar on the road behind the lead, following the lane
@@ -341,6 +372,21 @@ class ModelRenderer(Widget, ModelRendererSP):
for lead in self._lead_vehicles:
draw_polygon(self._rect, lead.bar + offset, rl.Color(255, 255, 255, int(255 * lead.fade_filter.x)))
def _map_to_screen(self, in_x, in_y, in_z):
input_pt = np.array([in_x, in_y, in_z])
pt = self._car_space_transform @ input_pt
if abs(pt[2]) < 1e-6:
return None
x, y = pt[0] / pt[2], pt[1] / pt[2]
clip = self._clip_region
if not (clip.x <= x + self._rect.x <= clip.x + clip.width and clip.y <= y + self._rect.y <= clip.y + clip.height):
return None
return (x, y)
@staticmethod
def _get_path_length_idx(pos_x_array: np.ndarray, path_height: float) -> int:
"""Get the index corresponding to the given path height"""
@@ -0,0 +1,270 @@
"""Tests for MICI Robotic Companion onroad UI mood engine and telemetry helpers."""
import random
from openpilot.cereal import log
from openpilot.common.test import OpenpilotTestCase
from openpilot.selfdrive.ui.mici.onroad.alert_renderer import Alert
from openpilot.selfdrive.ui.sunnypilot.mici.onroad.robotic.expressions import (
DrivingSnapshot,
EyeGlyph,
MouthGlyph,
PALETTE,
RoboticMood,
RoboticMoodEngine,
STANDSTILL_POUT_DELAY,
STANDSTILL_SLEEPY_DELAY,
display_speed_and_set_speed,
)
from openpilot.selfdrive.ui.ui_state import UIStatus
AlertStatus = log.SelfdriveState.AlertStatus
class TestRoboticMoodEngine(OpenpilotTestCase):
def _engine(self) -> RoboticMoodEngine:
return RoboticMoodEngine(rng=random.Random(42))
def test_engaged_happy_then_speed_then_cruising(self):
engine = self._engine()
# Initially disengaged
snap = DrivingSnapshot(started=True, engaged=False, status=UIStatus.DISENGAGED, v_ego=20.0)
target = engine.update(snap, now=10.0)
assert engine.mood == RoboticMood.IDLE_CURIOUS
assert target.color == PALETTE["disengaged"]
# Engage triggers HAPPY_ENGAGE crescent eyes
snap_eng = DrivingSnapshot(started=True, engaged=True, status=UIStatus.ENGAGED, v_ego=25.0, set_speed_kph=100.0)
target = engine.update(snap_eng, now=11.0)
assert engine.mood == RoboticMood.HAPPY_ENGAGE
assert target.glyph == EyeGlyph.CRESCENT
assert target.color == PALETTE["engaged"]
# After happy hold, briefly shows speed confirmation
engine.update(snap_eng, now=12.2)
assert engine.mood == RoboticMood.SPEED_DISPLAY
assert engine.showing_speed is True
# After speed confirm expires, settles into CRUISING_HAPPY
target = engine.update(snap_eng, now=15.0)
assert engine.mood == RoboticMood.CRUISING_HAPPY
assert engine.showing_speed is False
assert target.color == PALETTE["engaged"]
def test_critical_alert_overrides_all_moods(self):
engine = self._engine()
engine.trigger_love(now=10.0)
engine.trigger_speed_peek(now=10.0)
alert = Alert("TAKE CONTROL IMMEDIATELY", "Steering Required", status=AlertStatus.critical)
snap = DrivingSnapshot(started=True, engaged=True, status=UIStatus.ENGAGED, alert=alert)
target = engine.update(snap, now=10.1)
assert engine.mood == RoboticMood.CRITICAL
assert target.glyph == EyeGlyph.LASER_ALERT
assert target.color == PALETTE["critical"]
assert engine.showing_speed is False
def test_distracted_driver_monitoring(self):
engine = self._engine()
snap = DrivingSnapshot(started=True, engaged=True, status=UIStatus.ENGAGED, dm_alert_level=1)
target = engine.update(snap, now=20.0)
assert engine.mood == RoboticMood.DISTRACTED
assert target.color == PALETTE["prompt"]
assert target.mouth == MouthGlyph.FROWN
def test_hard_decel_triggers_star_eyes(self):
engine = self._engine()
snap = DrivingSnapshot(started=True, engaged=True, status=UIStatus.ENGAGED, a_ego=-3.8)
target = engine.update(snap, now=30.0)
assert engine.mood == RoboticMood.STARTLED_STARS
assert target.glyph == EyeGlyph.STAR
assert target.mouth == MouthGlyph.SURPRISED
def test_lane_change_and_blind_spot(self):
engine = self._engine()
snap_lc = DrivingSnapshot(started=True, engaged=True, status=UIStatus.ENGAGED, pre_lane_change_left=True)
target = engine.update(snap_lc, now=40.0)
assert engine.mood == RoboticMood.LANE_CHANGE
assert target.glyph == EyeGlyph.ARROW_LEFT
assert target.gaze_x < 0
snap_bsm = DrivingSnapshot(started=True, engaged=True, status=UIStatus.ENGAGED, right_blinker=True, right_blindspot=True)
target = engine.update(snap_bsm, now=41.0)
assert engine.mood == RoboticMood.BLIND_SPOT
assert target.gaze_x > 0
assert target.blind_spot_side == 1
def test_standstill_pout_and_sleepy_progression(self):
engine = self._engine()
snap = DrivingSnapshot(started=True, engaged=True, status=UIStatus.ENGAGED, standstill=True)
engine.update(snap, now=100.0)
# Past happy engage & speed confirm, still before pout
engine.update(snap, now=105.0)
assert engine.mood == RoboticMood.CRUISING_HAPPY
# Past pout threshold
target = engine.update(snap, now=100.0 + STANDSTILL_POUT_DELAY + 1.0)
assert engine.mood == RoboticMood.POUT_STANDSTILL
assert target.mouth == MouthGlyph.FROWN
# Past sleepy threshold
target = engine.update(snap, now=100.0 + STANDSTILL_SLEEPY_DELAY + 1.0)
assert engine.mood == RoboticMood.SLEEPY
assert target.top_lid >= 0.5
def test_set_speed_change_triggers_speed_display(self):
engine = self._engine()
snap1 = DrivingSnapshot(started=True, engaged=True, status=UIStatus.ENGAGED, v_ego=25.0, set_speed_kph=100.0)
engine.update(snap1, now=10.0)
engine.update(snap1, now=15.0)
assert engine.showing_speed is False
snap2 = DrivingSnapshot(started=True, engaged=True, status=UIStatus.ENGAGED, v_ego=25.0, set_speed_kph=110.0)
engine.update(snap2, now=16.0)
assert engine.mood == RoboticMood.SPEED_DISPLAY
assert engine.showing_speed is True
assert engine.speed_reason == "set_speed"
def test_mads_lat_only_warm_peach_palette(self):
engine = self._engine()
snap = DrivingSnapshot(started=True, engaged=True, status=UIStatus.LAT_ONLY, v_ego=18.0)
engine.update(snap, now=10.0)
target = engine.update(snap, now=15.0)
assert target.color == PALETTE["lat_only"]
def test_display_speed_conversion(self):
snap_mph = DrivingSnapshot(v_ego=26.8224, set_speed_kph=100.0, is_metric=False)
cur, set_s = display_speed_and_set_speed(snap_mph)
assert cur == 60
assert set_s == 62
snap_kph = DrivingSnapshot(v_ego=27.7778, set_speed_kph=100.0, is_metric=True)
cur, set_s = display_speed_and_set_speed(snap_kph)
assert cur == 100
assert set_s == 100
def test_sharp_accel_turn_signal_sharp_turn_and_continuous_motion(self):
engine = self._engine()
# Sharp acceleration triggers BOOST_ACCEL with speed lines
snap_boost = DrivingSnapshot(started=True, engaged=True, status=UIStatus.ENGAGED, v_ego=22.0, a_ego=2.8)
engine.update(snap_boost, now=10.0)
target = engine.update(snap_boost, now=14.0)
# Trigger fresh boost after engage hold expires
snap_boost2 = DrivingSnapshot(started=True, engaged=True, status=UIStatus.ENGAGED, v_ego=24.0, a_ego=2.9)
target = engine.update(snap_boost2, now=15.0)
assert engine.mood == RoboticMood.BOOST_ACCEL
assert target.glyph == EyeGlyph.SPARKLE_BOOST
assert target.show_speed_lines is True
# Turn indicator triggers TURN_SIGNAL with blinker side
snap_turn = DrivingSnapshot(started=True, engaged=False, status=UIStatus.DISENGAGED, v_ego=15.0, left_blinker=True)
target = engine.update(snap_turn, now=20.0)
assert engine.mood == RoboticMood.TURN_SIGNAL
assert target.blinker_side == -1
# Sharp turn triggers SHARP_TURN with centrifugal tilt
snap_sharp = DrivingSnapshot(started=True, engaged=False, status=UIStatus.DISENGAGED, v_ego=12.0, steering_angle_deg=55.0)
target = engine.update(snap_sharp, now=25.0)
assert engine.mood == RoboticMood.SHARP_TURN
assert abs(target.tilt_y) >= 10.0
# Bookmark wink triggers love with wink_right=True
engine.trigger_love(now=30.0, wink=True)
target = engine.update(DrivingSnapshot(started=True, engaged=False), now=30.2)
assert engine.mood == RoboticMood.BOOKMARK_LOVE
assert target.wink_right is True
assert target.show_hearts is True
# Continuous motion check: idle bounce_y & gaze_x are never frozen across frames
snap_idle = DrivingSnapshot(started=True, engaged=False, status=UIStatus.DISENGAGED, v_ego=0.0)
t1 = engine.update(snap_idle, now=40.0)
t2 = engine.update(snap_idle, now=40.5)
assert (t1.bounce_y != t2.bounce_y) or (t1.gaze_x != t2.gaze_x)
def test_music_analyzer_rejects_road_noise_and_speech_detects_music(self):
import numpy as np
from openpilot.selfdrive.ui.sunnypilot.mici.onroad.robotic.music_analyzer import (
DEFAULT_SAMPLE_RATE,
MusicAnalyzer,
MusicState,
)
sr = DEFAULT_SAMPLE_RATE
chunk_len = 800 # 50 ms @ 16 kHz
rng = np.random.default_rng(7)
# 1. Broadband cabin road/wind noise -> MUST be rejected
road_analyzer = MusicAnalyzer(sr)
for _ in range(90): # 4.5 s
noise = rng.normal(0.0, 0.08, size=chunk_len).astype(np.float32)
state = road_analyzer.process_samples(noise)
assert state.is_music is False, f"Road noise falsely triggered music (conf={state.confidence:.2f})"
# 2. Simulated human talking (irregular vocal-band bursts with speech pauses) -> MUST be rejected
speech_analyzer = MusicAnalyzer(sr)
t_total = np.arange(90 * chunk_len, dtype=np.float32) / sr
# Speech formants (550Hz + 1200Hz) modulated by irregular syllables & pauses
vocal = 0.09 * np.sin(2 * np.pi * 550 * t_total) + 0.06 * np.sin(2 * np.pi * 1250 * t_total)
for idx in range(90):
# Irregular talk/pause pattern (approx 45% active)
speaking = (idx % 11) in (0, 1, 2, 5, 6)
seg = vocal[idx * chunk_len:(idx + 1) * chunk_len] * (1.0 if speaking else 0.02)
seg = seg + rng.normal(0.0, 0.01, size=chunk_len).astype(np.float32)
state = speech_analyzer.process_samples(seg)
assert state.is_music is False, f"Talking falsely triggered music (conf={state.confidence:.2f})"
# 3. Simulated rhythmic harmonic music (120 BPM kick + chords + hi-hat) -> MUST be detected
music_analyzer = MusicAnalyzer(sr)
beat_period = 0.5 # 120 BPM
for idx in range(100): # 5.0 s
t = (idx * chunk_len + np.arange(chunk_len, dtype=np.float32)) / sr
beat_t = t % beat_period
kick = 0.22 * np.exp(-beat_t * 18.0) * np.sin(2 * np.pi * 95.0 * t)
chord = (
0.09 * np.sin(2 * np.pi * 261.6 * t)
+ 0.07 * np.sin(2 * np.pi * 329.6 * t)
+ 0.07 * np.sin(2 * np.pi * 392.0 * t)
)
hihat_t = (t + 0.25) % beat_period
hihat = 0.08 * np.exp(-hihat_t * 35.0) * np.sin(2 * np.pi * 5200.0 * t)
mix = (kick + chord + hihat).astype(np.float32)
state = music_analyzer.process_samples(mix)
assert state.is_music is True, f"Music was not detected (conf={state.confidence:.2f})"
assert max(state.bands) > 0.2
# 4. Mood engine enters MUSIC_GROOVE when cruising/idling, overridden immediately by alerts
engine = self._engine()
music_on = MusicState(is_music=True, confidence=0.85, beat_pulse=0.7, groove_phase=1.2, bpm=120.0, energy=0.7)
snap_cruise = DrivingSnapshot(started=True, engaged=True, status=UIStatus.ENGAGED, v_ego=25.0, music=music_on)
engine.update(snap_cruise, now=10.0)
engine.update(snap_cruise, now=15.0)
assert engine.mood == RoboticMood.MUSIC_GROOVE
# Alert overrides MUSIC_GROOVE immediately
snap_alert = DrivingSnapshot(
started=True, engaged=True, status=UIStatus.ENGAGED, v_ego=25.0, music=music_on,
alert=Alert("Pay Attention", "Eyes on road", status=AlertStatus.userPrompt),
)
engine.update(snap_alert, now=15.5)
assert engine.mood == RoboticMood.USER_PROMPT
def test_centrifugal_turn_squish_and_pitch_response(self):
engine = self._engine()
# Gentle left turn (yaw_rate > 0 -> pushed right: squish_force > 0)
snap_mild = DrivingSnapshot(started=True, engaged=True, status=UIStatus.ENGAGED, v_ego=15.0, yaw_rate=0.10, pitch_rad=0.05)
engine.update(snap_mild, now=10.0)
t_mild = engine.update(snap_mild, now=15.0)
assert t_mild.squish_force > 0.15
assert t_mild.pitch_offset_y > 0.0
# Fast left turn (high lateral G -> strongly squished right + surprised mouth)
snap_fast = DrivingSnapshot(started=True, engaged=True, status=UIStatus.ENGAGED, v_ego=24.0, yaw_rate=0.18, pitch_rate=-0.2)
t_fast = engine.update(snap_fast, now=16.0)
assert engine.mood == RoboticMood.SHARP_TURN
assert t_fast.squish_force > t_mild.squish_force
assert t_fast.squish_force > 0.65
assert t_fast.mouth == MouthGlyph.SURPRISED
# Fast right turn (yaw_rate < 0 -> pushed left: squish_force < 0)
snap_right = DrivingSnapshot(started=True, engaged=True, status=UIStatus.ENGAGED, v_ego=22.0, yaw_rate=-0.18)
t_right = engine.update(snap_right, now=17.0)
assert t_right.squish_force < -0.65
@@ -103,7 +103,7 @@ class AugmentedRoadView(CameraView, AugmentedRoadViewSP):
# Draw colored border based on driving state
self._draw_border(rect)
def _handle_mouse_press(self, _):
def _handle_mouse_press(self, mouse_pos):
if self._click_callback is not None:
self._click_callback()
@@ -11,6 +11,7 @@ from openpilot.system.ui.lib.shader_polygon import draw_polygon, Gradient
from openpilot.system.ui.widgets import Widget
from openpilot.selfdrive.ui.sunnypilot.onroad.model_renderer import ChevronMetrics, ModelRendererSP
from openpilot.selfdrive.ui.sunnypilot.onroad.radar_tracks import draw_radar_lead_connectors, radar_lead_track_colors
CLIP_MARGIN = 500
MIN_DRAW_DISTANCE = 10.0
@@ -35,6 +36,9 @@ class LeadVehicle:
glow: list[tuple[float, float]] = field(default_factory=list)
chevron: list[tuple[float, float]] = field(default_factory=list)
fill_alpha: int = 0
position: tuple[float, float] | None = None
radar_track_id: int = -1
radar: bool = False
class ModelRenderer(Widget, ChevronMetrics, ModelRendererSP):
@@ -107,7 +111,8 @@ class ModelRenderer(Widget, ChevronMetrics, ModelRendererSP):
# Update model data when needed
model_updated = sm.updated['modelV2']
if model_updated or sm.updated['radarState'] or self._transform_dirty:
transform_updated = self._transform_dirty
if model_updated or sm.updated['radarState'] or transform_updated:
if model_updated:
self._update_raw_points(model)
@@ -125,6 +130,21 @@ class ModelRenderer(Widget, ChevronMetrics, ModelRendererSP):
self._draw_path()
self.blendful.draw(self._rect)
if ui_state.draw_radar_tracks and sm.valid['radarTracks'] and sm.recv_frame['radarTracks'] >= ui_state.started_frame:
if (sm.updated['radarTracks'] or sm.updated['liveCalibration'] or transform_updated or
not self.radar_tracks.projection_initialized):
self.radar_tracks.update_radar_tracks(
sm['radarTracks'], self._map_to_screen, self._path_offset_z,
)
highlighted_tracks = radar_lead_track_colors(radar_state) if render_lead_indicator else {}
matched_positions = self.radar_tracks.draw_cached_radar_tracks(
highlighted_tracks=highlighted_tracks,
)
if render_lead_indicator:
draw_radar_lead_connectors(self._lead_vehicles, matched_positions, highlighted_tracks)
else:
self.radar_tracks.clear_projection()
if render_lead_indicator and radar_state:
self._draw_lead_indicator()
self.chevron_metrics.draw_lead_status(sm, radar_state, self._rect, self._lead_vehicles)
@@ -157,7 +177,11 @@ class ModelRenderer(Widget, ChevronMetrics, ModelRendererSP):
z = self._path.raw_points[idx, 2] if idx < len(self._path.raw_points) else 0.0
point = self._map_to_screen(d_rel, -y_rel + self._camera_offset, z + self._path_offset_z)
if point:
self._lead_vehicles[i] = self._update_lead_vehicle(d_rel, v_rel, point, self._rect)
lead_vehicle = self._update_lead_vehicle(d_rel, v_rel, point, self._rect)
lead_vehicle.position = lead_vehicle.chevron[1]
lead_vehicle.radar_track_id = int(lead_data.radarTrackId)
lead_vehicle.radar = lead_data.radar
self._lead_vehicles[i] = lead_vehicle
def _update_model(self, lead, path_x_array):
"""Update model visualization data based on model message"""
+30 -5
View File
@@ -15,6 +15,7 @@ from openpilot.system import micd
from openpilot.common.hardware import HARDWARE
from openpilot.sunnypilot.selfdrive.ui.quiet_mode import QuietMode
from openpilot.sunnypilot.selfdrive.ui.robotic_sounds import REACTIVE_CHIRP_IDS, RoboticSoundPack
SAMPLE_RATE = 48000
SAMPLE_BUFFER = 4096 # (approx 100ms)
@@ -73,6 +74,7 @@ def check_selfdrive_timeout_alert(sm):
class Soundd(QuietMode):
def __init__(self):
super().__init__()
self.robotic_sound_pack = RoboticSoundPack(self.params, SAMPLE_RATE)
self.load_sounds()
@@ -103,13 +105,22 @@ class Soundd(QuietMode):
length = wavefile.getnframes()
self.loaded_sounds[sound] = np.frombuffer(wavefile.readframes(length), dtype=np.int16).astype(np.float32) / (2**16/2)
self.robotic_sound_pack.load()
def load_param(self) -> None:
prev_frame = self._frame
super().load_param()
if self._frame != prev_frame and self._frame % 50 == 0:
if self.robotic_sound_pack.refresh_param():
self.current_sound_frame = 0
def get_sound_data(self, frames): # get "frames" worth of data from the current alert sound, looping when required
ret = np.zeros(frames, dtype=np.float32)
if self.should_play_sound(self.current_alert):
num_loops = sound_list[self.current_alert][1]
sound_data = self.loaded_sounds[self.current_alert]
num_loops = 1 if self.current_alert in REACTIVE_CHIRP_IDS else sound_list[self.current_alert][1]
sound_data = self.robotic_sound_pack.get_buffer(self.current_alert, self.loaded_sounds)
written_frames = 0
current_sound_frame = self.current_sound_frame % len(sound_data)
@@ -136,9 +147,17 @@ class Soundd(QuietMode):
data_out[:frames, 0] = self.get_sound_data(frames)
def update_alert(self, new_alert):
current_alert_played_once = self.current_alert == AudibleAlert.none or self.current_sound_frame >= len(self.loaded_sounds[self.current_alert])
current_alert_played_once = (
self.current_alert == AudibleAlert.none or
self.current_sound_frame >= len(self.robotic_sound_pack.get_buffer(self.current_alert, self.loaded_sounds))
)
# let looping sounds finish the current loop instead of cutting off mid tone
if new_alert == AudibleAlert.none and self.current_alert != AudibleAlert.none and sound_list[self.current_alert][1] is None:
if (
new_alert == AudibleAlert.none
and self.current_alert != AudibleAlert.none
and self.current_alert not in REACTIVE_CHIRP_IDS
and sound_list[self.current_alert][1] is None
):
if current_alert_played_once:
self.pending_stop = True
else:
@@ -164,6 +183,12 @@ class Soundd(QuietMode):
self.update_alert(AudibleAlert.none)
self.selfdrive_timeout_alert = False
# Trigger playful one-shot robotic chirps only when idle (never preempting safety alerts)
if self.robotic_sound_pack.enabled and self.current_alert == AudibleAlert.none:
chirp = self.robotic_sound_pack.detect_reactive_chirp(sm)
if chirp is not None:
self.update_alert(chirp)
def calculate_volume(self, weighted_db):
volume = ((weighted_db - AMBIENT_DB) / DB_SCALE) * (MAX_VOLUME - MIN_VOLUME) + MIN_VOLUME
return math.pow(VOLUME_BASE, (np.clip(volume, MIN_VOLUME, MAX_VOLUME) - 1))
@@ -180,7 +205,7 @@ class Soundd(QuietMode):
import sounddevice as sd
micd.patch_sounddevice(sd)
sm = messaging.SubMaster(['selfdriveState', 'selfdriveStateSP', 'soundPressure'])
sm = messaging.SubMaster(['selfdriveState', 'selfdriveStateSP', 'soundPressure', 'carState', 'controlsState', 'userBookmark', 'bookmarkButton'])
with self.get_stream(sd) as stream:
rk = Ratekeeper(20)
@@ -0,0 +1,91 @@
"""
Copyright (c) 2021-, sunnypilot, and a number of other contributors.
This file is part of sunnypilot and is licensed under the MIT License.
See the LICENSE.md file in the root directory for more details.
"""
import time
from openpilot.common.params import Params
from openpilot.selfdrive.ui.sunnypilot.layouts.settings.connect_phone import ConnectPhoneLayout
from openpilot.sunnypilot.system.ble import grants
from openpilot.sunnypilot.system.connect_phone import write_request
from openpilot.system.ui.lib.application import FontWeight, gui_app
from openpilot.system.ui.lib.multilang import tr
from openpilot.system.ui.lib.text_measure import measure_text_cached
from openpilot.system.ui.sunnypilot.widgets.list_view import button_item_sp, simple_button_item_sp, toggle_item_sp
from openpilot.system.ui.widgets import DialogResult, Widget
from openpilot.system.ui.widgets.confirm_dialog import ConfirmDialog
from openpilot.system.ui.widgets.list_view import ITEM_TEXT_FONT_SIZE
from openpilot.system.ui.widgets.scroller_tici import Scroller
POLL_INTERVAL = 1.0
NAME_MAX_WIDTH = 1000 # px at the list font: leaves room for REMOVE in the settings panel
def _fit_name(name: str) -> str:
# a phone name is up to 80 bytes; list titles are single line and never elided by stock
font = gui_app.font(FontWeight.NORMAL)
if measure_text_cached(font, name, ITEM_TEXT_FONT_SIZE).x <= NAME_MAX_WIDTH:
return name
while name and measure_text_cached(font, name + "...", ITEM_TEXT_FONT_SIZE).x > NAME_MAX_WIDTH:
name = name[:-1]
return name.rstrip() + "..."
class BluetoothLayout(Widget):
def __init__(self):
super().__init__()
self._params = Params()
self._bluetooth_toggle = toggle_item_sp(
title=lambda: tr("Bluetooth"),
description=lambda: tr("Allow phones to connect to this device over Bluetooth."),
param="BluetoothAllowed",
)
self._connect_phone_button = simple_button_item_sp(
button_text=lambda: tr("Connect phone"),
callback=lambda: gui_app.push_widget(ConnectPhoneLayout()),
enabled=lambda: self._bluetooth_toggle.action_item.get_state(),
)
self._phone_items = []
self._grants: list[dict] | None = None
self._last_poll = float("-inf")
self._scroller = Scroller([self._bluetooth_toggle, self._connect_phone_button], line_separator=True, spacing=0)
def _bluetooth_on(self) -> bool:
return self._bluetooth_toggle.action_item.get_state()
def _update_state(self):
now = time.monotonic()
if now - self._last_poll < POLL_INTERVAL:
return
self._last_poll = now
phones = grants.load(self._params)
if phones != self._grants:
self._grants = phones
self._rebuild_phone_items()
def _rebuild_phone_items(self):
for item in self._phone_items:
self._scroller._items.remove(item)
self._phone_items = [self._phone_item(phone) for phone in self._grants or []]
for item in self._phone_items:
item.set_visible(self._bluetooth_on)
self._scroller.add_widget(item)
def _phone_item(self, phone: dict):
spki, name = phone["spki"], _fit_name(phone["name"])
return button_item_sp(title=name, button_text=lambda: tr("REMOVE"), callback=lambda: self._remove(spki, name))
def _remove(self, spki: str, name: str):
def done(result: DialogResult):
if result == DialogResult.CONFIRM:
write_request(self._params, "remove", phone=spki)
gui_app.push_widget(ConfirmDialog(tr("Remove \"{}\"?").format(name), tr("Remove"), tr("Cancel"), callback=done))
def _render(self, rect):
self._scroller.render(rect)
@@ -0,0 +1,205 @@
"""
Copyright (c) 2021-, sunnypilot, and a number of other contributors.
This file is part of sunnypilot and is licensed under the MIT License.
See the LICENSE.md file in the root directory for more details.
"""
import math
import time
import pyray as rl
from openpilot.common.params import Params
from openpilot.selfdrive.ui.ui_state import device
from openpilot.selfdrive.ui.widgets.pairing_dialog import PairingDialog
from openpilot.sunnypilot.system.connect_phone import WINDOW_SECONDS, display_name, format_code, read_window, write_request
from openpilot.system.ui.lib.application import FontWeight, gui_app
from openpilot.system.ui.lib.multilang import tr, tr_noop
from openpilot.system.ui.lib.text_measure import measure_text_cached
from openpilot.system.ui.lib.wrap_text import wrap_text
from openpilot.system.ui.widgets import DialogResult
from openpilot.system.ui.widgets.confirm_dialog import ConfirmDialog
POLL_INTERVAL = 0.25
START_TIMEOUT = 15
STALE_SECONDS = 3
CLOSE_REASON_MESSAGES = {
"granted": tr_noop("Phone connected."),
"denied": tr_noop("Phone not connected."),
"no_answer": tr_noop("Phone not connected: Allow was not tapped in time."),
"phone_left": tr_noop("Phone not connected: the phone disconnected."),
"wrong_codes": tr_noop("Phone not connected: too many wrong codes. Try again."),
"limit": tr_noop("Phone not connected: 8 phones are already connected. Remove one first."),
"timeout": tr_noop("The connect window timed out. Try again."),
"bluetooth_off": tr_noop("Bluetooth is off. Turn Bluetooth on to connect a phone."),
"no_key": tr_noop("The device key is unavailable. Reboot and try again."),
}
class ConnectPhoneLayout(PairingDialog):
def __init__(self):
super().__init__()
self._params = Params()
self._name = display_name(self._params)
self._close_btn.set_click_callback(self._close_screen)
self._started = False
self._closed = False
self._seq = 0
self._opened_at = 0.0
self._matched_at = 0.0
self._window: dict | None = None
self._last_poll = float("-inf")
self._qr_source = ""
self._check_dialog: ConfirmDialog | None = None
self._check_shown_for: float | None = None
def show_event(self):
super().show_event()
device.set_override_interactive_timeout(WINDOW_SECONDS + 10)
# a tick, not _update_state: it has to keep polling while the Allow dialog is on top
gui_app.add_nav_stack_tick(self._tick)
if not self._started:
self._started = True
self._seq = write_request(self._params, "open")
self._opened_at = time.monotonic()
def hide_event(self):
super().hide_event()
gui_app.remove_nav_stack_tick(self._tick)
device.set_override_interactive_timeout(None)
if self._seq and not self._closed:
write_request(self._params, "cancel")
self._closed = True
def _update_state(self):
pass # stock closes itself once the device is paired to comma connect
def _tick(self):
if self._closed:
return
now = time.monotonic()
if now - self._last_poll >= POLL_INTERVAL:
self._last_poll = now
window = read_window(self._params)
if window and window.get("seq") == self._seq:
self._window = window
self._matched_at = now
if window.get("state") == "closed":
self._on_closed(window.get("reason", ""))
return
self._sync_check_dialog(window.get("prompt") or {})
if self._window is not None and self._window.get("state") == "open":
if not self._window.get("held") and now >= self._window.get("deadline", 0.0):
self._on_closed("timeout")
elif self._matched_at and now - self._matched_at > STALE_SECONDS:
self._finish(None)
elif now - self._opened_at > START_TIMEOUT:
write_request(self._params, "cancel")
self._finish(tr("Bluetooth did not start"))
def _sync_check_dialog(self, prompt: dict):
if prompt.get("step") == "allow" and self._check_shown_for != prompt.get("until"):
self._check_shown_for = prompt.get("until")
text = tr("Code {}\nIs the same code on your phone?").format(prompt.get("check", ""))
self._check_dialog = ConfirmDialog(text, tr("Allow"), tr("Deny"), callback=self._answer)
gui_app.push_widget(self._check_dialog)
elif prompt.get("step") != "allow" and self._check_dialog is not None:
gui_app.pop_widgets_to(self, instant=True)
self._check_dialog = None
def _answer(self, result: DialogResult):
self._check_dialog = None
write_request(self._params, "allow" if result == DialogResult.CONFIRM else "deny")
def _on_closed(self, reason: str):
message = CLOSE_REASON_MESSAGES.get(reason)
self._finish(tr(message) if message else None)
def _finish(self, message: str | None):
self._closed = True
gui_app.pop_widgets_to(self, instant=True)
self._close_screen()
if message:
gui_app.push_widget(ConfirmDialog(message, tr("OK"), cancel_text=""))
def _close_screen(self):
if gui_app.get_active_widget() is self:
gui_app.pop_widget()
def _get_pairing_url(self) -> str:
return self._qr_source
def _check_qr_refresh(self):
qr = (self._window or {}).get("qr", "") if self._is_open() else ""
if qr and qr != self._qr_source:
self._qr_source = qr
self._generate_qr_code()
def _is_open(self) -> bool:
return self._window is not None and self._window.get("state") == "open" and not self._window.get("held")
def _render(self, rect: rl.Rectangle) -> int:
# copied from PairingDialog._render: stock hardcodes its title and steps there
rl.clear_background(rl.Color(224, 224, 224, 255))
self._check_qr_refresh()
margin = 70
content_rect = rl.Rectangle(rect.x + margin, rect.y + margin, rect.width - 2 * margin, rect.height - 2 * margin)
y = content_rect.y
close_size = 80
pad = 20
self._close_btn.render(rl.Rectangle(content_rect.x - pad, y - pad, close_size + pad * 2, close_size + pad * 2))
y += close_size + 40
title_font = gui_app.font(FontWeight.NORMAL)
left_width = int(content_rect.width * 0.5 - 15)
title_wrapped = wrap_text(title_font, tr("Connect a phone to {}").format(self._name), 75, left_width)
rl.draw_text_ex(title_font, "\n".join(title_wrapped), rl.Vector2(content_rect.x, y), 75, 0.0, rl.BLACK)
y += len(title_wrapped) * 75 + 60
remaining_height = content_rect.height - (y - content_rect.y)
right_width = content_rect.width // 2 - 20
self._render_instructions(rl.Rectangle(content_rect.x, y, left_width, remaining_height))
qr_size = min(right_width, content_rect.height) - 40
qr_rect = rl.Rectangle(content_rect.x + left_width + 40 + (right_width - qr_size) // 2, content_rect.y, qr_size, qr_size)
if self._is_open():
self._render_qr_code(qr_rect)
else:
text = tr("Connecting phone") if self._window is not None and self._window.get("held") else tr("Starting Bluetooth")
rl.draw_rectangle_rounded(qr_rect, 0.1, 20, rl.Color(240, 240, 240, 255))
font = gui_app.font(FontWeight.BOLD)
size = measure_text_cached(font, text, 47)
rl.draw_text_ex(font, text, rl.Vector2(qr_rect.x + (qr_rect.width - size.x) / 2, qr_rect.y + (qr_rect.height - size.y) / 2), 47, 0,
rl.BLACK)
return -1
def _render_instructions(self, rect: rl.Rectangle) -> None:
window = self._window if self._is_open() else None
instructions = [
tr("Open the sunnylink app and tap Connect phone"),
tr("Scan the QR code on the right, or type {}").format(format_code(int(window["code"]))) if window else tr("Scan the QR code on the right"),
tr("Check that both screens show the same code, then tap Allow"),
]
font = gui_app.font(FontWeight.BOLD)
y = rect.y
for i, text in enumerate(instructions):
circle_radius = 25
circle_x = rect.x + circle_radius + 15
text_x = rect.x + circle_radius * 2 + 40
wrapped = wrap_text(font, text, 47, int(rect.width - (circle_radius * 2 + 40)))
text_height = len(wrapped) * 47
circle_y = y + text_height // 2
rl.draw_circle(int(circle_x), int(circle_y), circle_radius, rl.Color(70, 70, 70, 255))
number = str(i + 1)
number_size = measure_text_cached(font, number, 30)
rl.draw_text_ex(font, number, (int(circle_x - number_size.x // 2), int(circle_y - number_size.y // 2)), 30, 0, rl.WHITE)
rl.draw_text_ex(font, "\n".join(wrapped), rl.Vector2(text_x, y), 47, 0.0, rl.BLACK)
y += text_height + 50
if window:
remaining = max(0, math.ceil(window.get("deadline", 0.0) - time.monotonic()))
rl.draw_text_ex(gui_app.font(FontWeight.NORMAL), tr("Time left {}:{:02d}").format(remaining // 60, remaining % 60),
rl.Vector2(rect.x, y), 47, 0.0, rl.Color(70, 70, 70, 255))
@@ -149,7 +149,8 @@ class DeviceLayoutSP(DeviceLayout):
def _do_reset(result: int):
if result == DialogResult.CONFIRM:
for _key in ui_state.params.all_keys():
ui_state.params.remove(_key)
if not _key.startswith("SunnylinkLocal"):
ui_state.params.remove(_key)
HARDWARE.reboot()
def _second_confirm(result: int):
@@ -11,6 +11,7 @@ import pyray as rl
from openpilot.selfdrive.ui.layouts.settings import settings as OP
from openpilot.selfdrive.ui.layouts.settings.firehose import FirehoseLayout
from openpilot.selfdrive.ui.layouts.settings.toggles import TogglesLayout
from openpilot.selfdrive.ui.sunnypilot.layouts.settings.bluetooth import BluetoothLayout
from openpilot.selfdrive.ui.sunnypilot.layouts.settings.cruise import CruiseLayout
from openpilot.selfdrive.ui.sunnypilot.layouts.settings.developer import DeveloperLayoutSP
from openpilot.selfdrive.ui.sunnypilot.layouts.settings.device import DeviceLayoutSP
@@ -50,6 +51,7 @@ OP.PanelType = IntEnum( # type: ignore[assignment] # ty: ignore[invalid-assignm
"NAVIGATION",
"TRIPS",
"VEHICLE",
"BLUETOOTH",
],
start=0,
)
@@ -111,6 +113,7 @@ class SettingsLayoutSP(OP.SettingsLayout):
self._panels = {
OP.PanelType.DEVICE: PanelInfo(tr_noop("Device"), DeviceLayoutSP(), icon="../../sunnypilot/selfdrive/assets/offroad/icon_home.png"),
OP.PanelType.NETWORK: PanelInfo(tr_noop("Network"), NetworkUISP(wifi_manager), icon="icons/network.png"),
OP.PanelType.BLUETOOTH: PanelInfo(tr_noop("Bluetooth"), BluetoothLayout(), icon="../../sunnypilot/selfdrive/assets/offroad/icon_bluetooth.png"),
OP.PanelType.SUNNYLINK: PanelInfo(tr_noop("sunnylink"), SunnylinkLayout(), icon="icons/wifi_strength_full.png"),
OP.PanelType.TOGGLES: PanelInfo(tr_noop("Toggles"), TogglesLayout(), icon="../../sunnypilot/selfdrive/assets/offroad/icon_toggle.png"),
OP.PanelType.SOFTWARE: PanelInfo(tr_noop("Software"), SoftwareLayoutSP(), icon="../../sunnypilot/selfdrive/assets/offroad/icon_software.png"),
@@ -7,7 +7,7 @@ See the LICENSE.md file in the root directory for more details.
from openpilot.selfdrive.ui.sunnypilot.layouts.settings.vehicle.brands.base import BrandSettings
from openpilot.selfdrive.ui.ui_state import ui_state
from openpilot.system.ui.lib.multilang import tr
from openpilot.system.ui.sunnypilot.widgets.list_view import multiple_button_item_sp
from openpilot.system.ui.sunnypilot.widgets.list_view import toggle_item_sp
from opendbc.car.hyundai.values import CAR, UNSUPPORTED_LONGITUDINAL_CAR
@@ -16,16 +16,9 @@ class HyundaiSettings(BrandSettings):
super().__init__()
self.alpha_long_available = False
tuning_texts = [tr("Off"), tr("Dynamic"), tr("Predictive")]
self.longitudinal_tuning_item = multiple_button_item_sp(tr("Custom Longitudinal Tuning"), "", tuning_texts,
button_width=300, callback=self._on_tuning_selected,
param="HyundaiLongitudinalTuning", inline=False)
self.longitudinal_tuning_item = toggle_item_sp(tr("Custom Longitudinal Tuning"), "", param="HyundaiLongitudinalTuning")
self.items = [self.longitudinal_tuning_item]
@staticmethod
def _on_tuning_selected(index):
ui_state.params.put("HyundaiLongitudinalTuning", index)
def update_settings(self):
self.alpha_long_available = False
bundle = ui_state.params.get("CarPlatformBundle")
@@ -35,25 +28,14 @@ class HyundaiSettings(BrandSettings):
elif ui_state.CP is not None:
self.alpha_long_available = ui_state.CP.alphaLongitudinalAvailable
tuning_param = int(ui_state.params.get("HyundaiLongitudinalTuning") or "0")
long_enabled = ui_state.has_longitudinal_control
desc = tr("Accelerates and brakes the way your car's own cruise control does.")
if not ui_state.is_offroad():
desc = tr("This feature is unavailable while the car is onroad.")
elif not long_enabled:
desc = tr("This feature is unavailable because sunnypilot Longitudinal Control (Alpha) is not enabled.")
long_tuning_descs = [
tr("Your vehicle will use the Default longitudinal tuning."),
tr("Your vehicle will use the Dynamic longitudinal tuning."),
tr("Your vehicle will use the Predictive longitudinal tuning."),
]
long_tuning_desc = long_tuning_descs[tuning_param] if tuning_param < len(long_tuning_descs) else long_tuning_descs[0]
longitudinal_tuning_disabled = not ui_state.is_offroad() or not long_enabled
if longitudinal_tuning_disabled:
if not ui_state.is_offroad():
long_tuning_desc = tr("This feature is unavailable while the car is onroad.")
elif not long_enabled:
long_tuning_desc = tr("This feature is unavailable because sunnypilot Longitudinal Control (Alpha) is not enabled.")
self.longitudinal_tuning_item.action_item.set_enabled(not longitudinal_tuning_disabled)
self.longitudinal_tuning_item.set_description(long_tuning_desc)
self.longitudinal_tuning_item.action_item.set_enabled(ui_state.is_offroad() and long_enabled)
self.longitudinal_tuning_item.set_description(desc)
self.longitudinal_tuning_item.show_description(True)
self.longitudinal_tuning_item.action_item.set_selected_button(tuning_param)
self.longitudinal_tuning_item.set_visible(self.alpha_long_available)
@@ -11,6 +11,7 @@ import time
from dataclasses import dataclass
from openpilot.selfdrive.ui.ui_state import ui_state, ChestnutState
from openpilot.sunnypilot.sunnylink.api import UNREGISTERED_SUNNYLINK_DONGLE_ID
from openpilot.sunnypilot.system.connect_phone import phone_indicator, read_status
from openpilot.system.ui.lib.application import gui_app
from openpilot.system.ui.lib.multilang import tr_noop
@@ -23,6 +24,11 @@ HOME_BTN = rl.Rectangle(60, 860, 180, 180)
CHESTNUT_ICON_WIDTH = 180
CHESTNUT_ICON_HEIGHT = 133
BT_ICON_SIZE = 30
BT_ICON_X = 250 # right of the signal dots, clear of the mic indicator
BT_ICON_Y = 195
BT_POLL_SECONDS = 1.0
BT_WAITING_OPACITY = 0.35
# Color scheme
@@ -62,6 +68,19 @@ class SidebarSP:
self._chestnut_green_img = gui_app.texture("icons_mici/chestnut_green.png", CHESTNUT_ICON_WIDTH, CHESTNUT_ICON_HEIGHT)
self._chestnut_default_img = gui_app.texture("icons_mici/chestnut.png", CHESTNUT_ICON_WIDTH, CHESTNUT_ICON_HEIGHT)
self._chestnut_orange_img = gui_app.texture("icons_mici/chestnut_orange.png", CHESTNUT_ICON_WIDTH, CHESTNUT_ICON_HEIGHT)
self._bt_img = gui_app.texture("../../sunnypilot/selfdrive/assets/offroad/icon_bluetooth.png", BT_ICON_SIZE, BT_ICON_SIZE)
self._bt_state = "hidden"
self._bt_polled_at = float("-inf")
def _draw_bluetooth_indicator(self, rect: rl.Rectangle):
now = time.monotonic()
if now - self._bt_polled_at >= BT_POLL_SECONDS:
self._bt_polled_at = now
self._bt_state = phone_indicator(read_status(ui_state.params))
if self._bt_state == "hidden":
return
alpha = 255 if self._bt_state == "connected" else int(255 * BT_WAITING_OPACITY)
rl.draw_texture_ex(self._bt_img, rl.Vector2(rect.x + BT_ICON_X, rect.y + BT_ICON_Y), 0.0, 1.0, rl.Color(255, 255, 255, alpha))
def _update_sunnylink_status(self):
if not ui_state.params.get_bool("SunnylinkEnabled"):
@@ -0,0 +1,86 @@
"""
Copyright (c) 2021-, sunnypilot, and a number of other contributors.
This file is part of sunnypilot and is licensed under the MIT License.
See the LICENSE.md file in the root directory for more details.
"""
import time
from openpilot.selfdrive.ui.mici.widgets.button import BigButton, BigParamControl
from openpilot.selfdrive.ui.mici.widgets.dialog import BigConfirmationDialog
from openpilot.selfdrive.ui.sunnypilot.mici.layouts.connect_phone import start_connect_phone
from openpilot.selfdrive.ui.ui_state import ui_state
from openpilot.sunnypilot.system.ble import grants
from openpilot.sunnypilot.system.connect_phone import display_name, write_request
from openpilot.system.ui.lib.application import gui_app
from openpilot.system.ui.lib.multilang import tr
from openpilot.system.ui.widgets.scroller import NavScroller
POLL_SECONDS = 1.0
def _phone_count(n: int) -> str:
return tr("none connected") if n == 0 else tr("{} connected").format(n)
class BluetoothLayoutMici(NavScroller):
def __init__(self):
super().__init__()
self._bluetooth_on = ui_state.params.get_bool("BluetoothAllowed")
def bluetooth_callback(checked: bool):
self._bluetooth_on = checked
self._bluetooth_toggle = BigParamControl(tr("bluetooth"), "BluetoothAllowed", toggle_callback=bluetooth_callback)
self._connect_phone_btn = BigButton(tr("connect phone"), display_name(ui_state.params))
self._connect_phone_btn.set_click_callback(start_connect_phone)
self._connect_phone_btn.set_enabled(lambda: self._bluetooth_on)
self._phones_page = ConnectedPhonesMici()
self._phones_btn = BigButton(tr("phones"), "")
self._phones_btn.set_click_callback(lambda: gui_app.push_widget(self._phones_page))
self._phones_btn.set_visible(lambda: self._bluetooth_on)
self._last_poll = float("-inf")
self._scroller.add_widgets([self._bluetooth_toggle, self._connect_phone_btn, self._phones_btn])
def _update_state(self):
super()._update_state()
now = time.monotonic()
if now - self._last_poll >= POLL_SECONDS:
self._last_poll = now
self._phones_btn.set_value(_phone_count(len(grants.load(ui_state.params))))
class ConnectedPhonesMici(NavScroller):
def __init__(self):
super().__init__()
self._phone_items: list[BigButton] = []
self._grants: list[dict] | None = None
self._last_poll = float("-inf")
def _update_state(self):
super()._update_state()
now = time.monotonic()
if now - self._last_poll < POLL_SECONDS:
return
self._last_poll = now
phones = grants.load(ui_state.params)
if phones != self._grants:
self._grants = phones
for item in self._phone_items:
self._scroller._items.remove(item)
self._phone_items = [self._phone_item(phone) for phone in phones] or [BigButton(tr("no phones connected yet"), "")]
self._scroller.add_widgets(self._phone_items)
def _phone_item(self, phone: dict) -> BigButton:
spki = phone["spki"]
item = BigButton(phone["name"], tr("remove"), scroll=True)
item.set_click_callback(lambda: self._remove(spki))
return item
def _remove(self, spki: str) -> None:
icon = gui_app.texture("icons_mici/settings/network/new/trash.png", 54, 64)
gui_app.push_widget(BigConfirmationDialog(tr("slide to remove"), icon, lambda: write_request(ui_state.params, "remove", phone=spki), red=True))
@@ -0,0 +1,202 @@
"""
Copyright (c) 2021-, sunnypilot, and a number of other contributors.
This file is part of sunnypilot and is licensed under the MIT License.
See the LICENSE.md file in the root directory for more details.
"""
import time
import pyray as rl
from openpilot.common.qrcode import make_texture
from openpilot.common.swaglog import cloudlog
from openpilot.selfdrive.ui.mici.widgets.dialog import BigConfirmationCircleButton, BigDialog
from openpilot.selfdrive.ui.ui_state import device, ui_state
from openpilot.sunnypilot.system.connect_phone import WINDOW_SECONDS, format_code, read_window, write_request
from openpilot.system.ui.lib.application import FontWeight, gui_app
from openpilot.system.ui.lib.multilang import tr
from openpilot.system.ui.mici_setup import GreyBigButton
from openpilot.system.ui.widgets.label import UnifiedLabel
from openpilot.system.ui.widgets.nav_widget import NavWidget
from openpilot.system.ui.widgets.scroller import NavScroller
POLL_SECONDS = 0.25
START_TIMEOUT = 15 # seconds from open to the first window for this request
LOST_SECONDS = 3 # the daemon restarted mid-window and no longer reports our seq
INTERACTIVE_TIMEOUT = WINDOW_SECONDS + 10 # the offroad idle timeout would pop the screen mid-window
def _closed_message(reason: str) -> str | None:
messages = {
"granted": tr("phone connected"),
"denied": tr("phone not connected"),
"no_answer": tr("allow not tapped in time"),
"phone_left": tr("phone disconnected"),
"wrong_codes": tr("too many wrong codes"),
"limit": tr("8 phones already connected"),
"timeout": tr("connect timed out"),
"bluetooth_off": tr("turn on bluetooth"),
"no_key": tr("device key unavailable"),
}
return messages.get(reason)
def start_connect_phone() -> None:
gui_app.push_widget(ConnectPhoneDialog())
class ConnectPhoneDialog(NavWidget):
def __init__(self):
super().__init__()
self._params = ui_state.params
self._seq = write_request(self._params, "open")
self._opened_at = time.monotonic()
self._next_poll = 0.0
self._was_open = False
self._lost_since: float | None = None
self._window: dict | None = None
self._closing = False
self._check_shown_for: float | None = None
self._qr_source = ""
self._qr_texture: rl.Texture | None = None
self._title = UnifiedLabel(tr("connect phone"), font_size=48, font_weight=FontWeight.BOLD,
text_color=rl.Color(255, 255, 255, int(255 * 0.9)), line_height=0.8)
self._status = UnifiedLabel("", font_size=36, font_weight=FontWeight.ROMAN,
text_color=rl.Color(255, 255, 255, int(255 * 0.65)))
self._code = UnifiedLabel("", font_size=48, font_weight=FontWeight.BOLD,
text_color=rl.Color(255, 255, 255, int(255 * 0.9)))
self.set_back_callback(self._cancel)
def show_event(self):
super().show_event()
device.set_override_interactive_timeout(INTERACTIVE_TIMEOUT)
def hide_event(self):
super().hide_event()
device.set_override_interactive_timeout(None)
if not self._closing:
self._cancel()
def _update_state(self):
super()._update_state()
if self._closing:
return
now = time.monotonic()
if now < self._next_poll:
return
self._next_poll = now + POLL_SECONDS
window = read_window(self._params)
# the request seq guards against a window left over from an earlier open
if window is None or window.get("seq") != self._seq:
self._window = None
if self._was_open:
# a daemon restart writes seq 0 and never reports our window again
if self._lost_since is None:
self._lost_since = now
if now - self._lost_since > LOST_SECONDS:
self._finish(None)
elif now - self._opened_at > START_TIMEOUT:
self._cancel()
self._finish(tr("bluetooth did not start"))
return
self._lost_since = None
self._window = window
prompt = window.get("prompt") or {}
if prompt.get("step") == "allow" and self._check_shown_for != prompt.get("until"):
self._check_shown_for = prompt.get("until")
gui_app.push_widget(ConnectPhoneCheckDialog(prompt.get("check", ""), self._params))
if window.get("state") == "closed":
self._finish(_closed_message(window.get("reason", "")))
elif window.get("state") == "open":
self._was_open = True
if not window.get("held") and now >= window["deadline"]:
self._finish(_closed_message("timeout"))
def _cancel(self) -> None:
if not self._closing:
self._closing = True
write_request(self._params, "cancel")
def _finish(self, message: str | None) -> None:
self._closing = True
gui_app.pop_widgets_to(self, instant=True)
if message is None:
self.dismiss(lambda: None)
else:
self.dismiss(lambda: gui_app.push_widget(BigDialog(message, "")))
def _render(self, _):
window = self._window
held = window is not None and window.get("held", False)
show_code = window is not None and window.get("state") == "open" and not held
if show_code:
if window["qr"] != self._qr_source:
self._load_qr(window["qr"])
self._draw_qr()
label_x = self._rect.x + 8 + self._rect.height + 24 if show_code else self._rect.x + 20
max_width = int(self._rect.x + self._rect.width - label_x)
y = self._rect.y + 16
self._title.set_text(tr("scan or type") if show_code else tr("connect phone"))
self._title.set_max_width(max_width)
self._title.set_position(label_x, y)
self._title.render()
y += self._title.get_content_height(max_width) + 16
if show_code:
remaining = max(0, int(window["deadline"] - time.monotonic()))
self._code.set_text(format_code(int(window["code"])))
self._code.set_max_width(max_width)
self._code.set_position(label_x, y)
self._code.render()
y += self._code.get_content_height(max_width) + 12
self._status.set_text(f"{tr('expires in')} {remaining // 60}:{remaining % 60:02d}")
elif held:
self._status.set_text(tr("connecting phone"))
else:
self._status.set_text("" if self._closing else tr("starting bluetooth"))
self._status._shimmer = not show_code and not self._closing
self._status.set_max_width(max_width)
self._status.set_position(label_x, y)
self._status.render()
def _load_qr(self, text: str) -> None:
self._unload_qr()
self._qr_source = text
try:
self._qr_texture = make_texture(text, inverted=True)
except Exception:
cloudlog.exception("connect phone QR generation failed")
self._qr_texture = None
def _draw_qr(self) -> None:
if self._qr_texture is None:
return
scale = self._rect.height / self._qr_texture.height
rl.draw_texture_ex(self._qr_texture, rl.Vector2(round(self._rect.x + 8), round(self._rect.y)), 0.0, scale, rl.WHITE)
def _unload_qr(self) -> None:
if self._qr_texture and self._qr_texture.id != 0:
rl.unload_texture(self._qr_texture)
self._qr_texture = None
def __del__(self):
self._unload_qr()
class ConnectPhoneCheckDialog(NavScroller):
def __init__(self, check: str, params):
super().__init__()
self._params = params
allow = BigConfirmationCircleButton(tr("allow\nthis phone"), gui_app.texture("icons_mici/setup/driver_monitoring/dm_check.png", 64, 64),
lambda: self._answer("allow"))
deny = BigConfirmationCircleButton(tr("deny"), gui_app.texture("icons_mici/setup/cancel.png", 64, 64), lambda: self._answer("deny"))
self._scroller.add_widgets([GreyBigButton(check, tr("same code on your phone?"), gui_app.texture("icons_mici/setup/green_info.png", 64, 64)),
allow, deny])
def _answer(self, action: str) -> None:
self.dismiss(lambda: write_request(self._params, action))
@@ -5,19 +5,38 @@ This file is part of sunnypilot and is licensed under the MIT License.
See the LICENSE.md file in the root directory for more details.
"""
import math
import time
import pyray as rl
from openpilot.selfdrive.ui.mici.layouts.home import MiciHomeLayout
from openpilot.selfdrive.ui.ui_state import ui_state, ChestnutState
from openpilot.sunnypilot.system.connect_phone import phone_indicator, read_status
from openpilot.system.ui.lib.application import FontWeight
from openpilot.system.ui.widgets.icon_widget import IconWidget
from openpilot.system.ui.widgets.label import UnifiedLabel
BT_POLL_SECONDS = 1.0
BT_WAITING_OPACITY = 0.35
class MiciHomeLayoutSP(MiciHomeLayout):
def __init__(self):
super().__init__()
self._openpilot_label = UnifiedLabel("sunnypilot", font_size=88, font_weight=FontWeight.AUDIOWIDE, max_width=480, wrap_text=False)
self._bluetooth_icon = IconWidget("../../sunnypilot/selfdrive/assets/offroad/icon_bluetooth.png", (40, 40))
self._bluetooth_icon.set_visible(False)
self._bt_polled_at = float("-inf")
self._status_bar_layout.add_widget(self._bluetooth_icon)
def _update_state(self):
super()._update_state()
now = time.monotonic()
if now - self._bt_polled_at >= BT_POLL_SECONDS:
self._bt_polled_at = now
state = phone_indicator(read_status(ui_state.params))
self._bluetooth_icon.set_visible(state != "hidden")
self._bluetooth_icon.set_opacity(1.0 if state == "connected" else BT_WAITING_OPACITY)
def _set_chestnut_visibility(self):
usb_connected = ui_state.usb_connected
@@ -11,6 +11,7 @@ from openpilot.selfdrive.ui.mici.widgets.button import BigCircleButton
from openpilot.selfdrive.ui.mici.widgets.dialog import BigConfirmationDialog, BigDialog
from openpilot.selfdrive.ui.sunnypilot.mici.layouts.sunnylink import SunnylinkLayoutMici
from openpilot.selfdrive.ui.sunnypilot.mici.layouts.models import ModelsLayoutMici
from openpilot.selfdrive.ui.sunnypilot.mici.layouts.bluetooth import BluetoothLayoutMici
from openpilot.selfdrive.ui.ui_state import ui_state
from openpilot.system.ui.lib.application import gui_app, FontWeight
from openpilot.system.ui.lib.multilang import tr
@@ -50,6 +51,12 @@ class SettingsLayoutSP(OP.SettingsLayout):
models_btn = SettingsBigButton(tr("models"), "", gui_app.texture("../../sunnypilot/selfdrive/assets/offroad/icon_models.png", ICON_SIZE, ICON_SIZE))
models_btn.set_click_callback(lambda: gui_app.push_widget(models_panel))
network_btn = self._scroller._items[1]
bluetooth_panel = BluetoothLayoutMici()
bluetooth_btn = SettingsBigButton(tr("bluetooth"), "",
gui_app.texture("../../sunnypilot/selfdrive/assets/offroad/icon_bluetooth.png", ICON_SIZE, ICON_SIZE))
bluetooth_btn.set_click_callback(lambda: gui_app.push_widget(bluetooth_panel))
# onroad: enable button sits at the front (left of toggles)
self._enable_offroad_btn_onroad = BigCircleButton(self.icon_offroad_enable, red=True)
self._enable_offroad_btn_onroad.set_click_callback(lambda: self._handle_always_offroad(True))
@@ -68,6 +75,7 @@ class SettingsLayoutSP(OP.SettingsLayout):
items.insert(1, models_btn)
items.insert(5, sunnylink_btn)
items.insert(items.index(network_btn) + 1, bluetooth_btn)
# front slots (only one ever visible at a time): exit-always-offroad, then enable-onroad
items.insert(0, self._enable_offroad_btn_onroad)
@@ -7,6 +7,7 @@ See the LICENSE.md file in the root directory for more details.
import pyray as rl
from openpilot.selfdrive.ui.ui_state import UIStatus
from openpilot.selfdrive.ui.sunnypilot.onroad.blendful import BlendfulRenderer
from openpilot.selfdrive.ui.sunnypilot.onroad.radar_tracks import RadarTracks
from openpilot.selfdrive.ui.sunnypilot.onroad.rainbow_path import RainbowPath
LANE_LINE_COLORS_SP = {
@@ -18,4 +19,5 @@ LANE_LINE_COLORS_SP = {
class ModelRendererSP:
def __init__(self):
self.rainbow_path = RainbowPath()
self.radar_tracks = RadarTracks()
self.blendful = BlendfulRenderer(rect_relative=True)
@@ -0,0 +1,9 @@
"""
Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors.
This file is part of sunnypilot and is licensed under the MIT License.
See the LICENSE.md file in the root directory for more details.
"""
from openpilot.selfdrive.ui.sunnypilot.mici.onroad.robotic.robotic_view import RoboticOnroadView
__all__ = ["RoboticOnroadView"]
@@ -0,0 +1,137 @@
"""
Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors.
This file is part of sunnypilot and is licensed under the MIT License.
See the LICENSE.md file in the root directory for more details.
"""
import math
import pyray as rl
from openpilot.cereal import log
from openpilot.common.filter_simple import FirstOrderFilter
from openpilot.selfdrive.ui.mici.onroad.alert_renderer import Alert, AlertRenderer
from openpilot.selfdrive.ui.ui_state import ui_state
from openpilot.system.ui.lib.application import FontWeight, TextAlignment, gui_app
from openpilot.system.ui.widgets.label import UnifiedLabel
AlertStatus = log.SelfdriveState.AlertStatus
class RoboticAlertOverlay:
"""Harmonized alert overlay that keeps robotic expressions visible while preserving safety readability."""
def __init__(self):
dt = 1.0 / max(gui_app.target_fps, 1)
self._alert_source = AlertRenderer()
self._prev_alert: Alert | None = None
self._alpha_filter = FirstOrderFilter(0.0, 0.06, dt)
self._text1_label = UnifiedLabel(
text="",
font_size=44,
font_weight=FontWeight.DISPLAY,
alignment=TextAlignment.CENTER,
line_height=0.9,
)
self._text2_label = UnifiedLabel(
text="",
font_size=26,
font_weight=FontWeight.MEDIUM,
alignment=TextAlignment.CENTER,
line_height=0.95,
)
def get_alert(self) -> Alert | None:
alert = self._alert_source.get_alert(ui_state.sm)
if gui_app.sunnypilot_ui():
ui_state.onroad_brightness_handle_alerts(ui_state, alert)
return alert
def render(self, rect: rl.Rectangle, alert: Alert | None) -> float:
"""Render alert overlay and return current alpha (0..1) so caller can shift face if needed."""
alpha = self._alpha_filter.update(1.0 if alert is not None else 0.0)
if alert is not None:
self._prev_alert = alert
elif alpha > 0.02 and self._prev_alert is not None:
alert = self._prev_alert
else:
self._prev_alert = None
return 0.0
is_critical = alert.status == AlertStatus.critical
is_prompt = alert.status == AlertStatus.userPrompt
if is_critical:
pulse = 0.65 + 0.35 * (0.5 + 0.5 * math.sin(rl.get_time() * 14.0))
# Pulsing red edge frame + bottom dark backing so red eyes + takeover text are unmistakable
border_col = rl.Color(255, 25, 35, int(230 * pulse * alpha))
rl.draw_rectangle_rounded_lines_ex(
rl.Rectangle(rect.x + 3, rect.y + 3, rect.width - 6, rect.height - 6),
0.16,
12,
10.0,
border_col,
)
band_h = 98
rl.draw_rectangle_gradient_v(
int(rect.x),
int(rect.y + rect.height - band_h - 18),
int(rect.width),
band_h + 18,
rl.Color(180, 0, 15, 0),
rl.Color(210, 0, 20, int(230 * alpha)),
)
self._draw_banner_text(rect, alert, rect.y + rect.height - band_h + 4, band_h, alpha, big=True)
elif is_prompt:
band_h = 84
rl.draw_rectangle_gradient_v(
int(rect.x),
int(rect.y + rect.height - band_h - 14),
int(rect.width),
band_h + 14,
rl.Color(220, 95, 0, 0),
rl.Color(235, 105, 0, int(215 * alpha)),
)
self._draw_banner_text(rect, alert, rect.y + rect.height - band_h + 6, band_h, alpha, big=False)
else:
# Soft / normal alert: compact bottom pill leaving the expressive eyes unobstructed
band_h = 66
pill = rl.Rectangle(rect.x + 24, rect.y + rect.height - band_h - 8, rect.width - 48, band_h)
rl.draw_rectangle_rounded(pill, 0.38, 12, rl.Color(24, 28, 34, int(215 * alpha)))
rl.draw_rectangle_rounded_lines_ex(pill, 0.38, 12, 2.0, rl.Color(255, 255, 255, int(45 * alpha)))
self._draw_banner_text(rect, alert, pill.y + 6, band_h - 8, alpha, big=False)
return alpha
def _draw_banner_text(
self,
rect: rl.Rectangle,
alert: Alert,
top_y: float,
band_h: float,
alpha: float,
big: bool,
) -> None:
text1 = alert.text1.lower()
text2 = alert.text2.lower()
if big:
font1 = 42 if len(text1) <= 18 else 34
else:
font1 = 34 if len(text1) <= 22 else 28
margin_x = 34
w = rect.width - margin_x * 2
self._text1_label.set_text(text1)
self._text1_label.set_font_size(font1)
self._text1_label.set_text_color(rl.Color(255, 255, 255, int(245 * alpha)))
self._text1_label.render(rl.Rectangle(rect.x + margin_x, top_y, w, band_h))
if text2:
font2 = 24 if len(text2) <= 28 else 20
self._text2_label.set_text(text2)
self._text2_label.set_font_size(font2)
self._text2_label.set_text_color(rl.Color(255, 255, 255, int(195 * alpha)))
self._text2_label.render(rl.Rectangle(rect.x + margin_x, top_y + font1 + 2, w, max(24.0, band_h - font1)))
@@ -0,0 +1,712 @@
"""
Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors.
This file is part of sunnypilot and is licensed under the MIT License.
See the LICENSE.md file in the root directory for more details.
"""
from dataclasses import dataclass
from enum import Enum
import math
import random
import time
from openpilot.cereal import log
from openpilot.common.constants import CV
from openpilot.selfdrive.ui.mici.onroad.alert_renderer import Alert
from openpilot.selfdrive.ui.sunnypilot.mici.onroad.robotic.music_analyzer import MusicState
from openpilot.selfdrive.ui.sunnypilot.mici.onroad.robotic.music_visualizer import groove_prism_color
from openpilot.selfdrive.ui.ui_state import UIStatus
AlertStatus = log.SelfdriveState.AlertStatus
EventName = log.OnroadEvent.EventName
SET_SPEED_NA = 255
KM_TO_MILE = 0.621371
# Thresholds & hold durations (seconds)
HARD_DECEL_THRESHOLD = -3.0 # m/s^2 triggers startled star eyes
SHARP_ACCEL_THRESHOLD = 2.2 # m/s^2 triggers excited boost eyes
STANDSTILL_POUT_DELAY = 8.0 # seconds at standstill before pouting
STANDSTILL_SLEEPY_DELAY = 35.0 # seconds at standstill before sleepy
CURVE_STEER_THRESHOLD = 15.0 # degrees steering angle for curve tracking
SHARP_TURN_THRESHOLD = 45.0 # degrees steering angle for intense centrifugal lean
SET_SPEED_SHOW_DURATION = 3.0 # seconds to show speed arc on set-speed change
ENGAGE_HAPPY_DURATION = 0.9 # seconds of joyful crescent eyes on engage
ENGAGE_SPEED_CONFIRM = 2.0 # seconds of speed readout right after happy engage
STARTLED_HOLD_DURATION = 1.5 # seconds to hold star-shock expression
BOOST_HOLD_DURATION = 1.2 # seconds to hold sharp-accel boost expression
LOVE_HOLD_DURATION = 1.6 # seconds to hold heart/pet expression
MANUAL_SPEED_PEEK_DURATION = 4.0 # seconds for swipe-up speed peek
class RoboticMood(Enum):
CRITICAL = "critical"
DISTRACTED = "distracted"
USER_PROMPT = "user_prompt"
STARTLED_STARS = "startled_stars"
LANE_CHANGE = "lane_change"
BLIND_SPOT = "blind_spot"
BOOKMARK_LOVE = "bookmark_love"
HAPPY_ENGAGE = "happy_engage"
BOOST_ACCEL = "boost_accel"
TURN_SIGNAL = "turn_signal"
SPEED_DISPLAY = "speed_display"
POUT_STANDSTILL = "pout_standstill"
SLEEPY = "sleepy"
SHARP_TURN = "sharp_turn"
CURVE_FOCUS = "curve_focus"
MUSIC_GROOVE = "music_groove"
CRUISING_HAPPY = "cruising_happy"
IDLE_CURIOUS = "idle_curious"
class IdleAction(Enum):
"""Playful autonomous micro-behaviors during normal cruising & idle driving."""
NONE = "none"
HAPPY_SQUINT = "happy_squint"
CURIOUS_LOOK = "curious_look"
CHEEKY_WINK = "cheeky_wink"
GROOVE_BOB = "groove_bob"
class EyeGlyph(Enum):
ROUND_RECT = "round_rect"
STAR = "star"
HEART = "heart"
CRESCENT = "crescent"
ARROW_LEFT = "arrow_left"
ARROW_RIGHT = "arrow_right"
LASER_ALERT = "laser_alert"
SPARKLE_BOOST = "sparkle_boost"
class MouthGlyph(Enum):
NONE = "none"
SMILE = "smile"
BIG_GRIN = "big_grin"
FROWN = "frown"
SURPRISED = "surprised"
# Dynamic status & mood palette (RGB tuples)
PALETTE = {
"engaged": (64, 240, 226), # EMO vibrant cyan-emerald
"lat_only": (255, 212, 178), # Reference-video warm peach
"long_only": (92, 198, 255), # Sky cyan
"disengaged": (218, 232, 248), # Soft ice white
"override": (255, 196, 68), # Warm amber
"boost": (76, 178, 255), # Electric boost blue
"prompt": (255, 125, 20), # Vivid orange
"critical": (255, 38, 48), # Alert red
"love": (255, 112, 168), # Rose pink
}
@dataclass
class EyeTarget:
width: float = 104.0
height: float = 112.0
roundness: float = 0.62 # Bubbly chunky squircle
top_lid: float = 0.0 # 0..1 fraction covered from top
bottom_lid: float = 0.0 # 0..1 fraction covered from bottom
top_slant: float = 0.0 # degrees (+ = angry/inward, - = sad/outward)
gaze_x: float = 0.0 # px shift (-42..+42)
gaze_y: float = 0.0 # px shift (-22..+22)
bounce_y: float = 0.0 # vertical expressiveness offset
tilt_y: float = 0.0 # vertical asymmetry between left & right eye (playful head tilt)
scale_x: float = 1.0 # squash-and-stretch horizontal multiplier
scale_y: float = 1.0 # squash-and-stretch vertical multiplier
wink_right: bool = False # cute asymmetric wink on bookmark or cheeky idle wink
squish_force: float = 0.0 # -1..+1 centrifugal push (-1 left wall, +1 right wall)
pitch_offset_y: float = 0.0 # px vertical bob from pitch / pitch-rate (bumps, hills, dive)
glyph: EyeGlyph = EyeGlyph.ROUND_RECT
mouth: MouthGlyph = MouthGlyph.NONE
color: tuple[int, int, int] = PALETTE["engaged"]
pulse_speed: float = 0.0 # Hz for alert pulsing
blind_spot_side: int = 0 # -1 left, +1 right, 0 none
blinker_side: int = 0 # -1 left, +1 right, 0 none
show_speed_lines: bool = False
show_zzz: bool = False
show_hearts: bool = False
@dataclass
class DrivingSnapshot:
"""Pure-data snapshot of driving signals for deterministic mood evaluation & testing."""
started: bool = True
engaged: bool = False
status: UIStatus = UIStatus.DISENGAGED
v_ego: float = 0.0 # m/s
a_ego: float = 0.0 # m/s^2
standstill: bool = False
steering_angle_deg: float = 0.0
yaw_rate: float = 0.0 # rad/s (+ = turning left -> centrifugal push right)
pitch_rad: float = 0.0 # rad (+ = nose up / hill climb)
pitch_rate: float = 0.0 # rad/s (bumps, crests, braking dive)
curvature: float = 0.0 # rad/m fallback for centrifugal accel
set_speed_kph: float = SET_SPEED_NA
is_metric: bool = False
left_blinker: bool = False
right_blinker: bool = False
left_blindspot: bool = False
right_blindspot: bool = False
pre_lane_change_left: bool = False
pre_lane_change_right: bool = False
lane_change: bool = False
lane_change_blocked: bool = False
dm_alert_level: int = 0 # 0=none, 1=warn, 2=critical
alert: Alert | None = None
music: MusicState | None = None
class RoboticMoodEngine:
"""Priority-based EMO-inspired mood & lively autonomous personality state machine."""
def __init__(self, rng: random.Random | None = None):
self._rng = rng or random.Random()
self.mood: RoboticMood = RoboticMood.IDLE_CURIOUS
self.idle_action: IdleAction = IdleAction.NONE
self.showing_speed: bool = False
self.speed_reason: str = "" # "set_speed", "engage", "peek"
self.cruising_smoothly: bool = False
self._prev_engaged: bool = False
self._prev_set_speed: float = SET_SPEED_NA
self._standstill_since: float | None = None
self._last_lane_dir: int = 0 # -1 left, +1 right
# Hold / effect timers (monotonic timestamps)
self._startled_until: float = 0.0
self._boost_until: float = 0.0
self._love_until: float = 0.0
self._love_wink: bool = False
self._happy_engage_until: float = 0.0
self._speed_display_until: float = 0.0
# Blink, gaze, and playful idle personality schedulers
now = time.monotonic()
self._next_blink_at: float = now + self._rng.uniform(1.8, 3.6)
self._blink_end_at: float = 0.0
self._blink_rebound_until: float = 0.0
self._double_blink_pending: bool = False
self._next_glance_at: float = now + self._rng.uniform(1.2, 2.6)
self._idle_gaze_x: float = 0.0
self._idle_gaze_y: float = 0.0
self._idle_tilt_y: float = 0.0
self._next_idle_action_at: float = now + self._rng.uniform(2.2, 3.8)
self._idle_action_until: float = 0.0
self._idle_action_dir: float = 1.0
def trigger_love(self, now: float | None = None, wink: bool = False) -> None:
t = time.monotonic() if now is None else now
self._love_until = t + LOVE_HOLD_DURATION
self._love_wink = wink
def trigger_speed_peek(self, now: float | None = None) -> None:
t = time.monotonic() if now is None else now
self._speed_display_until = max(self._speed_display_until, t + MANUAL_SPEED_PEEK_DURATION)
self.speed_reason = "peek"
def trigger_startled(self, now: float | None = None) -> None:
t = time.monotonic() if now is None else now
self._startled_until = max(self._startled_until, t + STARTLED_HOLD_DURATION)
def trigger_boost(self, now: float | None = None) -> None:
t = time.monotonic() if now is None else now
self._boost_until = max(self._boost_until, t + BOOST_HOLD_DURATION)
def _status_color(self, snap: DrivingSnapshot) -> tuple[int, int, int]:
if snap.status == UIStatus.ENGAGED:
return PALETTE["engaged"]
if snap.status == UIStatus.LAT_ONLY:
return PALETTE["lat_only"]
if snap.status == UIStatus.LONG_ONLY:
return PALETTE["long_only"]
if snap.status == UIStatus.OVERRIDE:
return PALETTE["override"]
return PALETTE["disengaged"]
def _update_blink_and_personality(self, now: float, sleepy: bool) -> tuple[float, float, float]:
"""Returns (blink_closure, squash_x, stretch_y) and advances idle glances & micro-actions."""
blink_closure = 0.0
squash_x = 1.0
stretch_y = 1.0
if now < self._blink_end_at:
blink_closure = 1.0
squash_x = 1.16
stretch_y = 0.86
elif now < self._blink_rebound_until:
# Juicy bubbly pop-open after blink
squash_x = 0.93
stretch_y = 1.10
elif now >= self._next_blink_at:
blink_dur = 0.22 if sleepy else 0.11
self._blink_end_at = now + blink_dur
self._blink_rebound_until = self._blink_end_at + 0.12
blink_closure = 1.0
squash_x = 1.16
stretch_y = 0.86
if not sleepy and not self._double_blink_pending and self._rng.random() < 0.30:
self._double_blink_pending = True
self._next_blink_at = self._blink_end_at + 0.13
else:
self._double_blink_pending = False
lo, hi = (1.6, 3.0) if sleepy else (2.2, 4.4)
self._next_blink_at = self._blink_end_at + self._rng.uniform(lo, hi)
if now >= self._next_glance_at:
roll = self._rng.random()
if roll < 0.28:
self._idle_gaze_x = 0.0
self._idle_gaze_y = 0.0
self._idle_tilt_y = 0.0
else:
self._idle_gaze_x = self._rng.uniform(-34.0, 34.0)
self._idle_gaze_y = self._rng.uniform(-12.0, 10.0)
self._idle_tilt_y = self._rng.uniform(-9.0, 9.0)
self._next_glance_at = now + self._rng.uniform(1.3, 2.8)
# Playful autonomous micro-behaviors during normal cruising/idle
if now >= self._idle_action_until:
self.idle_action = IdleAction.NONE
if not sleepy and now >= self._next_idle_action_at:
choice = self._rng.choice([
IdleAction.HAPPY_SQUINT,
IdleAction.CURIOUS_LOOK,
IdleAction.CHEEKY_WINK,
IdleAction.GROOVE_BOB,
])
self.idle_action = choice
self._idle_action_dir = -1.0 if self._rng.random() < 0.5 else 1.0
dur = {
IdleAction.HAPPY_SQUINT: 0.80,
IdleAction.CURIOUS_LOOK: 1.50,
IdleAction.CHEEKY_WINK: 0.55,
IdleAction.GROOVE_BOB: 1.80,
}[choice]
self._idle_action_until = now + dur
self._next_idle_action_at = self._idle_action_until + self._rng.uniform(2.0, 3.8)
return blink_closure, squash_x, stretch_y
def update(self, snap: DrivingSnapshot, now: float | None = None) -> EyeTarget:
t = time.monotonic() if now is None else now
# Track standstill duration
if snap.standstill or not snap.started:
if self._standstill_since is None:
self._standstill_since = t
else:
self._standstill_since = None
standstill_dur = (t - self._standstill_since) if self._standstill_since is not None else 0.0
# Track engagement rising edge
if snap.engaged and not self._prev_engaged:
self._happy_engage_until = t + ENGAGE_HAPPY_DURATION
self._speed_display_until = max(
self._speed_display_until,
t + ENGAGE_HAPPY_DURATION + ENGAGE_SPEED_CONFIRM,
)
self.speed_reason = "engage"
self._prev_engaged = snap.engaged
# Track set-speed change while cruise is set
cruise_set = 0 < snap.set_speed_kph < SET_SPEED_NA
if cruise_set and snap.set_speed_kph != self._prev_set_speed and self._prev_set_speed != SET_SPEED_NA:
self._speed_display_until = max(self._speed_display_until, t + SET_SPEED_SHOW_DURATION)
self.speed_reason = "set_speed"
self._prev_set_speed = snap.set_speed_kph
# Track startling events & sharp acceleration
if snap.a_ego < HARD_DECEL_THRESHOLD or snap.lane_change_blocked:
self._startled_until = max(self._startled_until, t + STARTLED_HOLD_DURATION)
elif snap.a_ego > SHARP_ACCEL_THRESHOLD and not snap.standstill:
self._boost_until = max(self._boost_until, t + BOOST_HOLD_DURATION)
# Track lane change direction
if snap.pre_lane_change_left:
self._last_lane_dir = -1
elif snap.pre_lane_change_right:
self._last_lane_dir = 1
elif not snap.lane_change:
self._last_lane_dir = 0
blinker_side = -1 if snap.left_blinker else (1 if snap.right_blinker else 0)
bsm_side = 0
if snap.left_blindspot and (snap.left_blinker or snap.pre_lane_change_left):
bsm_side = -1
elif snap.right_blindspot and (snap.right_blinker or snap.pre_lane_change_right):
bsm_side = 1
elif snap.left_blindspot and not snap.standstill:
bsm_side = -1
elif snap.right_blindspot and not snap.standstill:
bsm_side = 1
self.cruising_smoothly = snap.engaged and not snap.standstill and abs(snap.a_ego) < 0.8
# Evaluate mood priority
alert = snap.alert
alert_status = alert.status if alert is not None else -1
alert_type = alert.alert_type if alert is not None else ""
is_dm_alert = snap.dm_alert_level >= 1 or "Distracted" in alert_type or "Unresponsive" in alert_type
self.showing_speed = False
# Compute physical centrifugal force (-1 = pushed left, +1 = pushed right) & pitch bob
# Positive yaw_rate (turning left) pushes the bot toward the right wall (+1)
effective_yaw = snap.yaw_rate
if abs(effective_yaw) < 1e-4 and abs(snap.curvature) > 1e-5:
effective_yaw = snap.v_ego * snap.curvature
lat_accel = snap.v_ego * effective_yaw # m/s^2
# Blend true lateral G with direct gyro yaw-rate so even tight low-speed turns feel lively
centrifugal_raw = (lat_accel / 4.2) + (effective_yaw / 1.4) * 0.35
if abs(centrifugal_raw) < 0.05 and abs(snap.steering_angle_deg) > CURVE_STEER_THRESHOLD and not snap.standstill:
# Fallback for desktop previews/simulators without IMU data
centrifugal_raw = max(-1.0, min(1.0, (snap.steering_angle_deg / 90.0) * max(0.35, snap.v_ego / 20.0)))
squish_force = max(-1.0, min(1.0, centrifugal_raw)) if not snap.standstill else 0.0
if abs(squish_force) < 0.08:
squish_force = 0.0
pitch_offset_y = max(-22.0, min(22.0, snap.pitch_rad * 55.0 + snap.pitch_rate * 20.0))
if alert is not None and alert_status == AlertStatus.critical:
self.mood = RoboticMood.CRITICAL
elif is_dm_alert:
self.mood = RoboticMood.DISTRACTED
elif alert is not None and alert_status == AlertStatus.userPrompt:
self.mood = RoboticMood.USER_PROMPT
elif t < self._startled_until:
self.mood = RoboticMood.STARTLED_STARS
elif snap.pre_lane_change_left or snap.pre_lane_change_right or snap.lane_change:
self.mood = RoboticMood.LANE_CHANGE
elif bsm_side != 0 and blinker_side != 0:
self.mood = RoboticMood.BLIND_SPOT
elif t < self._love_until:
self.mood = RoboticMood.BOOKMARK_LOVE
elif t < self._happy_engage_until:
self.mood = RoboticMood.HAPPY_ENGAGE
elif t < self._speed_display_until and snap.started:
self.mood = RoboticMood.SPEED_DISPLAY
self.showing_speed = True
elif t < self._boost_until:
self.mood = RoboticMood.BOOST_ACCEL
elif blinker_side != 0:
self.mood = RoboticMood.TURN_SIGNAL
elif (abs(squish_force) >= 0.42 or abs(snap.steering_angle_deg) >= SHARP_TURN_THRESHOLD) and not snap.standstill:
self.mood = RoboticMood.SHARP_TURN
elif (abs(squish_force) >= 0.18 or abs(snap.steering_angle_deg) > CURVE_STEER_THRESHOLD) and not snap.standstill:
self.mood = RoboticMood.CURVE_FOCUS
elif snap.started and snap.music is not None and snap.music.is_music and alert is None:
self.mood = RoboticMood.MUSIC_GROOVE
elif not snap.started or standstill_dur >= STANDSTILL_SLEEPY_DELAY:
self.mood = RoboticMood.SLEEPY
elif standstill_dur >= STANDSTILL_POUT_DELAY:
self.mood = RoboticMood.POUT_STANDSTILL
elif snap.engaged:
self.mood = RoboticMood.CRUISING_HAPPY
else:
self.mood = RoboticMood.IDLE_CURIOUS
base_color = self._status_color(snap)
blink, squash_x, stretch_y = self._update_blink_and_personality(t, sleepy=(self.mood == RoboticMood.SLEEPY))
# Lively, clearly visible breathing & energetic bounce so the face is always bubbling with life
energy = 1.0 + min(0.55, snap.v_ego / 35.0)
breathe_y = math.sin(t * 2.8 * energy) * 6.5 + math.sin(t * 1.3) * 2.5
breathe_scale = 1.0 + 0.035 * math.sin(t * 2.8 * energy - 0.35)
micro_drift_x = math.sin(t * 1.1) * 6.0
# Steering-coupled gaze (clamped to [-40, +40])
steer_gaze = max(-40.0, min(40.0, -snap.steering_angle_deg * 0.78))
target = EyeTarget(
color=base_color,
bounce_y=breathe_y,
scale_x=squash_x * breathe_scale,
scale_y=stretch_y * (2.0 - breathe_scale),
squish_force=squish_force,
pitch_offset_y=pitch_offset_y,
blind_spot_side=bsm_side,
blinker_side=blinker_side,
)
if self.mood == RoboticMood.CRITICAL:
target.glyph = EyeGlyph.LASER_ALERT
target.color = PALETTE["critical"]
target.width = 114.0
target.height = 84.0
target.roundness = 0.42
target.top_lid = 0.28
target.top_slant = 18.0
target.pulse_speed = 5.5
target.bounce_y = math.sin(t * 28.0) * 3.5
elif self.mood == RoboticMood.DISTRACTED:
target.color = PALETTE["prompt"]
target.width = 108.0
target.height = 96.0
target.roundness = 0.48
target.top_lid = 0.32
target.top_slant = 12.0
target.gaze_x = math.sin(t * 5.2) * 18.0
target.mouth = MouthGlyph.FROWN
target.pulse_speed = 2.5
elif self.mood == RoboticMood.USER_PROMPT:
target.color = PALETTE["prompt"]
target.width = 108.0
target.height = 120.0
target.top_lid = 0.06
target.top_slant = -6.0
target.gaze_x = micro_drift_x
target.pulse_speed = 1.8
elif self.mood == RoboticMood.STARTLED_STARS:
target.glyph = EyeGlyph.STAR
target.color = PALETTE["override"]
target.width = 114.0
target.height = 114.0
target.mouth = MouthGlyph.SURPRISED
target.bounce_y = math.sin(t * 26.0) * 6.0
target.scale_x = 1.0 + 0.08 * math.sin(t * 22.0)
target.scale_y = 1.0 - 0.08 * math.sin(t * 22.0)
elif self.mood == RoboticMood.LANE_CHANGE:
direction = -1 if snap.pre_lane_change_left else (1 if snap.pre_lane_change_right else self._last_lane_dir or 1)
target.glyph = EyeGlyph.ARROW_LEFT if direction < 0 else EyeGlyph.ARROW_RIGHT
target.gaze_x = direction * 32.0 + math.sin(t * 6.5) * 5.0
target.height = 106.0
target.top_lid = 0.10
target.tilt_y = direction * 7.0
target.mouth = MouthGlyph.SMILE
elif self.mood == RoboticMood.BLIND_SPOT:
target.color = PALETTE["override"]
target.gaze_x = bsm_side * 38.0
target.height = 102.0
target.top_lid = 0.22
target.top_slant = 9.0
target.pulse_speed = 3.2
elif self.mood == RoboticMood.BOOKMARK_LOVE:
target.glyph = EyeGlyph.HEART
target.color = PALETTE["love"]
target.width = 114.0
target.height = 114.0
target.wink_right = self._love_wink
target.mouth = MouthGlyph.BIG_GRIN
target.bounce_y = -abs(math.sin(t * 10.5)) * 15.0
target.show_hearts = True
elif self.mood == RoboticMood.HAPPY_ENGAGE:
target.glyph = EyeGlyph.CRESCENT
target.color = PALETTE["engaged"]
target.width = 116.0
target.height = 100.0
target.mouth = MouthGlyph.BIG_GRIN
target.bounce_y = -abs(math.sin(t * 9.5)) * 16.0
elif self.mood == RoboticMood.BOOST_ACCEL:
target.glyph = EyeGlyph.SPARKLE_BOOST
target.color = PALETTE["boost"]
target.width = 116.0
target.height = 120.0
target.gaze_y = -7.0
target.mouth = MouthGlyph.BIG_GRIN
target.bounce_y = math.sin(t * 18.0) * 5.0
target.show_speed_lines = True
elif self.mood == RoboticMood.TURN_SIGNAL:
beat = 0.5 + 0.5 * math.sin(t * 8.4)
target.gaze_x = blinker_side * (22.0 + 14.0 * beat)
target.tilt_y = blinker_side * 8.0
target.width = 106.0
target.height = 108.0
target.top_lid = 0.08
target.mouth = MouthGlyph.SMILE
elif self.mood == RoboticMood.POUT_STANDSTILL:
target.width = 98.0
target.height = 84.0
target.roundness = 0.34
target.top_lid = 0.26 + 0.05 * math.sin(t * 1.8)
target.gaze_x = self._idle_gaze_x * 0.75 + micro_drift_x
target.gaze_y = 6.0
target.tilt_y = self._idle_tilt_y * 0.7
target.mouth = MouthGlyph.FROWN
elif self.mood == RoboticMood.SLEEPY:
target.width = 104.0
target.height = 76.0
target.roundness = 0.45
target.top_lid = 0.58 + 0.09 * math.sin(t * 1.5)
target.bottom_lid = 0.14
target.gaze_y = 8.0
target.gaze_x = math.sin(t * 0.7) * 8.0
target.bounce_y = math.sin(t * 1.5) * 6.0
target.show_zzz = True
elif self.mood == RoboticMood.SHARP_TURN:
intensity = max(abs(squish_force), min(1.0, abs(snap.steering_angle_deg) / 85.0))
push_dir = 1.0 if squish_force > 0 else (-1.0 if squish_force < 0 else (1.0 if snap.steering_angle_deg > 0 else -1.0))
target.squish_force = push_dir * intensity
target.width = 108.0
target.height = 104.0
target.top_lid = 0.10 + 0.14 * intensity
target.top_slant = 5.0 + 7.0 * intensity
target.gaze_x = push_dir * 12.0 # squish renderer handles primary wall slide
target.gaze_y = -3.0
target.tilt_y = push_dir * (8.0 + 8.0 * intensity)
target.mouth = MouthGlyph.SURPRISED if intensity >= 0.62 else MouthGlyph.SMILE
elif self.mood == RoboticMood.CURVE_FOCUS:
intensity = max(abs(squish_force), min(0.5, abs(snap.steering_angle_deg) / 70.0))
push_dir = 1.0 if squish_force > 0 else (-1.0 if squish_force < 0 else (1.0 if snap.steering_angle_deg > 0 else -1.0))
target.squish_force = push_dir * intensity
target.width = 106.0
target.height = 106.0
target.top_lid = 0.08
target.gaze_x = push_dir * 8.0
target.gaze_y = -2.0
target.tilt_y = push_dir * (5.0 + 6.0 * intensity)
target.mouth = MouthGlyph.SMILE
elif self.mood == RoboticMood.MUSIC_GROOVE:
m = snap.music or MusicState()
sway = math.sin(m.groove_phase)
beat = m.beat_pulse
target.color = groove_prism_color(t)
target.width = 108.0
target.height = 112.0
target.gaze_x = sway * 22.0
target.gaze_y = -6.0 - beat * 6.0
target.tilt_y = sway * 12.0
target.bounce_y = -14.0 * beat - abs(sway) * 6.0 - 8.0
target.scale_x = 1.0 + 0.11 * beat
target.scale_y = 1.0 - 0.08 * beat
target.mouth = MouthGlyph.BIG_GRIN
if beat > 0.58:
target.glyph = EyeGlyph.CRESCENT
elif self.mood == RoboticMood.CRUISING_HAPPY:
target.width = 106.0
target.height = 114.0
target.mouth = MouthGlyph.SMILE
target.gaze_x = steer_gaze * 0.35 + self._idle_gaze_x * 0.65 + micro_drift_x
target.gaze_y = self._idle_gaze_y * 0.65
target.tilt_y = self._idle_tilt_y * 0.75 + math.sin(t * 1.6) * 3.0
self._apply_idle_action(target, t)
else: # IDLE_CURIOUS or SPEED_DISPLAY fallback
target.width = 104.0
target.height = 110.0
target.mouth = MouthGlyph.SMILE
target.gaze_x = self._idle_gaze_x + micro_drift_x
target.gaze_y = self._idle_gaze_y
target.tilt_y = self._idle_tilt_y + math.sin(t * 1.4) * 3.0
self._apply_idle_action(target, t)
# Apply natural blink closure to standard rounded-rect eyes
if target.glyph == EyeGlyph.ROUND_RECT and not target.wink_right and blink > 0.0:
target.top_lid = max(target.top_lid, 0.52 * blink)
target.bottom_lid = max(target.bottom_lid, 0.48 * blink)
return target
def _apply_idle_action(self, target: EyeTarget, t: float) -> None:
"""Layer bubbly autonomous micro-behaviors onto normal cruising/idle states."""
if self.idle_action == IdleAction.HAPPY_SQUINT:
target.glyph = EyeGlyph.CRESCENT
target.mouth = MouthGlyph.BIG_GRIN
target.bounce_y = -abs(math.sin(t * 9.0)) * 12.0
elif self.idle_action == IdleAction.CURIOUS_LOOK:
target.gaze_x = self._idle_action_dir * 34.0
target.gaze_y = -6.0
target.tilt_y = self._idle_action_dir * 10.0
target.height = 118.0
elif self.idle_action == IdleAction.CHEEKY_WINK:
target.wink_right = True
target.mouth = MouthGlyph.BIG_GRIN
target.tilt_y = 6.0
target.bounce_y = -8.0
elif self.idle_action == IdleAction.GROOVE_BOB:
target.bounce_y = math.sin(t * 7.2) * 11.0
target.tilt_y = math.sin(t * 3.6) * 8.0
target.mouth = MouthGlyph.BIG_GRIN
def snapshot_from_ui_state(ui_state, alert: Alert | None) -> DrivingSnapshot:
"""Build a DrivingSnapshot safely from ui_state.sm."""
sm = ui_state.sm
cs = sm["carState"]
controls = sm["controlsState"]
dm = sm["driverMonitoringState"]
events = sm["onroadEvents"]
v_cruise_cluster = cs.vCruiseCluster
set_speed_kph = controls.deprecated.vCruise if v_cruise_cluster == 0.0 else v_cruise_cluster
pre_left = any(e.name == EventName.preLaneChangeLeft for e in events)
pre_right = any(e.name == EventName.preLaneChangeRight for e in events)
lane_change = any(e.name == EventName.laneChange for e in events)
lane_blocked = any(e.name == EventName.laneChangeBlocked for e in events)
v_ego_cluster = cs.vEgoCluster
v_ego = v_ego_cluster if v_ego_cluster != 0.0 else cs.vEgo
# Extract pitch, pitch rate, and yaw rate from modelV2 orientation + gyroscope (104 Hz)
yaw_rate = 0.0
pitch_rad = 0.0
pitch_rate = 0.0
if sm.valid.get("modelV2"):
mv2 = sm["modelV2"]
if len(mv2.orientation.y) > 0:
pitch_rad = float(mv2.orientation.y[0])
if len(mv2.orientationRate.y) > 0 and len(mv2.orientationRate.z) > 0:
pitch_rate = float(mv2.orientationRate.y[0])
yaw_rate = float(mv2.orientationRate.z[0])
if sm.valid.get("gyroscope"):
gv = sm["gyroscope"].gyro.v
if len(gv) >= 3:
# Blend crisp high-rate gyro directly with model orientation rate
pitch_rate = 0.5 * pitch_rate + 0.5 * float(gv[1]) if pitch_rate != 0.0 else float(gv[1])
yaw_rate = 0.5 * yaw_rate + 0.5 * float(gv[2]) if yaw_rate != 0.0 else float(gv[2])
return DrivingSnapshot(
started=ui_state.started,
engaged=ui_state.engaged,
status=ui_state.status,
v_ego=max(0.0, float(v_ego)),
a_ego=float(cs.aEgo),
standstill=bool(cs.standstill),
steering_angle_deg=float(cs.steeringAngleDeg),
yaw_rate=yaw_rate,
pitch_rad=pitch_rad,
pitch_rate=pitch_rate,
curvature=float(controls.curvature) if sm.valid.get("controlsState") else 0.0,
set_speed_kph=float(set_speed_kph),
is_metric=bool(ui_state.is_metric),
left_blinker=bool(cs.leftBlinker),
right_blinker=bool(cs.rightBlinker),
left_blindspot=bool(cs.leftBlindspot),
right_blindspot=bool(cs.rightBlindspot),
pre_lane_change_left=pre_left,
pre_lane_change_right=pre_right,
lane_change=lane_change,
lane_change_blocked=lane_blocked,
dm_alert_level=int(dm.alertLevel.raw) if sm.valid["driverMonitoringState"] else 0,
alert=alert,
)
def display_speed_and_set_speed(snap: DrivingSnapshot) -> tuple[int, int | None]:
"""Convert current speed and cruise set speed to display units (mph or km/h)."""
speed_conv = CV.MS_TO_KPH if snap.is_metric else CV.MS_TO_MPH
cur_speed = round(max(0.0, snap.v_ego * speed_conv))
if 0 < snap.set_speed_kph < SET_SPEED_NA:
set_val = snap.set_speed_kph if snap.is_metric else snap.set_speed_kph * KM_TO_MILE
return cur_speed, round(set_val)
return cur_speed, None
@@ -0,0 +1,388 @@
"""
Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors.
This file is part of sunnypilot and is licensed under the MIT License.
See the LICENSE.md file in the root directory for more details.
"""
import math
import pyray as rl
from openpilot.common.filter_simple import BounceFilter, FirstOrderFilter
from openpilot.selfdrive.ui.sunnypilot.mici.onroad.robotic.expressions import (
EyeGlyph,
EyeTarget,
MouthGlyph,
)
from openpilot.system.ui.lib.application import FontWeight, gui_app
class ProceduralFaceRenderer:
"""60 FPS bubbly EMO-inspired procedural vector face renderer for 536x240 MICI OLED."""
EYE_SPACING = 166.0 # distance between left and right eye centers
def __init__(self):
dt = 1.0 / max(gui_app.target_fps, 1)
# Bubbly spring-overshoot filters for juicy EMO-style squash-and-stretch motion
self._w = BounceFilter(104.0, 0.065, dt, bounce=4.2)
self._h = BounceFilter(112.0, 0.065, dt, bounce=4.2)
self._gaze_x = BounceFilter(0.0, 0.075, dt, bounce=3.4)
self._gaze_y = BounceFilter(0.0, 0.075, dt, bounce=3.0)
self._bounce_y = BounceFilter(0.0, 0.055, dt, bounce=4.4)
self._tilt_y = BounceFilter(0.0, 0.075, dt, bounce=3.2)
self._scale_x = BounceFilter(1.0, 0.055, dt, bounce=4.5)
self._scale_y = BounceFilter(1.0, 0.055, dt, bounce=4.5)
self._squish = BounceFilter(0.0, 0.075, dt, bounce=3.6)
self._pitch_y = BounceFilter(0.0, 0.075, dt, bounce=3.0)
# Crisp first-order filters for eyelids, roundness, and smooth color blending
self._roundness = FirstOrderFilter(0.62, 0.08, dt)
self._top_lid = FirstOrderFilter(0.0, 0.032, dt)
self._bottom_lid = FirstOrderFilter(0.0, 0.032, dt)
self._top_slant = FirstOrderFilter(0.0, 0.065, dt)
self._r = FirstOrderFilter(218.0, 0.14, dt)
self._g = FirstOrderFilter(232.0, 0.14, dt)
self._b = FirstOrderFilter(248.0, 0.14, dt)
self._bsm_alpha = FirstOrderFilter(0.0, 0.07, dt)
self._blinker_alpha = FirstOrderFilter(0.0, 0.06, dt)
self._font_semi_bold: rl.Font = gui_app.font(FontWeight.SEMI_BOLD)
def render(self, rect: rl.Rectangle, target: EyeTarget, alpha: float = 1.0, y_shift: float = 0.0) -> None:
if alpha < 0.01:
return
t = rl.get_time()
# Update bubbly & smooth filters
w = max(24.0, self._w.update(target.width) * self._scale_x.update(target.scale_x))
h = max(20.0, self._h.update(target.height) * self._scale_y.update(target.scale_y))
roundness = max(0.15, min(0.85, self._roundness.update(target.roundness)))
top_lid = max(0.0, min(0.95, self._top_lid.update(target.top_lid)))
bottom_lid = max(0.0, min(0.95, self._bottom_lid.update(target.bottom_lid)))
top_slant = self._top_slant.update(target.top_slant)
gaze_x = self._gaze_x.update(target.gaze_x)
gaze_y = self._gaze_y.update(target.gaze_y)
bounce_y = self._bounce_y.update(target.bounce_y)
tilt_y = self._tilt_y.update(target.tilt_y)
squish = max(-1.0, min(1.0, self._squish.update(target.squish_force)))
pitch_y = self._pitch_y.update(target.pitch_offset_y)
squish_abs = abs(squish)
r = max(0, min(255, int(self._r.update(target.color[0]))))
g = max(0, min(255, int(self._g.update(target.color[1]))))
b = max(0, min(255, int(self._b.update(target.color[2]))))
# Optional alert brightness pulse
pulse = 1.0
if target.pulse_speed > 0.0:
pulse = 0.72 + 0.28 * (0.5 + 0.5 * math.sin(t * target.pulse_speed * math.tau))
eff_alpha = max(0.0, min(1.0, alpha * pulse))
core_color = rl.Color(r, g, b, int(255 * eff_alpha))
# Subtle wall-cushion glow when centrifugal force squishes the bot strongly to one side
if squish_abs > 0.35:
wall_a = (squish_abs - 0.35) / 0.65
self._draw_wall_squish_glow(rect, 1 if squish > 0 else -1, core_color, wall_a * eff_alpha)
# Ambient edge accents (blind spot glow, blinker chevrons, boost speed lines)
bsm_a = self._bsm_alpha.update(1.0 if target.blind_spot_side != 0 else 0.0)
if bsm_a > 0.02 and target.blind_spot_side != 0:
self._draw_bsm_edge_glow(rect, target.blind_spot_side, bsm_a * alpha)
blinker_a = self._blinker_alpha.update(1.0 if target.blinker_side != 0 else 0.0)
if blinker_a > 0.02 and target.blinker_side != 0:
self._draw_blinker_indicator(rect, target.blinker_side, blinker_a * alpha, t)
if target.show_speed_lines:
self._draw_speed_lines(rect, core_color, eff_alpha, t)
# Slide the whole face toward the opposite side of the turn under centrifugal force
centrifugal_shift_x = squish * 76.0
cx = rect.x + rect.width / 2.0 + gaze_x + centrifugal_shift_x
cy = rect.y + rect.height / 2.0 - 8.0 + gaze_y + bounce_y + pitch_y + y_shift
# Compress spacing between eyes as the bot gets smooshed against the side wall
spacing = self.EYE_SPACING * (1.0 - 0.24 * squish_abs)
left_cx = cx - spacing / 2.0
right_cx = cx + spacing / 2.0
left_cy = cy - tilt_y
right_cy = cy + tilt_y
# Asymmetric centrifugal wall-squish: outer pressed eye squishes narrower & taller!
left_w_mult = (1.0 - 0.36 * max(0.0, -squish)) * (1.0 - 0.14 * max(0.0, squish))
left_h_mult = (1.0 + 0.16 * max(0.0, -squish)) * (1.0 - 0.05 * max(0.0, squish))
right_w_mult = (1.0 - 0.36 * max(0.0, squish)) * (1.0 - 0.14 * max(0.0, -squish))
right_h_mult = (1.0 + 0.16 * max(0.0, squish)) * (1.0 - 0.05 * max(0.0, -squish))
# Subtle 3D perspective scaling when glancing left/right
left_scale = 1.0 - max(0.0, gaze_x / 210.0)
right_scale = 1.0 + min(0.0, gaze_x / 210.0)
eye_configs = (
(left_cx, left_cy, w * left_scale * left_w_mult, h * left_scale * left_h_mult),
(right_cx, right_cy, w * right_scale * right_w_mult, h * right_scale * right_h_mult),
)
for side_idx, (ecx, ecy, ew, eh) in enumerate(eye_configs):
slant = top_slant if side_idx == 0 else -top_slant
glyph = EyeGlyph.CRESCENT if (side_idx == 1 and target.wink_right) else target.glyph
self._draw_eye(ecx, ecy, ew, eh, roundness, top_lid, bottom_lid, slant, glyph, core_color, eff_alpha, gaze_x, gaze_y, t)
if target.mouth != MouthGlyph.NONE:
self._draw_mouth(cx, cy + h * 0.72, target.mouth, core_color)
if target.show_zzz:
self._draw_floating_zzz(right_cx + w * 0.58, right_cy - h * 0.35, core_color, eff_alpha, t)
if target.show_hearts:
self._draw_floating_mini_hearts(cx, cy - h * 0.58, core_color, eff_alpha, t)
def _draw_wall_squish_glow(self, rect: rl.Rectangle, side: int, color: rl.Color, alpha: float) -> None:
glow_w = 46
edge = rl.Color(color.r, color.g, color.b, int(95 * alpha))
clear = rl.Color(color.r, color.g, color.b, 0)
if side < 0:
rl.draw_rectangle_gradient_h(int(rect.x), int(rect.y), glow_w, int(rect.height), edge, clear)
else:
rl.draw_rectangle_gradient_h(int(rect.x + rect.width - glow_w), int(rect.y), glow_w, int(rect.height), clear, edge)
def _draw_bsm_edge_glow(self, rect: rl.Rectangle, side: int, alpha: float) -> None:
glow_w = 56
amber = rl.Color(255, 160, 30, int(145 * alpha))
clear = rl.Color(255, 160, 30, 0)
if side < 0:
rl.draw_rectangle_gradient_h(int(rect.x), int(rect.y), glow_w, int(rect.height), amber, clear)
else:
rl.draw_rectangle_gradient_h(int(rect.x + rect.width - glow_w), int(rect.y), glow_w, int(rect.height), clear, amber)
def _draw_blinker_indicator(self, rect: rl.Rectangle, side: int, alpha: float, t: float) -> None:
"""Crisp pulsing directional chevron on the left/right edge for turn signals."""
pulse = 0.35 + 0.65 * (0.5 + 0.5 * math.sin(t * 8.4))
col = rl.Color(85, 240, 140, int(235 * pulse * alpha))
glow = rl.Color(85, 240, 140, int(65 * pulse * alpha))
cy = rect.y + rect.height / 2.0
sign = 1.0 if side > 0 else -1.0
base_x = (rect.x + rect.width - 34.0) if side > 0 else (rect.x + 34.0)
for idx in range(2):
ox = base_x - sign * idx * 14.0
p_top = rl.Vector2(ox - sign * 10.0, cy - 18.0)
p_tip = rl.Vector2(ox + sign * 8.0, cy)
p_bot = rl.Vector2(ox - sign * 10.0, cy + 18.0)
rl.draw_line_ex(p_top, p_tip, 9.0, glow)
rl.draw_line_ex(p_tip, p_bot, 9.0, glow)
rl.draw_line_ex(p_top, p_tip, 4.5, col)
rl.draw_line_ex(p_tip, p_bot, 4.5, col)
def _draw_speed_lines(self, rect: rl.Rectangle, color: rl.Color, alpha: float, t: float) -> None:
"""Energetic animated speed streaks on the screen edges during sharp acceleration."""
for i in range(4):
phase = (t * 4.5 + i * 0.25) % 1.0
y = rect.y + 68.0 + i * 44.0
line_len = 26.0 + 22.0 * math.sin(phase * math.pi)
a = int(170 * math.sin(phase * math.pi) * alpha)
col = rl.Color(color.r, color.g, color.b, a)
# Left & right symmetrical streaks
lx = rect.x + 12.0 + (1.0 - phase) * 28.0
rx = rect.x + rect.width - 12.0 - (1.0 - phase) * 28.0
rl.draw_line_ex(rl.Vector2(lx, y), rl.Vector2(lx + line_len, y), 3.5, col)
rl.draw_line_ex(rl.Vector2(rx - line_len, y), rl.Vector2(rx, y), 3.5, col)
def _draw_floating_zzz(self, x: float, y: float, color: rl.Color, alpha: float, t: float) -> None:
"""Softly drifting Zzz bubbles so sleepy/standstill state is continuously animated."""
for idx, ch in enumerate(("z", "Z")):
phase = (t * 0.55 + idx * 0.5) % 1.0
zx = x + phase * 18.0 + math.sin(phase * math.tau) * 4.0
zy = y - phase * 34.0
fade = math.sin(phase * math.pi)
size = 20 + idx * 8
col = rl.Color(color.r, color.g, color.b, int(190 * fade * alpha))
rl.draw_text_ex(self._font_semi_bold, ch, rl.Vector2(zx, zy), size, 0, col)
def _draw_floating_mini_hearts(self, cx: float, y: float, color: rl.Color, alpha: float, t: float) -> None:
"""Floating mini-hearts above the face during pet/bookmark reactions."""
for idx, dx in enumerate((-62.0, 0.0, 62.0)):
phase = (t * 1.4 + idx * 0.33) % 1.0
hx = cx + dx + math.sin(phase * math.tau) * 6.0
hy = y - phase * 26.0
fade = math.sin(phase * math.pi)
col = rl.Color(color.r, color.g, color.b, int(210 * fade * alpha))
self._draw_heart_eye(hx, hy, 8.5, col, fade * alpha, with_glow=False)
def _draw_eye(
self,
cx: float,
cy: float,
w: float,
h: float,
roundness: float,
top_lid: float,
bottom_lid: float,
slant_deg: float,
glyph: EyeGlyph,
color: rl.Color,
alpha: float,
gaze_x: float,
gaze_y: float,
t: float,
) -> None:
if glyph == EyeGlyph.STAR:
self._draw_star_eye(cx, cy, min(w, h) * 0.48, color, alpha, t)
return
if glyph == EyeGlyph.HEART:
self._draw_heart_eye(cx, cy, min(w, h) * 0.48, color, alpha, with_glow=True)
return
if glyph == EyeGlyph.CRESCENT:
self._draw_crescent_eye(cx, cy, w, h, color, alpha)
return
# Silky radial OLED bloom (zero banding, consistent with star & heart eyes)
visible_frac = max(0.25, 1.0 - top_lid - bottom_lid)
bloom_r = max(w, h) * 0.78 * (0.65 + 0.35 * visible_frac)
rl.draw_circle_gradient(
rl.Vector2(cx, cy),
bloom_r,
rl.Color(color.r, color.g, color.b, int(92 * visible_frac * alpha)),
rl.Color(color.r, color.g, color.b, 0),
)
# Crisp eye core
core_rec = rl.Rectangle(cx - w / 2.0, cy - h / 2.0, w, h)
rl.draw_rectangle_rounded(core_rec, min(0.85, roundness), 24, color)
# Glossy dual specular catchlights (centered-dynamic so eyes never appear stuck staring at top-left)
glint_dx = gaze_x * 0.16 + math.sin(t * 3.0) * 1.8
glint_dy = gaze_y * 0.14 + math.cos(t * 2.4) * 1.4
hi_col = rl.Color(255, 255, 255, int(105 * alpha))
rl.draw_rectangle_rounded(
rl.Rectangle(cx - w * 0.14 + glint_dx, cy - h * 0.30 + glint_dy, w * 0.28, h * 0.16),
0.90,
12,
hi_col,
)
rl.draw_circle(
int(cx + w * 0.18 + glint_dx * 0.6),
int(cy + h * 0.22 + glint_dy * 0.6),
max(3.5, min(w, h) * 0.055),
rl.Color(255, 255, 255, int(75 * alpha)),
)
# Sparkle glint inside eyes during sharp acceleration boost
if glyph == EyeGlyph.SPARKLE_BOOST:
self._draw_boost_sparkle(cx, cy, min(w, h) * 0.22, alpha, t)
# Directional chevron glint inside eye during lane changes
if glyph in (EyeGlyph.ARROW_LEFT, EyeGlyph.ARROW_RIGHT):
self._draw_chevron_glint(cx, cy, w * 0.24, glyph == EyeGlyph.ARROW_RIGHT, alpha)
# Laser-alert inner bright core bar
if glyph == EyeGlyph.LASER_ALERT:
inner_col = rl.Color(255, 235, 235, int(215 * alpha))
rl.draw_rectangle_rounded(rl.Rectangle(cx - w * 0.36, cy - 5, w * 0.72, 10), 0.85, 10, inner_col)
# Eyelid masks (pure black polygons over the OLED canvas, tall enough to cleanly clip outer halo)
if top_lid > 0.01 or abs(slant_deg) > 0.5:
lid_h = max(42.0, h * (top_lid + 0.55))
lid_w = w + 80.0
lid_cy = (cy - h / 2.0) + h * top_lid - lid_h / 2.0 - 4.0
rl.draw_rectangle_pro(
rl.Rectangle(cx, lid_cy, lid_w, lid_h),
rl.Vector2(lid_w / 2.0, lid_h / 2.0),
slant_deg,
rl.BLACK,
)
if bottom_lid > 0.01:
lid_h = max(36.0, h * (bottom_lid + 0.45))
lid_w = w + 80.0
lid_cy = (cy + h / 2.0) - h * bottom_lid + lid_h / 2.0 + 4.0
rl.draw_rectangle_pro(
rl.Rectangle(cx, lid_cy, lid_w, lid_h),
rl.Vector2(lid_w / 2.0, lid_h / 2.0),
0.0,
rl.BLACK,
)
def _draw_boost_sparkle(self, cx: float, cy: float, size: float, alpha: float, t: float) -> None:
"""4-point pulsing star sparkle inside eyes during sharp acceleration."""
s = size * (0.85 + 0.25 * math.sin(t * 14.0))
col = rl.Color(255, 255, 255, int(210 * alpha))
rl.draw_line_ex(rl.Vector2(cx - s, cy), rl.Vector2(cx + s, cy), 4.0, col)
rl.draw_line_ex(rl.Vector2(cx, cy - s), rl.Vector2(cx, cy + s), 4.0, col)
def _draw_chevron_glint(self, cx: float, cy: float, size: float, right: bool, alpha: float) -> None:
sign = 1.0 if right else -1.0
col = rl.Color(0, 0, 0, int(135 * alpha))
p_top = rl.Vector2(cx - sign * size * 0.35, cy - size * 0.75)
p_tip = rl.Vector2(cx + sign * size * 0.55, cy)
p_bot = rl.Vector2(cx - sign * size * 0.35, cy + size * 0.75)
rl.draw_line_ex(p_top, p_tip, 7.0, col)
rl.draw_line_ex(p_tip, p_bot, 7.0, col)
def _draw_star_eye(self, cx: float, cy: float, outer_r: float, color: rl.Color, alpha: float, t: float) -> None:
inner_r = outer_r * 0.44
spin = math.sin(t * 7.0) * 0.14 # playful wobble
pts: list[rl.Vector2] = []
for i in range(10):
angle = -math.pi / 2.0 + spin + i * (math.pi / 5.0)
rad = outer_r if i % 2 == 0 else inner_r
pts.append(rl.Vector2(cx + math.cos(angle) * rad, cy + math.sin(angle) * rad))
rl.draw_circle_gradient(
rl.Vector2(cx, cy), outer_r * 1.25,
rl.Color(color.r, color.g, color.b, int(90 * alpha)),
rl.Color(color.r, color.g, color.b, 0),
)
center = rl.Vector2(cx, cy)
for i in range(10):
p1 = pts[i]
p2 = pts[(i + 1) % 10]
rl.draw_triangle(center, p2, p1, color)
def _draw_heart_eye(self, cx: float, cy: float, radius: float, color: rl.Color, alpha: float, with_glow: bool = True) -> None:
"""Seamless, perfectly symmetrical 48-point parametric smooth heart curve."""
if with_glow:
rl.draw_circle_gradient(
rl.Vector2(cx, cy), radius * 1.4,
rl.Color(color.r, color.g, color.b, int(92 * alpha)),
rl.Color(color.r, color.g, color.b, 0),
)
# Classic smooth parametric heart:
# x(t) = 16 sin^3(t), y(t) = -(13 cos(t) - 5 cos(2t) - 2 cos(3t) - cos(4t))
# Normalized so half-width ~= radius; centered vertically around cy
scale = radius / 16.0
n_pts = 48
pts: list[rl.Vector2] = []
for i in range(n_pts):
ang = (i / n_pts) * math.tau
s = math.sin(ang)
hx = 16.0 * (s * s * s)
hy = -(13.0 * math.cos(ang) - 5.0 * math.cos(2.0 * ang) - 2.0 * math.cos(3.0 * ang) - math.cos(4.0 * ang)) - 2.2
pts.append(rl.Vector2(cx + hx * scale, cy + hy * scale))
center = rl.Vector2(cx, cy + radius * 0.05)
for i in range(n_pts):
p1 = pts[i]
p2 = pts[(i + 1) % n_pts]
# Parametric curve runs clockwise in screen coords (y-down), so (center, p2, p1) is CCW
rl.draw_triangle(center, p2, p1, color)
def _draw_crescent_eye(self, cx: float, cy: float, w: float, h: float, color: rl.Color, alpha: float) -> None:
radius = min(w, h) * 0.50
arc_cy = cy + radius * 0.35
glow_col = rl.Color(color.r, color.g, color.b, int(55 * alpha))
rl.draw_ring(rl.Vector2(cx, arc_cy), radius - 22.0, radius + 8.0, 200.0, 340.0, 28, glow_col)
rl.draw_ring(rl.Vector2(cx, arc_cy), radius - 14.0, radius, 202.0, 338.0, 28, color)
def _draw_mouth(self, cx: float, cy: float, mouth: MouthGlyph, color: rl.Color) -> None:
if mouth == MouthGlyph.SMILE:
rl.draw_ring(rl.Vector2(cx, cy - 10.0), 17.0, 23.0, 25.0, 155.0, 20, color)
elif mouth == MouthGlyph.BIG_GRIN:
rl.draw_ring(rl.Vector2(cx, cy - 12.0), 19.0, 26.0, 18.0, 162.0, 24, color)
elif mouth == MouthGlyph.FROWN:
rl.draw_ring(rl.Vector2(cx, cy + 16.0), 17.0, 23.0, 205.0, 335.0, 20, color)
elif mouth == MouthGlyph.SURPRISED:
rl.draw_ring(rl.Vector2(cx, cy + 2.0), 9.0, 15.0, 0.0, 360.0, 24, color)
@@ -0,0 +1,249 @@
"""
Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors.
This file is part of sunnypilot and is licensed under the MIT License.
See the LICENSE.md file in the root directory for more details.
"""
from collections import deque
from dataclasses import dataclass, field
import math
import numpy as np
DEFAULT_SAMPLE_RATE = 16000
FRAME_RATE = 20.0 # micd publishes 800 samples @ 16kHz = 50ms (20 Hz)
FFT_SIZE = 1024 # ~64ms analysis window
NUM_BANDS = 12
HISTORY_FRAMES = 50 # 2.5 seconds of flux/energy history @ 20 Hz
# Tempo autocorrelation lag bounds @ 20 Hz: 7..17 frames -> 70..171 BPM
MIN_TEMPO_LAG = 7
MAX_TEMPO_LAG = 17
# Hysteresis thresholds for stable music detection (rejects road noise & talking)
ENTER_MUSIC_CONF = 0.58
EXIT_MUSIC_CONF = 0.36
MIN_ACTIVE_RMS = 0.012
@dataclass
class MusicState:
is_music: bool = False
confidence: float = 0.0
beat_pulse: float = 0.0 # 0..1 sharp onset with smooth decay
groove_phase: float = 0.0 # radians advancing at estimated tempo
bpm: float = 116.0
energy: float = 0.0 # 0..1 normalized musical loudness
bands: tuple[float, ...] = field(default_factory=lambda: (0.0,) * NUM_BANDS)
class MusicAnalyzer:
"""Low-CPU pure-NumPy cabin music detector, beat tracker, and 12-band equalizer analyzer.
Distinguishes ambient music from car road/wind noise and human speech by combining:
1. Adaptive cabin noise-floor gating
2. Spectral tonality (1 - spectral flatness) to reject broadband road/wind noise
3. Musical bandwidth balance (bass + treble presence) to reject narrowband talking
4. Rhythmic tempo periodicity (spectral flux autocorrelation at 70-171 BPM)
5. Temporal energy continuity (speech has frequent inter-word silences)
"""
def __init__(self, sample_rate: int = DEFAULT_SAMPLE_RATE):
self._sample_rate = sample_rate
self._window = np.hanning(FFT_SIZE).astype(np.float32)
self._ring = np.zeros(FFT_SIZE, dtype=np.float32)
self._prev_mag: np.ndarray | None = None
self._noise_floor: float = 0.008
self._confidence: float = 0.0
self._is_music: bool = False
self._beat_pulse: float = 0.0
self._groove_phase: float = 0.0
self._bpm: float = 116.0
self._energy: float = 0.0
self._bands = np.zeros(NUM_BANDS, dtype=np.float32)
self._flux_hist: deque[float] = deque(maxlen=HISTORY_FRAMES)
self._active_hist: deque[float] = deque(maxlen=HISTORY_FRAMES)
self._bass_flux_hist: deque[float] = deque(maxlen=20)
self._build_frequency_masks(sample_rate)
def _build_frequency_masks(self, sr: int) -> None:
self._sample_rate = sr
freqs = np.fft.rfftfreq(FFT_SIZE, d=1.0 / sr)
self._freqs = freqs
self._bass_mask = (freqs >= 55.0) & (freqs < 230.0)
self._speech_mask = (freqs >= 300.0) & (freqs < 2400.0)
self._treble_mask = (freqs >= 2800.0) & (freqs < min(7600.0, sr * 0.48))
self._tonal_mask = (freqs >= 100.0) & (freqs < 4000.0)
# 12 log-spaced equalizer bands (60 Hz .. 7200 Hz)
edges = np.geomspace(60.0, min(7200.0, sr * 0.47), NUM_BANDS + 1)
self._band_slices: list[tuple[int, int]] = []
for i in range(NUM_BANDS):
lo = int(np.searchsorted(freqs, edges[i]))
hi = max(lo + 1, int(np.searchsorted(freqs, edges[i + 1])))
self._band_slices.append((lo, min(hi, len(freqs))))
@property
def state(self) -> MusicState:
return MusicState(
is_music=self._is_music,
confidence=self._confidence,
beat_pulse=self._beat_pulse,
groove_phase=self._groove_phase,
bpm=self._bpm,
energy=self._energy,
bands=tuple(float(b) for b in self._bands),
)
def step_visual_decay(self, dt: float) -> MusicState:
"""Advance smooth 60 FPS groove phase and beat decay between 20 Hz audio chunks."""
if self._is_music:
rad_per_sec = (self._bpm / 60.0) * math.pi # half-note sway cycle
self._groove_phase = (self._groove_phase + rad_per_sec * dt) % (math.tau * 4.0)
decay = math.exp(-dt * 7.5)
self._beat_pulse *= decay
if not self._is_music:
self._bands *= math.exp(-dt * 6.0)
return self.state
def process_audio_bytes(self, data: bytes, sample_rate: int = DEFAULT_SAMPLE_RATE) -> MusicState:
"""Process a rawAudioData int16 PCM byte buffer from micd."""
if not data:
return self.state
if sample_rate > 0 and sample_rate != self._sample_rate:
self._build_frequency_masks(sample_rate)
samples = np.frombuffer(data, dtype=np.int16).astype(np.float32) / 32768.0
return self.process_samples(samples)
def process_samples(self, samples: np.ndarray) -> MusicState:
"""Analyze a normalized float32 [-1, 1] mono audio chunk (~50 ms)."""
n = len(samples)
if n == 0:
return self.state
# Update rolling FFT window
if n >= FFT_SIZE:
self._ring[:] = samples[-FFT_SIZE:]
else:
self._ring[:-n] = self._ring[n:]
self._ring[-n:] = samples
rms = float(np.sqrt(np.mean(self._ring * self._ring)))
# Slow adaptive cabin noise floor (tracks down quickly, tracks up very slowly)
if rms < self._noise_floor:
self._noise_floor = 0.85 * self._noise_floor + 0.15 * rms
else:
self._noise_floor = 0.996 * self._noise_floor + 0.004 * rms
self._noise_floor = max(0.003, min(0.08, self._noise_floor))
# Gate very quiet / pure-floor frames
above_floor = rms > max(MIN_ACTIVE_RMS, self._noise_floor * 1.45)
self._active_hist.append(1.0 if above_floor else 0.0)
# FFT magnitude spectrum
spec = np.abs(np.fft.rfft(self._ring * self._window)) / (FFT_SIZE * 0.5)
power = spec * spec + 1e-12
# 1. Spectral tonality (1 - flatness): music is tonal/harmonic; road noise is flat
tonal_p = power[self._tonal_mask]
geo_mean = float(np.exp(np.mean(np.log(tonal_p))))
arith_mean = float(np.mean(tonal_p))
flatness = geo_mean / max(arith_mean, 1e-12)
tonality_score = float(np.clip((0.52 - flatness) / 0.36, 0.0, 1.0))
# 2. Musical bandwidth balance: speech is concentrated in 300-2400Hz with weak bass+treble
total_p = float(np.sum(power[1:])) + 1e-12
bass_ratio = float(np.sum(power[self._bass_mask])) / total_p
speech_ratio = float(np.sum(power[self._speech_mask])) / total_p
treble_ratio = float(np.sum(power[self._treble_mask])) / total_p
non_speech_ratio = bass_ratio + treble_ratio
# Penalize narrowband vocal-only energy (speech_ratio > 0.78 and low bass+treble)
bandwidth_score = float(np.clip(non_speech_ratio / 0.34, 0.0, 1.0))
if speech_ratio > 0.80 and bass_ratio < 0.12:
bandwidth_score *= 0.25
# 3. Spectral flux & bass onset flux
if self._prev_mag is None:
flux = 0.0
bass_flux = 0.0
else:
diff = np.maximum(0.0, spec - self._prev_mag)
flux = float(np.sum(diff))
bass_flux = float(np.sum(diff[self._bass_mask]))
self._prev_mag = spec
self._flux_hist.append(flux)
self._bass_flux_hist.append(bass_flux)
# 4. Tempo periodicity via normalized autocorrelation of spectral flux (70-171 BPM)
rhythm_score = 0.0
if len(self._flux_hist) >= MAX_TEMPO_LAG + 12:
arr = np.array(self._flux_hist, dtype=np.float32)
arr_centered = arr - np.mean(arr)
denom = float(np.dot(arr_centered, arr_centered))
if denom > 1e-9:
best_corr = 0.0
best_lag = 10
for lag in range(MIN_TEMPO_LAG, MAX_TEMPO_LAG + 1):
c = float(np.dot(arr_centered[:-lag], arr_centered[lag:])) / denom
if c > best_corr:
best_corr = c
best_lag = lag
rhythm_score = float(np.clip((best_corr - 0.14) / 0.32, 0.0, 1.0))
if best_corr > 0.22:
est_bpm = (60.0 * FRAME_RATE) / best_lag
# Smooth BPM estimate
self._bpm = 0.90 * self._bpm + 0.10 * float(np.clip(est_bpm, 75.0, 170.0))
# 5. Temporal continuity (music fills frames steadily; talking has frequent pauses)
continuity = float(np.mean(self._active_hist)) if self._active_hist else 0.0
continuity_score = float(np.clip((continuity - 0.45) / 0.45, 0.0, 1.0))
# Combined music frame score
if not above_floor:
frame_score = 0.0
else:
frame_score = (
0.30 * tonality_score
+ 0.25 * bandwidth_score
+ 0.30 * rhythm_score
+ 0.15 * continuity_score
)
# Require both harmonic tonality AND either rhythmic lock or rich musical bandwidth
if tonality_score < 0.22 or (rhythm_score < 0.15 and bandwidth_score < 0.45):
frame_score *= 0.35
# Smooth confidence with hysteresis (~1.4s attack, ~2.0s release @ 20 Hz)
alpha = 0.055 if frame_score > self._confidence else 0.035
self._confidence = (1.0 - alpha) * self._confidence + alpha * frame_score
if not self._is_music and self._confidence >= ENTER_MUSIC_CONF:
self._is_music = True
elif self._is_music and self._confidence <= EXIT_MUSIC_CONF:
self._is_music = False
# Beat onset pulse (bass + overall flux spike above rolling mean)
if self._is_music and len(self._bass_flux_hist) >= 6:
bf_mean = float(np.mean(self._bass_flux_hist))
bf_std = float(np.std(self._bass_flux_hist)) + 1e-6
if bass_flux > bf_mean + 0.95 * bf_std and bass_flux > 0.015:
strength = float(np.clip((bass_flux - bf_mean) / (2.2 * bf_std), 0.45, 1.0))
self._beat_pulse = max(self._beat_pulse, strength)
# Normalized energy & 12-band equalizer bars (log-compressed for lush visuals)
self._energy = float(np.clip((rms - self._noise_floor) / max(0.10, self._noise_floor * 4.5), 0.0, 1.0))
for i, (lo, hi) in enumerate(self._band_slices):
band_mag = float(np.sqrt(np.mean(power[lo:hi])))
# Log scale into 0..1 with slight treble tilt for lively equalizer shape
tilt = 1.0 + 0.16 * i
norm = float(np.clip(math.log1p(band_mag * 150.0 * tilt) / 2.0, 0.0, 1.0))
if norm > self._bands[i]:
self._bands[i] = 0.45 * self._bands[i] + 0.55 * norm
else:
self._bands[i] = 0.78 * self._bands[i] + 0.22 * norm
return self.state
@@ -0,0 +1,127 @@
"""
Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors.
This file is part of sunnypilot and is licensed under the MIT License.
See the LICENSE.md file in the root directory for more details.
"""
import math
import pyray as rl
from openpilot.common.filter_simple import FirstOrderFilter
from openpilot.selfdrive.ui.sunnypilot.mici.onroad.robotic.music_analyzer import MusicState, NUM_BANDS
from openpilot.system.ui.lib.application import gui_app
def groove_prism_color(t: float) -> tuple[int, int, int]:
"""Smoothly cycle vibrant OLED-friendly cyan -> aqua -> orchid -> mint hues while grooving."""
# Smooth cosine palette keeping high brightness and pleasant saturation
r = int(125 + 95 * math.sin(t * 0.9 + 2.2))
g = int(195 + 55 * math.sin(t * 0.9 + 0.4))
b = int(215 + 40 * math.sin(t * 0.9 + 4.1))
return (max(50, min(255, r)), max(90, min(255, g)), max(140, min(255, b)))
class MusicVisualizerRenderer:
"""Smooth 60 FPS OLED equalizer bars, bass pulse aura, and floating musical notes."""
def __init__(self):
dt = 1.0 / max(gui_app.target_fps, 1)
self._alpha = FirstOrderFilter(0.0, 0.16, dt)
self._bar_filters = [FirstOrderFilter(0.0, 0.06, dt) for _ in range(NUM_BANDS)]
def render_background(self, rect: rl.Rectangle, music: MusicState, active: bool) -> float:
"""Render smooth ambient bass aura & bottom pill equalizer bars; returns current visualizer alpha."""
alpha = self._alpha.update(1.0 if active else 0.0)
if alpha < 0.01:
return 0.0
t = rl.get_time()
cr, cg, cb = groove_prism_color(t)
# 1. Soft beat-reactive ambient bass aura along bottom center
aura_r = 140.0 + 75.0 * music.beat_pulse + 35.0 * music.energy
aura_alpha = int((42 + 52 * music.beat_pulse) * alpha)
rl.draw_circle_gradient(
rl.Vector2(rect.x + rect.width / 2.0, rect.y + rect.height + 10.0),
aura_r,
rl.Color(cr, cg, cb, aura_alpha),
rl.Color(cr, cg, cb, 0),
)
# 2. Smooth 12-band symmetric pill equalizer along the bottom edge
bar_count = NUM_BANDS
total_w = rect.width - 76.0
gap = 10.0
bar_w = (total_w - gap * (bar_count - 1)) / bar_count
start_x = rect.x + (rect.width - total_w) / 2.0
base_y = rect.y + rect.height - 8.0
max_bar_h = 44.0
for i in range(bar_count):
raw_level = music.bands[i] if i < len(music.bands) else 0.0
# Keep a smooth living wave + subtle beat lift on bass/mid bars
wave = 0.14 + 0.10 * math.sin(t * 5.0 + i * 0.65)
beat_lift = music.beat_pulse * (0.28 if i < 6 else 0.16)
level = self._bar_filters[i].update(min(1.0, max(wave, raw_level + beat_lift)))
bar_h = max(8.0, level * max_bar_h)
bx = start_x + i * (bar_w + gap)
by = base_y - bar_h
# Subtle color gradient across the spectrum (cyan -> violet -> pink)
frac = i / max(1, bar_count - 1)
br = int(min(255, cr * (1.0 - frac * 0.25) + 255 * frac * 0.25))
bg = int(min(255, cg * (1.0 - frac * 0.30) + 120 * frac * 0.30))
bb = int(min(255, cb * 0.85 + 255 * 0.15))
# Soft glow cap on taller bars
if level > 0.35:
rl.draw_circle_gradient(
rl.Vector2(bx + bar_w / 2.0, by + 4.0),
bar_w * 1.15,
rl.Color(br, bg, bb, int(75 * level * alpha)),
rl.Color(br, bg, bb, 0),
)
bar_col = rl.Color(br, bg, bb, int((155 + 90 * level) * alpha))
rl.draw_rectangle_rounded(rl.Rectangle(bx, by, bar_w, bar_h), 0.9, 10, bar_col)
return alpha
def render_foreground_notes(self, rect: rl.Rectangle, music: MusicState, alpha: float) -> None:
"""Draw cute floating vector musical notes on the left and right edges while grooving."""
if alpha < 0.05:
return
t = rl.get_time()
cr, cg, cb = groove_prism_color(t + 1.2)
note_specs = (
(rect.x + 48.0, 0.0, 1.0),
(rect.x + rect.width - 48.0, 0.5, -1.0),
(rect.x + 82.0, 0.28, 0.8),
(rect.x + rect.width - 82.0, 0.76, -0.8),
)
for base_x, phase_off, sway_dir in note_specs:
phase = (t * 0.65 + phase_off) % 1.0
fade = math.sin(phase * math.pi)
nx = base_x + math.sin(phase * math.tau) * 10.0 * sway_dir
ny = rect.y + 150.0 - phase * 98.0
scale = 0.85 + 0.25 * music.beat_pulse
col = rl.Color(cr, cg, cb, int(215 * fade * alpha))
self._draw_eighth_note(nx, ny, 7.5 * scale, col)
def _draw_eighth_note(self, cx: float, cy: float, r: float, color: rl.Color) -> None:
"""Crisp vector eighth-note glyph (♪) — zero font dependency."""
rl.draw_circle(int(cx), int(cy), r * 0.72, color)
stem_x = cx + r * 0.58
stem_top = cy - r * 2.5
rl.draw_line_ex(rl.Vector2(stem_x, cy), rl.Vector2(stem_x, stem_top), 2.8, color)
# Curved flag
rl.draw_line_ex(
rl.Vector2(stem_x, stem_top),
rl.Vector2(stem_x + r * 1.15, stem_top + r * 0.95),
2.8,
color,
)
@@ -0,0 +1,214 @@
"""
Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors.
This file is part of sunnypilot and is licensed under the MIT License.
See the LICENSE.md file in the root directory for more details.
"""
import pyray as rl
from openpilot.cereal import log
from openpilot.common.filter_simple import FirstOrderFilter
from openpilot.selfdrive.ui.mici.onroad.augmented_road_view import BookmarkIcon
from openpilot.selfdrive.ui.sunnypilot.mici.onroad.robotic.alert_overlay import RoboticAlertOverlay
from openpilot.selfdrive.ui.sunnypilot.mici.onroad.robotic.expressions import (
DrivingSnapshot,
RoboticMood,
RoboticMoodEngine,
snapshot_from_ui_state,
)
from openpilot.selfdrive.ui.sunnypilot.mici.onroad.robotic.face_renderer import ProceduralFaceRenderer
from openpilot.selfdrive.ui.sunnypilot.mici.onroad.robotic.music_analyzer import MusicAnalyzer, MusicState
from openpilot.selfdrive.ui.sunnypilot.mici.onroad.robotic.music_visualizer import MusicVisualizerRenderer
from openpilot.selfdrive.ui.sunnypilot.mici.onroad.robotic.speed_arc_renderer import SpeedArcRenderer
from openpilot.selfdrive.ui.sunnypilot.ui_state import OnroadTimerStatus
from openpilot.selfdrive.ui.ui_state import UIStatus, ui_state
from openpilot.system.ui.lib.application import (
FontWeight,
MouseEvent,
MousePos,
TextAlignment,
TextAlignmentVertical,
gui_app,
)
from openpilot.system.ui.widgets import Widget
from openpilot.system.ui.widgets.label import UnifiedLabel
VERTICAL_SWIPE_THRESHOLD = 45.0 # px
class RoboticOnroadView(Widget):
"""Full-screen EMO-inspired Robotic Companion onroad view for MICI (536x240 @ 60 FPS)."""
def __init__(self, bookmark_callback=None):
super().__init__()
self._bookmark_callback = bookmark_callback
self._mood_engine = RoboticMoodEngine()
self._face_renderer = ProceduralFaceRenderer()
self._speed_renderer = SpeedArcRenderer()
self._alert_overlay = RoboticAlertOverlay()
self._music_analyzer = MusicAnalyzer()
self._music_visualizer = MusicVisualizerRenderer()
self._bookmark_icon = BookmarkIcon(self._on_bookmark_triggered)
dt = 1.0 / max(gui_app.target_fps, 1)
self._speed_blend = FirstOrderFilter(0.0, 0.08, dt)
# Vertical swipe tracking (up = speed peek, down = pet robot)
self._touch_start_y: float = 0.0
self._touch_start_x: float = 0.0
self._vertical_swipe_handled: bool = False
self._offroad_label = UnifiedLabel(
"start the car to\nuse sunnypilot",
54,
FontWeight.DISPLAY,
text_color=rl.Color(255, 255, 255, int(255 * 0.9)),
alignment=TextAlignment.CENTER,
alignment_vertical=TextAlignmentVertical.MIDDLE,
)
def _on_bookmark_triggered(self) -> None:
self._mood_engine.trigger_love(wink=True)
if self._bookmark_callback is not None:
self._bookmark_callback()
def is_swiping_left(self) -> bool:
"""Match AugmentedRoadView API so MiciMainLayout disables horizontal scroller during bookmark swipe."""
return self._bookmark_icon.is_swiping_left()
def _update_state(self) -> None:
super()._update_state()
if ui_state.panda_type == log.PandaState.PandaType.unknown:
self._offroad_label.set_text("system booting")
elif ui_state.ignition and not ui_state.started:
self._offroad_label.set_text("openpilot can't start\ncheck alerts")
else:
self._offroad_label.set_text("start the car to\nuse sunnypilot")
def _handle_mouse_event(self, mouse_event: MouseEvent) -> None:
if ui_state.started:
if mouse_event.left_pressed:
self._touch_start_x = mouse_event.pos.x
self._touch_start_y = mouse_event.pos.y
self._vertical_swipe_handled = False
elif mouse_event.left_down and not self._vertical_swipe_handled:
dx = abs(mouse_event.pos.x - self._touch_start_x)
dy = mouse_event.pos.y - self._touch_start_y
if abs(dy) > VERTICAL_SWIPE_THRESHOLD and abs(dy) > dx * 1.4:
self._vertical_swipe_handled = True
if dy < 0:
self._mood_engine.trigger_speed_peek()
else:
self._mood_engine.trigger_love()
self._bookmark_icon._handle_mouse_event(mouse_event)
super()._handle_mouse_event(mouse_event)
def _handle_mouse_release(self, mouse_pos: MousePos) -> None:
if self._vertical_swipe_handled:
self._vertical_swipe_handled = False
return
if not self._bookmark_icon.interacting():
super()._handle_mouse_release(mouse_pos)
def _render(self, _) -> None:
rl.draw_rectangle_rec(self.rect, rl.BLACK)
if not ui_state.started:
# Keep subtle animated sleepy eyes behind the offroad message so the screen is never static
sleepy_snap = DrivingSnapshot(started=False, standstill=True)
eye_target = self._mood_engine.update(sleepy_snap)
self._face_renderer.render(self.rect, eye_target, alpha=0.28, y_shift=16.0)
self._offroad_label.render(self._rect)
return
alert = self._alert_overlay.get_alert()
if ui_state.sm.updated["rawAudioData"] and alert is None:
raw_audio = ui_state.sm["rawAudioData"]
self._music_analyzer.process_audio_bytes(raw_audio.data, int(raw_audio.sampleRate))
music_state = self._music_analyzer.step_visual_decay(1.0 / max(gui_app.target_fps, 1))
snap = snapshot_from_ui_state(ui_state, alert)
snap.music = music_state
self._render_from_snapshot(snap, alert)
self._bookmark_icon.render(self.rect)
def _render_from_snapshot(self, snap: DrivingSnapshot, alert) -> None:
eye_target = self._mood_engine.update(snap)
speed_alpha = self._speed_blend.update(1.0 if self._mood_engine.showing_speed else 0.0)
face_alpha = 1.0 - speed_alpha
# Shift eyes slightly upward when a bottom alert banner or music equalizer is visible
grooving = self._mood_engine.mood == RoboticMood.MUSIC_GROOVE and alert is None
alert_shift = -26.0 if alert is not None else (-14.0 if grooving else 0.0)
music_state = snap.music or MusicState()
viz_alpha = 0.0
if face_alpha > 0.01:
viz_alpha = self._music_visualizer.render_background(self.rect, music_state, active=grooving)
self._face_renderer.render(self.rect, eye_target, alpha=face_alpha, y_shift=alert_shift)
if viz_alpha > 0.05:
self._music_visualizer.render_foreground_notes(self.rect, music_state, alpha=viz_alpha * face_alpha)
if alert is None:
self._speed_renderer.render_corner_badge(self.rect, snap, alpha=face_alpha)
if speed_alpha > 0.01:
self._speed_renderer.render_speed_mode(
self.rect,
snap,
alpha=speed_alpha,
cruising_smoothly=self._mood_engine.cruising_smoothly,
reason=self._mood_engine.speed_reason,
)
self._alert_overlay.render(self.rect, alert)
def show_event(self) -> None:
if gui_app.sunnypilot_ui():
ui_state.reset_onroad_sleep_timer(OnroadTimerStatus.RESUME)
def hide_event(self) -> None:
if gui_app.sunnypilot_ui():
ui_state.reset_onroad_sleep_timer(OnroadTimerStatus.PAUSE)
if __name__ == "__main__":
from openpilot.selfdrive.ui.mici.onroad.alert_renderer import Alert
gui_app.init_window("MICI Robotic Companion Preview")
view = RoboticOnroadView()
view.set_rect(rl.Rectangle(0, 0, gui_app.width, gui_app.height))
snap = DrivingSnapshot(started=True, engaged=True, status=UIStatus.ENGAGED, v_ego=29.0, set_speed_kph=105.0)
print("Keys: [1] Engaged [2] MADS [3] Disengaged [4] Speed Peek [5] Stars [6] Love [7] Prompt [8] Critical [9] Pout [Left/Right] Steer")
for _ in gui_app.render():
if rl.is_key_pressed(rl.KeyboardKey.KEY_ONE):
snap = DrivingSnapshot(started=True, engaged=True, status=UIStatus.ENGAGED, v_ego=29.0, set_speed_kph=105.0)
elif rl.is_key_pressed(rl.KeyboardKey.KEY_TWO):
snap = DrivingSnapshot(started=True, engaged=True, status=UIStatus.LAT_ONLY, v_ego=20.0, set_speed_kph=90.0)
elif rl.is_key_pressed(rl.KeyboardKey.KEY_THREE):
snap = DrivingSnapshot(started=True, engaged=False, status=UIStatus.DISENGAGED, v_ego=15.0)
elif rl.is_key_pressed(rl.KeyboardKey.KEY_FOUR):
view._mood_engine.trigger_speed_peek()
elif rl.is_key_pressed(rl.KeyboardKey.KEY_FIVE):
view._mood_engine.trigger_startled()
elif rl.is_key_pressed(rl.KeyboardKey.KEY_SIX):
view._mood_engine.trigger_love()
elif rl.is_key_pressed(rl.KeyboardKey.KEY_SEVEN):
snap.alert = Alert("Pay Attention", "Eyes on road", status=log.SelfdriveState.AlertStatus.userPrompt)
elif rl.is_key_pressed(rl.KeyboardKey.KEY_EIGHT):
snap.alert = Alert("TAKE CONTROL IMMEDIATELY", "Steering Required", status=log.SelfdriveState.AlertStatus.critical)
elif rl.is_key_pressed(rl.KeyboardKey.KEY_NINE):
snap = DrivingSnapshot(started=True, engaged=True, status=UIStatus.ENGAGED, standstill=True)
elif rl.is_key_down(rl.KeyboardKey.KEY_LEFT):
snap.steering_angle_deg = 30.0
elif rl.is_key_down(rl.KeyboardKey.KEY_RIGHT):
snap.steering_angle_deg = -30.0
else:
snap.steering_angle_deg = 0.0
rl.draw_rectangle_rec(view.rect, rl.BLACK)
view._render_from_snapshot(snap, snap.alert)
@@ -0,0 +1,218 @@
"""
Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors.
This file is part of sunnypilot and is licensed under the MIT License.
See the LICENSE.md file in the root directory for more details.
"""
import math
import pyray as rl
from openpilot.common.filter_simple import BounceFilter
from openpilot.selfdrive.ui.sunnypilot.mici.onroad.robotic.expressions import (
DrivingSnapshot,
PALETTE,
display_speed_and_set_speed,
)
from openpilot.selfdrive.ui.ui_state import UIStatus
from openpilot.system.ui.lib.application import FontWeight, gui_app
from openpilot.system.ui.lib.multilang import tr
from openpilot.system.ui.lib.text_measure import measure_text_cached
class SpeedArcRenderer:
"""Reference-video-inspired color-coded speed + curved arc gauge and subtle Set-Speed badge."""
SPEED_FONT_SIZE = 114
UNIT_FONT_SIZE = 24
BADGE_SPEED_FONT_SIZE = 32
def __init__(self):
dt = 1.0 / max(gui_app.target_fps, 1)
self._font_display: rl.Font = gui_app.font(FontWeight.DISPLAY)
self._font_semi_bold: rl.Font = gui_app.font(FontWeight.SEMI_BOLD)
self._font_medium: rl.Font = gui_app.font(FontWeight.MEDIUM)
self._arc_progress = BounceFilter(0.0, 0.11, dt, bounce=2.4)
def _speed_color(self, snap: DrivingSnapshot) -> tuple[int, int, int]:
if snap.status == UIStatus.OVERRIDE or snap.a_ego > 1.8:
return (255, 205, 65) # Warm yellow/amber
if snap.status == UIStatus.ENGAGED:
return (85, 238, 150) # Vibrant green
if snap.status == UIStatus.LAT_ONLY:
return PALETTE["lat_only"]
return (240, 245, 255) # Crisp white
def render_speed_mode(
self,
rect: rl.Rectangle,
snap: DrivingSnapshot,
alpha: float,
cruising_smoothly: bool,
reason: str,
) -> None:
if alpha < 0.01:
return
t = rl.get_time()
cur_speed, set_speed = display_speed_and_set_speed(snap)
sr, sg, sb = self._speed_color(snap)
speed_color = rl.Color(sr, sg, sb, int(255 * alpha))
sub_color = rl.Color(255, 255, 255, int(195 * alpha))
cx = rect.x + rect.width / 2.0
# Subtle breathing float so speed mode is alive and never frozen
float_y = math.sin(t * 2.2) * 2.0
# Top accent above speed: MAX set-speed pill or gently pulsing heart
if reason == "set_speed" and set_speed is not None:
pill_text = f"{tr('MAX')} {set_speed}"
pill_sz = measure_text_cached(self._font_semi_bold, pill_text, 26)
pill_w = pill_sz.x + 28
pill_h = 34
pill_rect = rl.Rectangle(cx - pill_w / 2.0, rect.y + 14 + float_y * 0.5, pill_w, pill_h)
rl.draw_rectangle_rounded(pill_rect, 0.5, 14, rl.Color(sr, sg, sb, int(48 * alpha)))
rl.draw_rectangle_rounded_lines_ex(pill_rect, 0.5, 14, 2.0, rl.Color(sr, sg, sb, int(180 * alpha)))
rl.draw_text_ex(
self._font_semi_bold,
pill_text,
rl.Vector2(cx - pill_sz.x / 2.0, pill_rect.y + (pill_h - pill_sz.y) / 2.0),
26,
0,
speed_color,
)
elif cruising_smoothly:
heart_r = 10.0 * (1.0 + 0.10 * math.sin(t * 4.5))
self._draw_tiny_heart(cx, rect.y + 30 + float_y * 0.5, heart_r, rl.Color(255, 118, 168, int(240 * alpha)))
elif set_speed is not None:
max_lbl = f"{tr('MAX')} {set_speed}"
lbl_sz = measure_text_cached(self._font_medium, max_lbl, self.UNIT_FONT_SIZE)
rl.draw_text_ex(
self._font_medium,
max_lbl,
rl.Vector2(cx - lbl_sz.x / 2.0, rect.y + 18 + float_y * 0.5),
self.UNIT_FONT_SIZE,
0,
sub_color,
)
# Big centered speed number
speed_text = str(cur_speed)
speed_sz = measure_text_cached(self._font_display, speed_text, self.SPEED_FONT_SIZE)
speed_y = rect.y + rect.height / 2.0 - speed_sz.y / 2.0 - 8.0 + float_y
rl.draw_text_ex(
self._font_display,
speed_text,
rl.Vector2(cx - speed_sz.x / 2.0, speed_y),
self.SPEED_FONT_SIZE,
0,
speed_color,
)
# Unit beside speed (small & subtle)
unit_text = tr("km/h") if snap.is_metric else tr("mph")
rl.draw_text_ex(
self._font_medium,
unit_text,
rl.Vector2(cx + speed_sz.x / 2.0 + 10.0, speed_y + speed_sz.y - 34.0),
self.UNIT_FONT_SIZE,
0,
rl.Color(255, 255, 255, int(150 * alpha)),
)
# Curved arc speedometer gauge underneath (matches reference video)
max_ref = float(set_speed) if (set_speed is not None and set_speed > 0) else (130.0 if snap.is_metric else 85.0)
raw_frac = max(0.0, min(1.0, cur_speed / max_ref))
frac = max(0.0, min(1.0, self._arc_progress.update(raw_frac)))
arc_center = rl.Vector2(cx, rect.y + rect.height + 74.0)
inner_r = 104.0
outer_r = 114.0
mid_r = (inner_r + outer_r) / 2.0
cap_r = (outer_r - inner_r) / 2.0
start_deg = 228.0
end_deg = 312.0
span_deg = end_deg - start_deg
# Track background arc with rounded caps
track_col = rl.Color(255, 255, 255, int(45 * alpha))
rl.draw_ring(arc_center, inner_r, outer_r, start_deg, end_deg, 32, track_col)
for deg in (start_deg, end_deg):
rad = math.radians(deg)
rl.draw_circle(int(arc_center.x + math.cos(rad) * mid_r), int(arc_center.y + math.sin(rad) * mid_r), cap_r, track_col)
# Active glowing arc + bright animated tip pip
if frac > 0.01:
active_end = start_deg + span_deg * frac
glow_pulse = 0.78 + 0.22 * math.sin(t * 3.5)
rl.draw_ring(
arc_center,
inner_r - 4.0,
outer_r + 4.0,
start_deg,
active_end,
32,
rl.Color(sr, sg, sb, int(65 * glow_pulse * alpha)),
)
rl.draw_ring(arc_center, inner_r, outer_r, start_deg, active_end, 32, speed_color)
# Rounded start cap & bright glowing tip pip
s_rad = math.radians(start_deg)
e_rad = math.radians(active_end)
rl.draw_circle(int(arc_center.x + math.cos(s_rad) * mid_r), int(arc_center.y + math.sin(s_rad) * mid_r), cap_r, speed_color)
tip_x = arc_center.x + math.cos(e_rad) * mid_r
tip_y = arc_center.y + math.sin(e_rad) * mid_r
rl.draw_circle_gradient(
rl.Vector2(tip_x, tip_y),
14.0,
rl.Color(255, 255, 255, int(140 * glow_pulse * alpha)),
rl.Color(sr, sg, sb, 0),
)
rl.draw_circle(int(tip_x), int(tip_y), cap_r + 1.5, rl.Color(255, 255, 255, int(235 * alpha)))
def render_corner_badge(self, rect: rl.Rectangle, snap: DrivingSnapshot, alpha: float) -> None:
"""Subtle top-left Set-Speed / engagement pill visible during normal hero-face mode."""
if alpha < 0.01:
return
t = rl.get_time()
_, set_speed = display_speed_and_set_speed(snap)
sr, sg, sb = self._speed_color(snap)
dot_pulse = 0.72 + 0.28 * math.sin(t * 3.0)
x = rect.x + 16.0
y = rect.y + 12.0
if set_speed is not None:
text = str(set_speed)
sz = measure_text_cached(self._font_semi_bold, text, self.BADGE_SPEED_FONT_SIZE)
pill_w = sz.x + 48.0
pill_h = 38.0
pill_rec = rl.Rectangle(x, y, pill_w, pill_h)
rl.draw_rectangle_rounded(pill_rec, 0.5, 14, rl.Color(255, 255, 255, int(22 * alpha)))
rl.draw_rectangle_rounded_lines_ex(pill_rec, 0.5, 14, 1.5, rl.Color(255, 255, 255, int(35 * alpha)))
rl.draw_circle(int(x + 16), int(y + pill_h / 2.0), 5.0, rl.Color(sr, sg, sb, int(235 * dot_pulse * alpha)))
rl.draw_text_ex(
self._font_semi_bold,
text,
rl.Vector2(x + 28.0, y + (pill_h - sz.y) / 2.0),
self.BADGE_SPEED_FONT_SIZE,
0,
rl.Color(255, 255, 255, int(210 * alpha)),
)
else:
rl.draw_circle(int(x + 10), int(y + 12), 5.5, rl.Color(sr, sg, sb, int(200 * dot_pulse * alpha)))
def _draw_tiny_heart(self, cx: float, cy: float, radius: float, color: rl.Color) -> None:
scale = radius / 16.0
n_pts = 32
pts: list[rl.Vector2] = []
for i in range(n_pts):
ang = (i / n_pts) * math.tau
s = math.sin(ang)
hx = 16.0 * (s * s * s)
hy = -(13.0 * math.cos(ang) - 5.0 * math.cos(2.0 * ang) - 2.0 * math.cos(3.0 * ang) - math.cos(4.0 * ang)) - 2.2
pts.append(rl.Vector2(cx + hx * scale, cy + hy * scale))
center = rl.Vector2(cx, cy + radius * 0.05)
for i in range(n_pts):
rl.draw_triangle(center, pts[(i + 1) % n_pts], pts[i], color)
@@ -8,6 +8,7 @@ from openpilot.common.filter_simple import FirstOrderFilter
from openpilot.selfdrive.ui.ui_state import ui_state
from openpilot.selfdrive.ui.sunnypilot.onroad.blendful import BlendfulRenderer
from openpilot.selfdrive.ui.sunnypilot.onroad.chevron_metrics import ChevronMetrics
from openpilot.selfdrive.ui.sunnypilot.onroad.radar_tracks import RadarTracks
from openpilot.selfdrive.ui.sunnypilot.onroad.rainbow_path import RainbowPath
from openpilot.selfdrive.ui.sunnypilot.ui_state import UIStateSP
from openpilot.system.ui.lib.application import gui_app
@@ -17,6 +18,7 @@ class ModelRendererSP:
def __init__(self):
self.rainbow_path = RainbowPath()
self.chevron_metrics = ChevronMetrics()
self.radar_tracks = RadarTracks()
self.blendful = BlendfulRenderer(readout=False)
self._width_filter = FirstOrderFilter(0.9, 0.1, 1 / gui_app.target_fps)
@@ -0,0 +1,193 @@
"""
Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors.
This file is part of sunnypilot and is licensed under the MIT License.
See the LICENSE.md file in the root directory for more details.
"""
from dataclasses import dataclass
import math
import pyray as rl
from opendbc.car.hyundai.radar_interface import RADAR_235_248, RADAR_3A5_3C4
NEUTRAL_COLOR = (255, 255, 255)
DBC_MOVING_COLOR = (190, 125, 255)
DBC_UNKNOWN_COLOR = (154, 168, 184)
DBC_MOTION_STATIONARY = 1
DBC_MOTION_MOVING = 2
LEAD_TRACK_COLORS = (
rl.Color(255, 215, 0, 255),
rl.Color(255, 140, 0, 220),
)
@dataclass(frozen=True)
class ProjectedRadarTrack:
x: float
y: float
radius: float
color: object
source_index: int
camera_object: bool
track_id: int
def is_preferred_radar_source(source) -> bool:
return source.startAddress == RADAR_3A5_3C4.start_addr and source.endAddress == RADAR_3A5_3C4.end_addr
def radar_source_sort_key(source) -> tuple[bool, int, int, int]:
return (
not is_preferred_radar_source(source),
int(source.startAddress),
int(source.endAddress),
int(source.bus),
)
def sorted_radar_sources(live_tracks):
return sorted(live_tracks.trackSources, key=radar_source_sort_key)
def radar_track_source_index(track, sources) -> int:
address = int(track.sourceAddress)
bus = int(track.sourceBus)
if address != 0:
return next((
index for index, source in enumerate(sources)
if source.startAddress <= address <= source.endAddress and source.bus == bus
), 0)
return 0
def is_camera_object_source(source) -> bool:
return source.startAddress == RADAR_235_248.start_addr and source.endAddress == RADAR_235_248.end_addr
def radar_track_source(track, sources):
address = int(track.sourceAddress)
bus = int(track.sourceBus)
if address == 0:
return None
return next((
source for source in sources
if source.startAddress <= address <= source.endAddress and source.bus == bus
), None)
def draw_radar_source_marker(center: rl.Vector2, radius: float, color: rl.Color, source_index: int,
camera_object: bool = False) -> None:
if camera_object:
rl.draw_poly(center, 3, radius, -90.0, color)
return
if source_index <= 0:
rl.draw_circle(int(center.x), int(center.y), radius, color)
return
sides = (4, 3, 5, 6)[(source_index - 1) % 4]
rotation = 45.0 if sides == 4 else -90.0
rl.draw_poly(center, sides, radius, rotation, color)
def radar_track_display(motion_state: int) -> tuple[rl.Color, bool]:
"""Color tracks exclusively from the radar's DBC motion classification."""
if motion_state == DBC_MOTION_STATIONARY:
return rl.Color(*NEUTRAL_COLOR, 255), True
if motion_state == DBC_MOTION_MOVING:
return rl.Color(*DBC_MOVING_COLOR, 255), False
return rl.Color(*DBC_UNKNOWN_COLOR, 255), False
def radar_lead_track_colors(radar_state) -> dict[int, rl.Color]:
highlighted_tracks = {}
if radar_state is None:
return highlighted_tracks
for lead, color in zip((radar_state.leadOne, radar_state.leadTwo), LEAD_TRACK_COLORS, strict=True):
if lead.present and lead.radar and lead.radarTrackId >= 0:
highlighted_tracks.setdefault(int(lead.radarTrackId), color)
return highlighted_tracks
def draw_radar_lead_connectors(lead_vehicles, matched_positions, highlighted_tracks, screen_offset=(0, 0)) -> None:
for lead in lead_vehicles:
if not lead.radar or lead.position is None or lead.radar_track_id not in matched_positions:
continue
radar_position = matched_positions[lead.radar_track_id]
lead_position = (lead.position[0] + screen_offset[0], lead.position[1] + screen_offset[1])
if math.dist(lead_position, radar_position) < 4:
continue
rl.draw_line_ex(
rl.Vector2(*lead_position), rl.Vector2(*radar_position), 2,
highlighted_tracks[lead.radar_track_id],
)
class RadarTracks:
def __init__(self):
self._projected_tracks: tuple[ProjectedRadarTrack, ...] = ()
self._projection_initialized = False
@property
def projection_initialized(self) -> bool:
return self._projection_initialized
def clear_projection(self) -> None:
self._projected_tracks = ()
self._projection_initialized = False
def update_radar_tracks(self, live_tracks, map_to_screen, path_offset_z, track_size=7) -> None:
projected_tracks = []
sources = sorted_radar_sources(live_tracks)
for track in live_tracks.points:
d_rel, y_rel, v_rel = track.dRel, track.yRel, track.vRel
if not (math.isfinite(d_rel) and math.isfinite(y_rel) and math.isfinite(v_rel)):
continue
motion_state = int(track.motionState)
if motion_state not in (DBC_MOTION_STATIONARY, DBC_MOTION_MOVING):
continue
pt = map_to_screen(d_rel, -y_rel, path_offset_z)
if pt is None:
continue
color, stationary = radar_track_display(motion_state)
radius = max(1, track_size - 5) if stationary else track_size
source = radar_track_source(track, sources)
projected_tracks.append(ProjectedRadarTrack(
x=pt[0],
y=pt[1],
radius=radius,
color=color,
source_index=radar_track_source_index(track, sources),
camera_object=source is not None and is_camera_object_source(source),
track_id=int(track.trackId),
))
self._projected_tracks = tuple(projected_tracks)
self._projection_initialized = True
def draw_cached_radar_tracks(self, screen_offset=(0, 0), highlighted_tracks=None):
highlighted_tracks = highlighted_tracks or {}
highlighted_positions = {}
for track in self._projected_tracks:
x, y = track.x + screen_offset[0], track.y + screen_offset[1]
highlight_color = highlighted_tracks.get(track.track_id)
if highlight_color is not None:
center = rl.Vector2(int(x), int(y))
rl.draw_ring(center, track.radius + 2, track.radius + 5, 0, 360, 24, highlight_color)
highlighted_positions[track.track_id] = (x, y)
draw_radar_source_marker(
rl.Vector2(x, y), track.radius, track.color, track.source_index, track.camera_object,
)
return highlighted_positions
def draw_radar_tracks(self, live_tracks, map_to_screen, path_offset_z, track_size=7, screen_offset=(0, 0), v_ego=0.0,
highlighted_tracks=None):
self.update_radar_tracks(live_tracks, map_to_screen, path_offset_z, track_size)
return self.draw_cached_radar_tracks(screen_offset, highlighted_tracks)
@@ -36,7 +36,8 @@ class UIStateSP:
self.is_sp_release: bool = self.params.get_bool("IsReleaseSpBranch")
self.sm_services_ext = [
"modelManagerSP", "selfdriveStateSP", "longitudinalPlanSP", "backupManagerSP",
"lateralTorqueParameters", "carStateSP", "liveMapDataSP", "carParamsSP", "lateralDelay", "modelDataV2SP"
"lateralTorqueParameters", "carStateSP", "liveMapDataSP", "carParamsSP", "lateralDelay", "modelDataV2SP",
"gyroscope",
]
self.sunnylink_state = SunnylinkState()
@@ -51,7 +52,9 @@ class UIStateSP:
self.chevron_metrics = None
self.custom_interactive_timeout: int = 0
self.developer_ui = None
self.draw_radar_tracks: bool = self.params.get_bool("DrawRadarTracks")
self.hide_v_ego_ui: bool = False
self.mici_robotic_ui: bool = self.params.get_bool("MiciRoboticUI")
self.onroad_brightness: int = 0
self.onroad_brightness_timer: int = 0
self.onroad_brightness_timer_param: int = 0
@@ -175,7 +178,9 @@ class UIStateSP:
self.chevron_metrics = self.params.get("ChevronInfo")
self.custom_interactive_timeout = self.params.get("InteractivityTimeout", return_default=True)
self.developer_ui = self.params.get("DevUIInfo")
self.draw_radar_tracks = self.params.get_bool("DrawRadarTracks")
self.hide_v_ego_ui = self.params.get_bool("HideVEgoUI")
self.mici_robotic_ui = self.params.get_bool("MiciRoboticUI")
self.onroad_brightness = int(float(self.params.get("OnroadScreenOffBrightness", return_default=True)))
self.onroad_brightness_timer_param = self.params.get("OnroadScreenOffTimer", return_default=True)
self.rainbow_path = self.params.get_bool("RainbowMode")
+86 -1
View File
@@ -1,10 +1,13 @@
import os
import threading
import time
import wave
from openpilot.common.test import OpenpilotTestCase
from openpilot.cereal import log, messaging
from openpilot.cereal.messaging import SubMaster, PubMaster
from openpilot.selfdrive.ui.soundd import SELFDRIVE_STATE_TIMEOUT, check_selfdrive_timeout_alert
from openpilot.selfdrive.ui.soundd import SAMPLE_RATE, SELFDRIVE_STATE_TIMEOUT, Soundd, check_selfdrive_timeout_alert
from openpilot.sunnypilot.selfdrive.ui.robotic_sounds import ROBOTIC_SOUND_FILES, ROBOTIC_SOUNDS_DIR, RoboticSoundPack
AudibleAlert = log.SelfdriveState.AudibleAlert
@@ -56,4 +59,86 @@ class TestSoundd(OpenpilotTestCase):
assert check_selfdrive_timeout_alert(sm)
def test_robotic_sound_pack_wav_formats(self):
for alert_id, filename in ROBOTIC_SOUND_FILES.items():
path = os.path.join(ROBOTIC_SOUNDS_DIR, filename)
assert os.path.exists(path), f"Missing robotic sound for {alert_id}: {path}"
with wave.open(path, "r") as wf:
assert wf.getnchannels() == 1, f"{filename} must be mono"
assert wf.getsampwidth() == 2, f"{filename} must be 16-bit PCM"
assert wf.getframerate() == SAMPLE_RATE, f"{filename} must be {SAMPLE_RATE} Hz"
assert wf.getnframes() > 0, f"{filename} must not be empty"
def test_robotic_sound_pack_switching_and_quiet_mode(self):
class _FakeParams:
def __init__(self):
self.vals = {"MiciRoboticUI": False, "QuietMode": False}
def get_bool(self, key: str) -> bool:
return self.vals.get(key, False)
fake_params = _FakeParams()
pack = RoboticSoundPack(fake_params, SAMPLE_RATE)
pack.load()
assert set(ROBOTIC_SOUND_FILES).issubset(pack.sounds)
soundd = Soundd.__new__(Soundd)
soundd.params = fake_params
soundd.enabled = False
soundd._frame = 0
soundd.robotic_sound_pack = pack
soundd.load_sounds()
soundd.current_alert = AudibleAlert.engage
soundd.current_volume = 1.0
soundd.current_sound_frame = 0
soundd.pending_stop = False
# Default buffer used when MiciRoboticUI is False
buf_default = soundd.robotic_sound_pack.get_buffer(AudibleAlert.engage, soundd.loaded_sounds)
assert buf_default is soundd.loaded_sounds[AudibleAlert.engage]
# Switching MiciRoboticUI to True swaps buffer to robotic sound
fake_params.vals["MiciRoboticUI"] = True
assert pack.refresh_param() is True
buf_robotic = soundd.robotic_sound_pack.get_buffer(AudibleAlert.engage, soundd.loaded_sounds)
assert buf_robotic is pack.sounds[AudibleAlert.engage]
assert buf_robotic is not buf_default
# QuietMode still suppresses non-critical robotic engage chirp
soundd.enabled = True
assert not soundd.should_play_sound(AudibleAlert.engage)
assert soundd.should_play_sound(AudibleAlert.warningImmediate)
def test_robotic_sound_pack_lfs_fallback_and_reactive_chirps(self):
from types import SimpleNamespace
from openpilot.sunnypilot.selfdrive.ui.robotic_sounds import (
CHIRP_BOOST,
CHIRP_SPEED_UP,
CHIRP_STARTLED,
REACTIVE_CHIRP_IDS,
)
class _FakeParams:
def get_bool(self, key: str) -> bool:
return key == "MiciRoboticUI"
pack = RoboticSoundPack(_FakeParams(), SAMPLE_RATE)
pack.load()
for cid in REACTIVE_CHIRP_IDS:
assert cid in pack.sounds and len(pack.sounds[cid]) > 0
class _FakeSM:
def __init__(self, v_cruise=100.0, a_ego=0.0):
self.updated = {"carState": True, "userBookmark": False, "bookmarkButton": False}
self.valid = {"controlsState": False}
self._cs = SimpleNamespace(vCruiseCluster=v_cruise, leftBlinker=False, rightBlinker=False, standstill=False, aEgo=a_ego)
def __getitem__(self, key):
return self._cs
assert pack.detect_reactive_chirp(_FakeSM(100.0, 0.0), now=10.0) is None # first sample seeds prev_set_speed
assert pack.detect_reactive_chirp(_FakeSM(110.0, 0.0), now=11.0) == CHIRP_SPEED_UP
assert pack.detect_reactive_chirp(_FakeSM(110.0, -3.5), now=12.0) == CHIRP_STARTLED
assert pack.detect_reactive_chirp(_FakeSM(110.0, 2.6), now=13.0) == CHIRP_BOOST
# TODO: add test with micd for checking that soundd actually outputs sounds
+1
View File
@@ -77,6 +77,7 @@ class UIState(UIStateSP):
"vehicleParameters",
"testJoystick",
"rawAudioData",
"radarTracks",
] + self.sm_services_ext
)
+28 -5
View File
@@ -8,10 +8,10 @@ import numpy as np
from openpilot.common.filter_simple import FirstOrderFilter
from openpilot.common.realtime import DT_MDL
from openpilot.sunnypilot.modeld_v2.constants import ModelConstants
from openpilot.sunnypilot.modeld_v2.constants import ModelConstants, Plan
LANE_WIDTH_DEFAULT = 3.6 # m
LANE_WIDTH_CLIP = (2.8, 4.5) # m
LANE_WIDTH_CLIP = (2.4, 4.5) # m
LOOKAHEAD_TIME = 1.5 # s
MIN_LOOKAHEAD = 10.0 # m
MIN_SPEED = 5.0 # m/s
@@ -19,6 +19,11 @@ LINE_STD = (0.2, 0.6)
POINT_STD = 0.1
YIELD = (0.2, 0.45)
X_IDXS = np.array(ModelConstants.X_IDXS)
JUMP = 0.5
JUMP_TAU = 0.5
JUMP_ACCEPT = 3.0
WIDEN = 0.4
YAW_RATE = Plan.ORIENTATION_RATE.start + 2 # matched .991 correlation to actual car
class Blendful:
@@ -36,7 +41,8 @@ class Blendful:
self.l_prob = 0.0
self.r_prob = 0.0
self.model_curvature = 0.0
self.smooth = 0.0 # smooths the correction target below .53 lat accel
self.ref = None
self.jumped = np.zeros(2)
self.curvature = 0.0
def update(self, model_output: dict[str, np.ndarray], v_ego: float, active: bool, model_curvature: float, enabled: bool = True) -> float:
@@ -52,8 +58,8 @@ class Blendful:
self.usual_offset.initialized = False
self.lane_width.initialized = False
self.going_around = False
self.ref = None
target = 0.0 if fading else self._target(model_output, v_ego, model_curvature)
target = self.smooth = self.smooth + (target - self.smooth) * DT_MDL / (DT_MDL + np.interp(abs(model_curvature) * v_ego ** 2, [0.18, 0.53], [0.5, 0.0]))
build = 0.5 / max(v_ego, 1.0) ** 2 * DT_MDL # jerk over 1 second
release = (0.5 if fading else 2.0) / max(v_ego, 1.0) ** 2 * DT_MDL # lets go fast, but past zero it builds like any other pull
k = self.curvature
@@ -63,6 +69,10 @@ class Blendful:
def _target(self, model_output: dict[str, np.ndarray], v_ego: float, model_curvature: float) -> float:
lookahead = max(v_ego * LOOKAHEAD_TIME, MIN_LOOKAHEAD)
lines = model_output['lane_lines'][0, :, :, 0]
plan = model_output['plan'][0]
self._jumps(lines[1:3], v_ego, plan[0, YAW_RATE] if plan.shape[-1] > YAW_RATE else model_curvature * v_ego,
np.interp(abs(model_curvature) * v_ego ** 2, [0.18, 0.53], [JUMP_TAU, 0.0]), lookahead)
held = bool(np.any((self.jumped > 0) & (self.jumped < JUMP_ACCEPT)))
stds = model_output['lane_lines_stds'][0, :, :, 0]
lone_weight = np.interp(abs(model_curvature) * v_ego ** 2, [0.18, 0.53], [0.5, 1.0]) # 0.5 on straights, 1.0 in curves
@@ -83,6 +93,8 @@ class Blendful:
lane_trust = min(l_prob, r_prob)
else:
lane_trust = l_prob + r_prob - l_prob * r_prob
if held or (l_prob * r_prob > 0.5 and np.interp(lookahead, X_IDXS, lines[2] - lines[1]) > self.lane_width.x + WIDEN):
lane_trust = 0.0
if lone_weight > 0.5 and lane_trust < self.line_trust:
lane_trust = self.line_trust + (lane_trust - self.line_trust) * DT_MDL / (lone_weight - 0.5 + DT_MDL)
self.line_trust = lane_trust
@@ -96,7 +108,7 @@ class Blendful:
win = (X_IDXS >= 0.5 * lookahead) & (X_IDXS <= 1.5 * lookahead)
x = X_IDXS[win]
half_width = self.lane_width.x / 2
if l_prob * r_prob > 0.5:
if l_prob * r_prob > 0.5 and not held:
width = np.interp(lookahead, X_IDXS, lines[2]) - np.interp(lookahead, X_IDXS, lines[1])
self.lane_width.update(float(np.clip(width, *LANE_WIDTH_CLIP)))
half_width = np.clip(lines[2, win] - lines[1, win], *LANE_WIDTH_CLIP) / 2
@@ -143,3 +155,14 @@ class Blendful:
self.trust = lane_trust if lane_trust < self.trust else self.trust + (lane_trust - self.trust) * DT_MDL / (1.5 + DT_MDL)
self.dk = dk
return float(self.trust * dk)
def _jumps(self, raw: np.ndarray, v_ego: float, yaw_rate: float, tau: float, lookahead: float) -> None:
if self.ref is None:
self.ref, self.jumped = raw.copy(), np.zeros(2)
return
ref = np.array([np.interp(X_IDXS + v_ego * DT_MDL, X_IDXS, line) for line in self.ref]) - yaw_rate * DT_MDL * X_IDXS
off = np.abs([np.interp(lookahead, X_IDXS, d) for d in raw - ref]) > JUMP
self.jumped = np.where(off & ~off[::-1], self.jumped + DT_MDL, 0.0)
self.ref = ref + (raw - ref) * DT_MDL / (DT_MDL + tau)
accept = (self.jumped >= JUMP_ACCEPT) | off.all()
self.ref[accept] = raw[accept]
@@ -371,7 +371,7 @@ def _compile_warp_resolution_worker(cam_w, cam_h, model_w, model_h, benchmark_ru
if __name__ == "__main__":
if 'USB' in os.getenv('DEV', '') or os.getenv('CHESTNUT'):
if ('USB' in os.getenv('DEV', '') or os.getenv('CHESTNUT')) and not os.getenv('DEV', '').startswith('MOCK'):
from openpilot.system.hardware.chestnut.flash import link_up
for _ in range(10):
if link_up():
+10 -7
View File
@@ -17,6 +17,7 @@ def main():
parser.add_argument("--frame", required=True, help="width,height,stride,y_height,uv_height,buffer_size")
parser.add_argument("--warp-to", required=True, help="model input WxH")
parser.add_argument("--output", required=True)
parser.add_argument("--light", action="store_true")
parser.add_argument("--split-frames", action="store_true", help="one input per camera (frame, big_frame), bound to the camera buffers by pointer")
args = parser.parse_args()
@@ -24,18 +25,20 @@ def main():
from tinygrad import Device, Tensor, TinyJit
frame = parse_frame(args.frame)
warp = make_frame_prepare(frame, *parse_size(args.warp_to))
n = 1 if args.light else 2
cams = list(range(n))
rng = np.random.default_rng(42)
frames = rng.integers(0, 256, (2, frame.size), dtype=np.uint8)
m_inv = Tensor((rng.standard_normal((2, 3, 3)) * 8).astype(np.float32), device=Device.DEFAULT).realize()
m_inv = Tensor((rng.standard_normal((n, 3, 3)) * 8).astype(np.float32), device=Device.DEFAULT).realize()
if args.split_frames:
run = TinyJit(lambda frame, big_frame, M_inv: Tensor.stack(warp(frame, M_inv[0]), warp(big_frame, M_inv[1])), prune=True)
inputs = {"frame": Tensor(frames[0], device=Device.DEFAULT).realize(), "big_frame": Tensor(frames[1], device=Device.DEFAULT).realize(), "M_inv": m_inv}
specs = {"frame": ((frame.size,), "|u1", Device.DEFAULT), "big_frame": ((frame.size,), "|u1", Device.DEFAULT),
"M_inv": ((2, 3, 3), "<f4", Device.DEFAULT)}
names = [("frame", "big_frame")[c] for c in cams]
run = TinyJit(lambda M_inv, **f: Tensor.stack(*(warp(f[nm], M_inv[i]) for i, nm in enumerate(names))), prune=True)
inputs = {nm: Tensor(frames[c], device=Device.DEFAULT).realize() for nm, c in zip(names, cams, strict=True)} | {"M_inv": m_inv}
specs = {nm: ((frame.size,), "|u1", Device.DEFAULT) for nm in names} | {"M_inv": ((n, 3, 3), "<f4", Device.DEFAULT)} # noqa: C420
else:
run = TinyJit(lambda input_frame, M_inv: Tensor.stack(*(warp(input_frame[i], M_inv[i]) for i in range(2))), prune=True)
run = TinyJit(lambda input_frame, M_inv: Tensor.stack(*(warp(input_frame[c], M_inv[i]) for i, c in enumerate(cams))), prune=True)
inputs = {"input_frame": Tensor(frames, device=Device.DEFAULT).realize(), "M_inv": m_inv}
specs = {"input_frame": ((2, frame.size), "|u1", Device.DEFAULT), "M_inv": ((2, 3, 3), "<f4", Device.DEFAULT)}
specs = {"input_frame": ((2, frame.size), "|u1", Device.DEFAULT), "M_inv": ((n, 3, 3), "<f4", Device.DEFAULT)}
with record_kernel_linear() as recorded:
run(**inputs)
run(**inputs)
@@ -10,6 +10,7 @@ import dataclasses
import inspect
import itertools
import mmap
import os
import re
import struct
import tempfile
@@ -194,7 +195,8 @@ def convert(jit, kwargs: dict, frame: dict, target) -> tuple[dict, memoryview]:
base, at, nbytes = _address(argument_words[slot])
args.append({"buffer": buffers.setdefault(base, len(buffers)), "offset": at, "nbytes": nbytes or base.max_numel() * base.dtype.itemsize, "dtype": u8})
outs, ins = kernel[6]
calls.append({"kind": "program", "name": re.sub(r"\x1b\[[0-9;]*m", "", kernel[1]), "lib": programs[image_alloc], "target": dataclasses.asdict(target),
device_target = dataclasses.asdict(dataclasses.replace(target, interface=target.interface.removeprefix("MOCK")))
calls.append({"kind": "program", "name": re.sub(r"\x1b\[[0-9;]*m", "", kernel[1]), "lib": programs[image_alloc], "target": device_target,
"signature": [[f"data{i}", i, u8, [a.get("nbytes", 1)]] for i, a in enumerate(args)], "global_size": grid, "local_size": local,
"globals": list(range(len(args))), "outs": list(outs), "ins": list(ins), "args": args})
needs_init |= {args[i]["buffer"] for i in ins if "buffer" in args[i] and args[i]["buffer"] not in written}
@@ -235,14 +237,16 @@ def main():
frame, _ = capture_frame(artifact["run"], kwargs, "output_buffers")
part = convert(artifact["run"], kwargs, frame, Device[Device.DEFAULT].renderer.target)
plain = PlainJit(*part) # replays the frame, within tolerance
replay = {path[0]: Tensor(array, device=device).realize() for path, array, device in frame["inputs"] if len(path) == 1}
replay["output_buffers"] = {path[1]: Tensor(array, device=device).realize() for path, array, device in frame["inputs"] if len(path) == 2}
flatten(plain(**replay))
for index, (got, expected) in enumerate(zip([t.numpy() for t in replay["output_buffers"].values()], frame["outputs"], strict=True)):
assert np.array_equal(got, expected), f"output {index} of the plain artifact differs from the pickle"
if not os.getenv("MOCKUSB_SOCKET"):
plain = PlainJit(*part)
replay = {path[0]: Tensor(array, device=device).realize() for path, array, device in frame["inputs"] if len(path) == 1}
replay["output_buffers"] = {path[1]: Tensor(array, device=device).realize() for path, array, device in frame["inputs"] if len(path) == 2}
flatten(plain(**replay))
for index, (got, expected) in enumerate(zip([t.numpy() for t in replay["output_buffers"].values()], frame["outputs"], strict=True)):
assert np.array_equal(got, expected), f"output {index} of the plain artifact differs from the pickle"
write_bundle(args.output, {"run": part}, {key: artifact[key] for key in ("metadata", "input_specs", "output_specs")})
print(f"converted {len(part[0]['calls'])} kernels, bit-exact with the pickle: {args.output}")
checked = "left to mock_parity" if os.getenv("MOCKUSB_SOCKET") else "bit-exact with the pickle"
print(f"converted {len(part[0]['calls'])} kernels, {checked}: {args.output}")
if __name__ == "__main__":
+38 -15
View File
@@ -12,8 +12,6 @@ from functools import partial
from openpilot.common.basedir import BASEDIR
from openpilot.sunnypilot.modeld_v2.helpers import _dtype, read_parts
SPLIT_FRAMES = ("big_frame", "frame")
def pack_layout(shapes: dict[str, tuple], frame_size: int) -> tuple[dict[str, int], int]:
offsets, offset = {}, 0
@@ -21,6 +19,13 @@ def pack_layout(shapes: dict[str, tuple], frame_size: int) -> tuple[dict[str, in
offsets[name], offset = offset, offset + -(-math.prod(shape) * 4 // 128) * 128
return offsets | {"frames": offset}, offset + 2 * frame_size
EXTRA_WARPS = {"light_img": "light_tfm"}
SPLIT_FRAMES = ("big_frame", "frame")
def host_shapes(input_shapes: dict[str, tuple], states) -> dict[str, tuple]:
shapes = {name: shape for name, shape in input_shapes.items() if name not in states and name != "new_img" and name not in EXTRA_WARPS}
return shapes | {tfm: (1, 3, 3) for img, tfm in EXTRA_WARPS.items() if img in input_shapes}
class _Blobs: # the model's and the warp's blobs as one address space, for a part whose ranges span both files
def __init__(self, *blobs):
@@ -32,31 +37,46 @@ class _Blobs: # the model's and the warp's blobs as one address space, for a pa
def fused_with_warp(cam_w: int, cam_h: int, chestnut: bool): # load_model's extend: a native model runs upload, warp and model as one submit
return partial(frame_part, f"{BASEDIR}/openpilot/sunnypilot/modeld_v2/models/{'big_' if chestnut else ''}driving_warp_{cam_w}x{cam_h}_tinygrad.pkl")
models, big = f"{BASEDIR}/openpilot/sunnypilot/modeld_v2/models", 'big_' if chestnut else ''
return partial(frame_part, f"{models}/{big}driving_warp_{cam_w}x{cam_h}_tinygrad.pkl",
light_warp_path=f"{models}/{big}driving_lightwarp_{cam_w}x{cam_h}_tinygrad.pkl")
def frame_part(warp_path: str, parts: dict, extras: dict) -> dict:
def frame_part(warp_path: str, parts: dict, extras: dict, light_warp_path: str | None = None) -> dict:
if "input_specs" not in extras: # a legacy model warps in its own parts
return {}
(model, model_blob), (warp, warp_blob) = parts["run"], read_parts(warp_path)[0]["run"]
states = sorted(name for name in extras["input_specs"] if f"next_{name}" in extras["metadata"]["output_shapes"])
host = {name: shape for name, (shape, _, _) in extras["input_specs"].items() if name not in states and name != "new_img"}
frame_specs = {s["name"]: s for s in warp["inputs"] if s["name"] in SPLIT_FRAMES}
offsets, packed = pack_layout(host, 0 if frame_specs else next(s["numel"] for s in warp["inputs"] if s["name"] == "input_frame") // 2)
shift, upload, u8 = len(model_blob), len(model["buffers"]) + len(warp["buffers"]), repr(_dtype("dtypes.uint8"))
host = host_shapes({name: shape for name, (shape, _, _) in extras["input_specs"].items()}, states)
paths = {"light_img": light_warp_path}
extra = [(img, tfm, *read_parts(paths[img])[0]["run"]) for img, tfm in EXTRA_WARPS.items() if img in extras["input_specs"]]
split = any(s["name"] in SPLIT_FRAMES for s in warp["inputs"])
assert all(any(s["name"] in SPLIT_FRAMES for s in part["inputs"]) == split for _, _, part, _ in extra), "camera and extra warps must share a frame layout"
offsets, packed = pack_layout(host, 0 if split else next(s["numel"] for s in warp["inputs"] if s["name"] == "input_frame") // 2)
shift = len(model_blob)
buf_base, blob_base = [len(model["buffers"]) + len(warp["buffers"])], [len(model_blob) + len(warp_blob)]
for _, _, part, blob in extra:
buf_base.append(buf_base[-1] + len(part["buffers"])); blob_base.append(blob_base[-1] + len(blob))
upload, u8 = buf_base[-1], repr(_dtype("dtypes.uint8"))
extra_at = {img: (part, buf_base[i], blob_base[i], tfm) for i, (img, tfm, part, _) in enumerate(extra)}
def view(name: str, nbytes: int, dtype: str) -> dict:
return {"buffer": upload, "offset": offsets[name], "nbytes": nbytes, "dtype": dtype}
outputs = sorted(s["slot"] for s in model["inputs"] if s["name"] is None)
frame_specs = {s["name"]: s for _, _, part, _ in [(None, None, warp, None), *extra] for s in part["inputs"] if s["name"] in SPLIT_FRAMES}
names = sorted(["host", *states, *frame_specs])
slots = {s["slot"]: names.index(s["name"]) for s in model["inputs"] if s["name"] in states} | \
{slot: len(names) + i for i, slot in enumerate(outputs)}
returned = warp["returns"]["tensors"][0]
def warped(part: dict, base: int) -> dict:
returned = part["returns"]["tensors"][0]
return {k: v for k, v in returned.items() if k != "shape"} | {"buffer": returned["buffer"] + base}
model_inputs = {s["slot"]: {"input": slots[s["slot"]]} if s["slot"] in slots else
{k: v for k, v in returned.items() if k != "shape"} | {"buffer": returned["buffer"] + len(model["buffers"])} if s["name"] == "new_img" else
warped(warp, len(model["buffers"])) if s["name"] == "new_img" else
warped(extra_at[s["name"]][0], extra_at[s["name"]][1]) if s["name"] in extra_at else
view(s["name"], s["numel"] * _dtype(s["dtype"]).itemsize, s["dtype"]) for s in model["inputs"]}
warp_inputs = {s["slot"]: {"input": names.index(s["name"])} if s["name"] in frame_specs else
view("frames" if s["name"] == "input_frame" else "tfm", s["numel"] * _dtype(s["dtype"]).itemsize, s["dtype"]) for s in warp["inputs"]}
def warp_inputs(part: dict, tfm: str) -> dict:
return {s["slot"]: {"input": names.index(s["name"])} if s["name"] in frame_specs else
view("frames" if s["name"] == "input_frame" else tfm, s["numel"] * _dtype(s["dtype"]).itemsize, s["dtype"]) for s in part["inputs"]}
def remap(calls: list, inputs: dict, buffers: int, lib: int) -> list:
return [call | ({"lib": [call["lib"][0] + lib, call["lib"][1] + lib]} if "lib" in call else {}) |
@@ -65,8 +85,11 @@ def frame_part(warp_path: str, parts: dict, extras: dict) -> dict:
"inputs": [{"slot": names.index("host"), "name": "host", "dtype": u8, "numel": packed, "device": "NPY"}] +
[s | {"slot": slots[s["slot"]]} for s in model["inputs"] if s["slot"] in slots] +
[s | {"slot": names.index(name)} for name, s in frame_specs.items()],
"buffers": model["buffers"] + [b | ({"init": [b["init"][0] + shift, b["init"][1] + shift]} if "init" in b else {}) for b in warp["buffers"]] +
"buffers": model["buffers"] + [b | ({"init": [b["init"][0] + d, b["init"][1] + d]} if "init" in b else {})
for part, d in ((warp, shift), *((p, bb) for p, _, bb, _ in extra_at.values())) for b in part["buffers"]] +
[{"nbytes": packed, "device": model["inputs"][0]["device"], "dtype": u8}],
"calls": [{"kind": "copy", "args": [{"buffer": upload, "offset": 0, "nbytes": packed, "dtype": u8}, {"input": names.index("host")}]}] +
remap(warp["calls"], warp_inputs, len(model["buffers"]), shift) + remap(model["calls"], model_inputs, 0, 0)}
return {"run": (header, _Blobs(model_blob, warp_blob))} # replaces the model's run: one set of buffers, no separate warp
remap(warp["calls"], warp_inputs(warp, "tfm"), len(model["buffers"]), shift) +
[c for p, b0, bb, tfm in extra_at.values() for c in remap(p["calls"], warp_inputs(p, tfm), b0, bb)] +
remap(model["calls"], model_inputs, 0, 0)}
return {"run": (header, _Blobs(model_blob, warp_blob, *(blob for *_, blob in extra)))}
@@ -0,0 +1,22 @@
"""
Copyright (c) 2021-, sunnypilot, and a number of other contributors.
This file is part of sunnypilot and is licensed under the MIT License.
See the LICENSE.md file in the root directory for more details.
"""
import numpy as np
from openpilot.common.transformations.camera import get_view_frame_from_calib_frame, view_frame_from_device_frame
from openpilot.common.transformations.orientation import rot_from_euler
LIGHT_INPUT_SIZE = (512, 256)
light_intrinsics = np.array([
[1000.0, 0.0, 256.0],
[0.0, 1000.0, 200.0],
[0.0, 0.0, 1.0]])
calib_from_light = np.linalg.inv((light_intrinsics @ get_view_frame_from_calib_frame(0, 0, 0, 0))[:, :3])
def get_light_warp_matrix(device_from_calib_euler: np.ndarray, intrinsics: np.ndarray) -> np.ndarray:
camera_from_calib = intrinsics @ view_frame_from_device_frame @ rot_from_euler(device_from_calib_euler)
return (camera_from_calib @ calib_from_light).astype(np.float32)
@@ -0,0 +1,153 @@
import json
import os
import shutil
import struct
import sys
import tempfile
import time
os.environ.setdefault("DEV", "MOCKUSB+AMD")
QCOM = "QCOM" in os.environ["DEV"]
ON_MOCK = os.environ["DEV"].startswith("MOCK")
ARCH, HARDWARE = ("a630", "comma 3x/4 (a630)") if QCOM else ("gfx1200", "chestnut")
os.environ.setdefault("CHECK_OOB", "0")
os.environ.setdefault("GMMU", "0")
if sys.platform == "darwin" and os.environ["DEV"].startswith("MOCKUSB"): # the mock's VRAM is a memfd, which macOS lacks: an unlinked file is the same
from tinygrad.runtime.autogen import libc
def _memfd_create(name, flags):
fd, path = tempfile.mkstemp()
os.unlink(path)
return fd
libc.memfd_create = _memfd_create
import numpy as np
from openpilot.sunnypilot.modeld_v2.helpers import ALIGNMENT, MAGIC, PlainJit, _device, read_parts
class ParityError(RuntimeError):
pass
def _emulator():
try:
if QCOM:
from test.mockgpu.qcom import emu
else:
from test.mockgpu.amd import emu
except ImportError as e:
raise ParityError(f"tinygrad's {'qcom' if QCOM else 'amd'} mock is not importable: put tinygrad_repo on PYTHONPATH") from e
if not hasattr(emu, "hw_unverified"):
raise ParityError(f"this tinygrad's emulator has no {ARCH} rounding model, its check frames would not match a {HARDWARE}")
return emu
def unverified(header: dict, blob: memoryview) -> dict[str, int]:
emu, out = _emulator(), {}
for call in header["calls"]:
if call["kind"] != "program":
continue
if (arch := call["target"].get("arch", "")).split(",")[0] != ARCH: # IMAGE builds append ",IMAGE_PITCH_ALIGNMENT=64"
out[f"arch={arch}"] = out.get(f"arch={arch}", 0) + 1
continue
for sig, n in emu.hw_unverified(bytes(blob[slice(*call["lib"])])).items():
out[sig] = out.get(sig, 0) + n
return out
def _array(blob: memoryview, stored: dict) -> np.ndarray:
return np.frombuffer(blob[slice(*stored["data"])], dtype=np.dtype(stored["dtype"])).reshape(stored["shape"]).copy()
def replay(header: dict, blob: memoryview, shared: dict) -> list[np.ndarray]:
from tinygrad import Tensor
check = header["check"]
jit = PlainJit(header, blob, None, verify=False, shared=shared)
kwargs: dict = {}
for path, stored, device in check["inputs"]:
tensor = Tensor(_array(blob, stored), device=_device(device, None)).realize()
kwargs[path[0]] = tensor if len(path) == 1 else {**kwargs.get(path[0], {}), path[1]: tensor}
result = jit(**kwargs)
outputs = kwargs[check["output_container"]].values() if check["output_container"] else result
return [t.numpy() for t in (outputs if isinstance(outputs, (list, tuple)) or check["output_container"] else [outputs])]
def _parts_with_offsets(path: str) -> tuple[dict, dict]:
parts, _ = read_parts(path)
with open(path, "rb") as f:
head = f.read(len(MAGIC) + 8)
start = len(MAGIC) + 8 + struct.unpack_from("<Q", head, len(MAGIC))[0]
f.seek(len(MAGIC) + 8)
entries = json.loads(f.read(start - len(MAGIC) - 8))["parts"]
base = start + -start % ALIGNMENT
offsets = {tuple(e["key"]) if isinstance(e["key"], list) else e["key"]: base + e["blob"][0] for e in entries}
return parts, offsets
def _gate(parts: dict) -> None:
missing: dict[str, int] = {}
for header, blob in parts.values():
if "check" not in header:
raise ParityError("artifact has no check frame")
for sig, n in unverified(header, blob).items():
missing[sig] = missing.get(sig, 0) + n
if missing:
raise ParityError(f"kernels use instructions the emulator is not verified against a {HARDWARE} for: " +
", ".join(f"{s} ({n}x)" for s, n in sorted(missing.items(), key=lambda kv: -kv[1])))
def check(path: str) -> None:
parts, _ = read_parts(path)
if ON_MOCK:
_gate(parts)
shared: dict = {}
for key, (header, blob) in parts.items():
got = replay(header, blob, shared)
for i, (g, stored) in enumerate(zip(got, header["check"]["outputs"], strict=True)):
want = _array(blob, stored)
if g.shape != want.shape or not np.array_equal(g.view(np.uint8), want.view(np.uint8)):
n = int(np.count_nonzero(g != want)) if g.shape == want.shape else -1
where = "mock" if ON_MOCK else "device"
raise ParityError(f"part {key} output {i}: the {where}'s check frame differs from the stored one in {n} of {want.size} values")
def record(path: str, out: str) -> None:
parts, offsets = _parts_with_offsets(path)
_gate(parts)
shared, writes = {}, []
for key, (header, blob) in parts.items():
for g, stored in zip(replay(header, blob, shared), header["check"]["outputs"], strict=True):
want = np.dtype(stored["dtype"])
if tuple(g.shape) != tuple(stored["shape"]) or g.dtype != want:
raise ParityError(f"part {key}: replayed output {g.dtype}{g.shape} does not fit the stored {want}{tuple(stored['shape'])}")
writes.append((offsets[key] + stored["data"][0], np.ascontiguousarray(g).tobytes()))
shutil.copyfile(path, out)
with open(out, "r+b") as f:
for offset, data in writes:
f.seek(offset)
f.write(data)
def main(argv: list[str]) -> int:
if len(argv) < 2 or argv[0] not in ("check", "record") or (argv[0] == "record" and len(argv) != 3):
print("usage: mock_parity check ARTIFACT... | record ARTIFACT OUT", file=sys.stderr)
return 2
try:
if argv[0] == "record":
st = time.perf_counter()
record(argv[1], argv[2])
print(f"{argv[2]}: check frame recorded on the mock in {time.perf_counter() - st:.0f}s")
return 0
for path in argv[1:]:
st = time.perf_counter()
check(path)
print(f"{os.path.basename(path)}: bit-identical to its {HARDWARE} check frame on the {'mock' if ON_MOCK else 'device'} ({time.perf_counter() - st:.0f}s)")
return 0
except ParityError as e:
print(f"PARITY FAIL: {e}", file=sys.stderr)
return 1
if __name__ == "__main__":
sys.exit(main(sys.argv[1:]))
@@ -11,7 +11,7 @@ import pickle
import numpy as np
from openpilot.common.basedir import BASEDIR
from openpilot.sunnypilot.modeld_v2.frame_fusion import pack_layout, SPLIT_FRAMES
from openpilot.sunnypilot.modeld_v2.frame_fusion import host_shapes, pack_layout, SPLIT_FRAMES
from openpilot.sunnypilot.modeld_v2.helpers import load_model
from openpilot.sunnypilot.modeld_v2.compile_modeld import (POLICY_INPUTS, derive_frame_skip,
make_split_input_queues, make_supercombo_input_queues)
@@ -174,7 +174,7 @@ class NativeTinygradAdapter(BaseModelAdapter):
self.input_queues = {name: Tensor(np.zeros(shape, dtype=dtype), device=self.model_device).realize()
for name, (shape, dtype) in self.input_shapes.items() if name in self.state_pairs}
shapes = {name: shape for name, (shape, _) in self.input_shapes.items() if name not in self.state_pairs and name != 'new_img'}
shapes = host_shapes({name: shape for name, (shape, _) in self.input_shapes.items()}, self.state_pairs)
offsets, packed = pack_layout(shapes, 0 if self.split else self.warp_frame_size)
self.packed_input = np.zeros(packed, dtype=np.uint8)
self.host = Tensor(self.packed_input, device='NPY')
+16 -2
View File
@@ -11,6 +11,7 @@ from functools import partial
import gc
import os
os.environ['GMMU'] = '0'
os.environ['QCOM_PRIORITY'] = '1'
from tinygrad.device import Device
import numpy as np
import threading
@@ -44,6 +45,7 @@ from openpilot.sunnypilot.modeld_v2.blendful import Blendful
from openpilot.sunnypilot.modeld_v2.constants import ModelConstants, Plan
from openpilot.sunnypilot.modeld_v2.meta_helper import load_meta_constants
from openpilot.sunnypilot.modeld_v2.camera_offset_helper import CameraOffsetHelper
from openpilot.sunnypilot.modeld_v2.light_frame import get_light_warp_matrix
from openpilot.sunnypilot.livedelay.helpers import get_lat_delay
from openpilot.sunnypilot.modeld_v2.modeld_base import ModelStateBase
from openpilot.sunnypilot.modeld_v2.helpers import load_model
@@ -171,7 +173,7 @@ class ModelState(ModelStateBase):
np.where(inputs[desire_key] - self.prev_desire > .99, inputs[desire_key], 0)
self.prev_desire[:] = inputs[desire_key]
for key in ('traffic_convention', 'lateral_control_params', 'action_t'):
for key in ('traffic_convention', 'lateral_control_params', 'action_t', 'speed_limit'):
if key in self.numpy_inputs and key in inputs:
self.numpy_inputs[key][:] = inputs[key]
@@ -179,6 +181,8 @@ class ModelState(ModelStateBase):
for i, key in enumerate(self._vision_input_names):
if key in transforms:
self.numpy_inputs['tfm'][i] = transforms[key].reshape(3, 3)
if 'light_tfm' in self.numpy_inputs and 'light' in transforms:
self.numpy_inputs['light_tfm'][0] = transforms['light'].reshape(3, 3)
else:
self.numpy_inputs['tfm'][:, :] = transforms[self._road_key].reshape(3, 3)
self.numpy_inputs['big_tfm'][:, :] = transforms[self._wide_key].reshape(3, 3)
@@ -338,7 +342,7 @@ def main(demo=False):
pub_socks = ["modelV2", "drivingModelData", "cameraOdometry", "modelDataV2SP"] + (["chestnutGpuState"] if CHESTNUT else [])
pm = PubMaster(pub_socks)
sm = SubMaster(["deviceState", "carState", "narrowRoadCameraState", "extrinsicsCalibration", "driverMonitoringState",
"carControl", "controlsState", "lateralDelay"])
"carControl", "controlsState", "lateralDelay", "longitudinalPlanSP"])
publish_state = PublishState()
chestnut_state = ChestnutGpuState(pm, model.chestnut) if CHESTNUT else None
@@ -351,6 +355,7 @@ def main(demo=False):
model_transform_main = np.zeros((3, 3), dtype=np.float32)
model_transform_extra = np.zeros((3, 3), dtype=np.float32)
model_transform_light = np.zeros((3, 3), dtype=np.float32)
live_calib_seen = False
buf_main, buf_extra = None, None
meta_main = FrameMeta()
@@ -369,6 +374,9 @@ def main(demo=False):
prev_action = log.ModelDataV2.Action()
DH = DesireHelper()
desire_frames = [q.shape[0] for m in (model, small_model) if m is not None for name, q in m.adapter.input_queues.items() if 'desire' in name]
if desire_frames:
DH.turn_repulse = min(desire_frames) - 2
meta_constants = load_meta_constants()
RELC = RoadEdgeLaneChangeController()
blendful = Blendful()
@@ -425,6 +433,7 @@ def main(demo=False):
model_transform_main = get_warp_matrix(device_from_calib_euler, main_intrinsics, False).astype(np.float32)
model_transform_extra = get_warp_matrix(device_from_calib_euler, dc.wide_road.intrinsics, True).astype(np.float32)
model_transform_main, model_transform_extra = camera_offset_helper.update(model_transform_main, model_transform_extra, sm, main_wide_camera)
model_transform_light = get_light_warp_matrix(device_from_calib_euler, main_intrinsics)
live_calib_seen = True
traffic_convention = np.zeros(2)
@@ -446,6 +455,7 @@ def main(demo=False):
bufs = {name: buf_extra if 'big' in name else buf_main for name in model.vision_input_names}
transforms = {name: model_transform_extra if 'big' in name else model_transform_main for name in model.vision_input_names}
transforms['light'] = model_transform_light
frame_delay = DT_MDL # compensate for time passed since the frame was captured: current_time - timestamp_eof is 50ms on average
action_delay = DT_MDL / 2 # middle of the interval between model output (current state) and next frame (expected state)
@@ -463,6 +473,10 @@ def main(demo=False):
if 'action_t' in model.numpy_inputs:
inputs['action_t'] = np.array([lat_action_t, long_action_t], dtype=np.float32)
if 'speed_limit' in model.numpy_inputs:
resolver = sm['longitudinalPlanSP'].speedLimit.resolver
inputs['speed_limit'] = np.array([resolver.speedLimitFinal if resolver.speedLimitValid else 0.0], dtype=np.float32)
mt1 = time.perf_counter()
try:
send_chestnut = (chestnut_state is not None and
@@ -0,0 +1,3 @@
version https://git-lfs.github.com/spec/v1
oid sha256:1baac6f02902df5689e9e275633c122a9955b7c57de2681e0137e1724c1f32dd
size 3463278
@@ -0,0 +1,3 @@
version https://git-lfs.github.com/spec/v1
oid sha256:0478837491c584b2212e31a91c494a908b8fb048205700f05a02a13ee7fc9b90
size 7690094
@@ -0,0 +1,3 @@
version https://git-lfs.github.com/spec/v1
oid sha256:580fadf61ded34b4b19f0ba1f5e4b61c0ea489ca34a0952ccf2878593e3f68c4
size 1851239
@@ -0,0 +1,3 @@
version https://git-lfs.github.com/spec/v1
oid sha256:44700f3533abb3e65232c8aca46b48384a59218545ed6bb505c5d4762204359b
size 3964263
@@ -1,3 +1,3 @@
version https://git-lfs.github.com/spec/v1
oid sha256:d776c72125156b5dd3eb59768409401e28c8a52a3a619cd3b9f02c10a156fda6
oid sha256:1f5dd8855de07d0e8b9ed836934e1dcbe77aa27c3b5c77eee1f21888f974ba8b
size 3699072
@@ -1,3 +1,3 @@
version https://git-lfs.github.com/spec/v1
oid sha256:a3f13ed12e087817a86afd48b2496c66c4f61a1925065b676b2945e81fabaacd
oid sha256:226d40112a292077b7eca26b97273c56ab3a84feee8ddf9b6d02d46c2a7b8403
size 7924864
@@ -80,7 +80,8 @@ def serialize_jit(jit, kernel_linear, check: dict | None = None) -> tuple[dict,
if ast.op is Ops.PROGRAM:
elf, info = ast.to_elf(), ast.arg
global_size, local_size = info.launch_dims({})
calls.append({"kind": "program", "name": elf.name, "lib": blob.add(bytes(elf.lib)), "target": dataclasses.asdict(elf.target),
device_target = dataclasses.asdict(dataclasses.replace(elf.target, interface=elf.target.interface.removeprefix("MOCK")))
calls.append({"kind": "program", "name": elf.name, "lib": blob.add(bytes(elf.lib)), "target": device_target,
"signature": kernel_signature(ast, elf),
"global_size": [int(x) for x in global_size], "local_size": [int(x) for x in local_size],
"globals": list(info.globals), "outs": list(info.outs), "ins": list(info.ins), "args": arguments})
@@ -17,4 +17,4 @@ class TestRegistryModels(unittest.TestCase):
self.skipTest("MODEL_BASE_NAME env var not set, skipping integration test.")
bundle = load_model(os.path.join(os.environ.get("MODEL_DIR", "/tmp/models"), base_name), {"QCOM": "CPU", "AMD": "CPU"}, verify=False, cache=False)
jits = [value for value in bundle.values() if isinstance(value, PlainJit)]
assert "metadata" in bundle and jits and all(len(jit.captured.linear.src) > 0 for jit in jits)
assert "metadata" in bundle and jits and all(len(jit.captured._linear.src) > 0 for jit in jits)
+1 -1
View File
@@ -112,7 +112,7 @@ class ModelCache:
class ModelFetcher:
"""Handles fetching and caching of model data from remote source"""
MODEL_URL = "https://raw.githubusercontent.com/sunnypilot/sunnypilot-models/refs/heads/gh-pages/docs/driving_models_v25.json"
MODEL_URL = "https://raw.githubusercontent.com/sunnypilot/sunnypilot-models/refs/heads/gh-pages/docs/driving_models_v26.json"
MODEL_URL_CHESTNUT = "https://raw.githubusercontent.com/sunnypilot/sunnypilot-models/refs/heads/gh-pages/docs/driving_models_chestnut_v28.json"
MODEL_SOURCES = {
@@ -0,0 +1,3 @@
version https://git-lfs.github.com/spec/v1
oid sha256:f7df0485754b51731fc60b4cb324d75c7058c0e20c7c979ac84aa5273e29aa83
size 5956
@@ -0,0 +1,3 @@
version https://git-lfs.github.com/spec/v1
oid sha256:bd28c1e0a0dc15f5a1abc97cea2817f437880ed9e04fd7fc2ab1fb1b6a694ab0
size 65812
@@ -0,0 +1,3 @@
version https://git-lfs.github.com/spec/v1
oid sha256:e641bf54c1dd190ec903f12b06c761865b5bcfe918f015c4f8b781364a52817d
size 33164
@@ -0,0 +1,3 @@
version https://git-lfs.github.com/spec/v1
oid sha256:4d94997ee61f7ba0f3afece1db5b0c9c16f32512832380fc0ac13c384d360efd
size 56152
@@ -0,0 +1,3 @@
version https://git-lfs.github.com/spec/v1
oid sha256:9c85ee1bdbede640c484da13c5a25bd40f7c165df5d2ed9b1db3edf15712aae7
size 115522
@@ -0,0 +1,3 @@
version https://git-lfs.github.com/spec/v1
oid sha256:4b9cd0c5d6f06f53dd8781afe685a52ea52de717eabb3865a642b3464c851ac8
size 31244
@@ -0,0 +1,219 @@
#!/usr/bin/env python3
"""Generate EMO-inspired robotic chirps and vocoded voice alert WAVs (48 kHz, mono, 16-bit PCM).
Run this script whenever tweaking the robotic sound pack:
python3 openpilot/sunnypilot/selfdrive/assets/sounds/robotic/generate_robotic_sounds.py
"""
from pathlib import Path
import shutil
import subprocess
import tempfile
import wave
import numpy as np
SAMPLE_RATE = 48000
MAX_INT16 = 32767
OUT_DIR = Path(__file__).resolve().parent
def write_wav(path: Path, samples: np.ndarray) -> None:
clipped = np.clip(samples, -1.0, 1.0)
pcm = (clipped * MAX_INT16).astype(np.int16)
with wave.open(str(path), "wb") as wf:
wf.setnchannels(1)
wf.setsampwidth(2)
wf.setframerate(SAMPLE_RATE)
wf.writeframes(pcm.tobytes())
def adsr(n: int, attack: float = 0.015, release: float = 0.04) -> np.ndarray:
env = np.ones(n, dtype=np.float32)
a_n = min(n // 2, int(attack * SAMPLE_RATE))
r_n = min(n // 2, int(release * SAMPLE_RATE))
if a_n > 0:
env[:a_n] = np.linspace(0.0, 1.0, a_n, dtype=np.float32)
if r_n > 0:
env[-r_n:] = np.linspace(1.0, 0.0, r_n, dtype=np.float32)
return env
def emo_chirp(f_start: float, f_end: float, duration: float, vibrato_hz: float = 0.0, vibrato_depth: float = 0.0, gain: float = 0.65) -> np.ndarray:
"""Synthesize an expressive EMO-like harmonic chirp with smooth pitch glide."""
n = int(SAMPLE_RATE * duration)
t = np.arange(n, dtype=np.float32) / SAMPLE_RATE
# Smooth cubic-ish frequency glide
progress = t / max(duration, 1e-6)
s_curve = progress * progress * (3.0 - 2.0 * progress)
freq = f_start + (f_end - f_start) * s_curve
if vibrato_hz > 0.0:
freq = freq + vibrato_depth * np.sin(2.0 * np.pi * vibrato_hz * t)
phase = 2.0 * np.pi * np.cumsum(freq) / SAMPLE_RATE
# Warm robotic timbre: fundamental + soft 2nd & 3rd harmonics
sig = (
0.72 * np.sin(phase)
+ 0.22 * np.sin(2.0 * phase + 0.3)
+ 0.08 * np.sin(3.0 * phase)
)
env = adsr(n, attack=min(0.015, duration * 0.2), release=min(0.055, duration * 0.35))
return (sig * env * gain).astype(np.float32)
def silence(duration: float) -> np.ndarray:
return np.zeros(int(SAMPLE_RATE * duration), dtype=np.float32)
def robotize_voice(samples: np.ndarray, carrier_hz: float = 165.0) -> np.ndarray:
"""Apply a clean EMO-style robotic vocoder / comb-resonance effect while keeping speech crisp."""
n = len(samples)
if n == 0:
return samples
t = np.arange(n, dtype=np.float32) / SAMPLE_RATE
# Normalize speech input
peak = float(np.max(np.abs(samples)))
if peak > 1e-5:
samples = samples / peak
# Short metallic comb resonance (~5.5 ms delay) for unmistakable robot character
delay = int(0.0055 * SAMPLE_RATE)
comb = samples.copy()
if delay < n:
comb[delay:] += 0.42 * samples[:-delay]
# Gentle ring modulation blended with intelligible dry+comb voice
carrier = 0.65 * np.sin(2.0 * np.pi * carrier_hz * t) + 0.35 * np.sin(2.0 * np.pi * carrier_hz * 2.0 * t)
ring = comb * carrier
blended = 0.62 * comb + 0.38 * ring
# Soft saturation & normalization
blended = np.tanh(blended * 1.45)
peak = float(np.max(np.abs(blended)))
if peak > 1e-5:
blended = blended / peak * 0.94
return blended.astype(np.float32)
def synthesize_robotic_phrase(text: str, rate: int = 205, carrier_hz: float = 175.0) -> np.ndarray | None:
"""Render a short spoken phrase via macOS `say` + `ffmpeg`/`afconvert`, then robotize it."""
say_bin = shutil.which("say")
ffmpeg_bin = shutil.which("ffmpeg")
if not say_bin or not ffmpeg_bin:
return None
with tempfile.TemporaryDirectory() as tmpdir:
aiff_path = Path(tmpdir) / "speech.aiff"
wav_path = Path(tmpdir) / "speech.wav"
# Use a crisp clear voice ("Samantha" or system default) pitched up slightly via ffmpeg asetrate
cmd_say = [say_bin, "-r", str(rate), "-o", str(aiff_path), text]
subprocess.run(cmd_say, check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
# Convert to 48kHz mono 16-bit WAV, slight pitch-up (+12%) for cute EMO-like robot timbre, trim silence
cmd_ff = [
ffmpeg_bin, "-y", "-i", str(aiff_path),
"-af", "silenceremove=start_periods=1:start_threshold=-40dB:stop_periods=1:stop_threshold=-40dB,asetrate=22050*1.12,aresample=48000",
"-ac", "1", "-ar", str(SAMPLE_RATE), "-sample_fmt", "s16",
str(wav_path),
]
subprocess.run(cmd_ff, check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
with wave.open(str(wav_path), "rb") as wf:
raw = np.frombuffer(wf.readframes(wf.getnframes()), dtype=np.int16).astype(np.float32) / 32768.0
return robotize_voice(raw, carrier_hz=carrier_hz)
def build_all_sounds() -> None:
# 1. EMO-style expressive chirps & vocalizations (punchy & bubbly loudness matching stock WAVs)
engage = np.concatenate([
emo_chirp(660, 1020, 0.11, gain=0.88),
silence(0.025),
emo_chirp(1020, 1580, 0.19, vibrato_hz=24, vibrato_depth=28, gain=0.94),
])
write_wav(OUT_DIR / "engage.wav", engage)
disengage = np.concatenate([
emo_chirp(1080, 740, 0.13, gain=0.86),
silence(0.025),
emo_chirp(700, 440, 0.19, gain=0.84),
])
write_wav(OUT_DIR / "disengage.wav", disengage)
refuse = np.concatenate([
emo_chirp(480, 340, 0.12, vibrato_hz=32, vibrato_depth=28, gain=0.88),
silence(0.04),
emo_chirp(390, 270, 0.16, vibrato_hz=32, vibrato_depth=28, gain=0.88),
])
write_wav(OUT_DIR / "refuse.wav", refuse)
pre_alert = emo_chirp(860, 1480, 0.22, vibrato_hz=26, vibrato_depth=22, gain=0.88)
write_wav(OUT_DIR / "pre_alert.wav", pre_alert)
prompt_low = emo_chirp(620, 500, 0.19, gain=0.84)
write_wav(OUT_DIR / "prompt_single_low.wav", prompt_low)
prompt_high = emo_chirp(1080, 1420, 0.17, gain=0.88)
write_wav(OUT_DIR / "prompt_single_high.wav", prompt_high)
# 2. Hybrid chirp + vocoded robotic spoken phrases for warnings & critical alerts
def hybrid(intro: np.ndarray, phrase: str, fallback: np.ndarray, tail_pause: float = 0.0, carrier_hz: float = 175.0) -> np.ndarray:
voice = synthesize_robotic_phrase(phrase, carrier_hz=carrier_hz)
body = voice if voice is not None else fallback
parts = [intro, silence(0.04), body]
if tail_pause > 0.0:
parts.append(silence(tail_pause))
return np.concatenate(parts)
warning = hybrid(
emo_chirp(820, 1120, 0.12, gain=0.65),
"Heads up",
emo_chirp(1120, 880, 0.22, gain=0.65),
carrier_hz=185.0,
)
write_wav(OUT_DIR / "warning.wav", warning)
warning_repeat = hybrid(
emo_chirp(860, 1180, 0.12, gain=0.68),
"Attention",
emo_chirp(1180, 900, 0.22, gain=0.68),
tail_pause=0.35,
carrier_hz=185.0,
)
write_wav(OUT_DIR / "warning_repeat.wav", warning_repeat)
dm_warning = hybrid(
np.concatenate([emo_chirp(740, 1080, 0.10, gain=0.68), silence(0.03), emo_chirp(880, 1240, 0.10, gain=0.68)]),
"Eyes on road",
emo_chirp(1050, 780, 0.25, gain=0.68),
tail_pause=0.35,
carrier_hz=190.0,
)
write_wav(OUT_DIR / "dm_warning.wav", dm_warning)
critical = hybrid(
np.concatenate([emo_chirp(1320, 1520, 0.11, gain=0.80), silence(0.03), emo_chirp(1520, 1320, 0.11, gain=0.80)]),
"Take control",
emo_chirp(1480, 1100, 0.26, gain=0.80),
tail_pause=0.28,
carrier_hz=160.0,
)
write_wav(OUT_DIR / "critical.wav", critical)
dm_critical = hybrid(
np.concatenate([
emo_chirp(1450, 1720, 0.09, gain=0.85),
silence(0.025),
emo_chirp(1450, 1720, 0.09, gain=0.85),
]),
"Take control now",
emo_chirp(1680, 1200, 0.28, gain=0.85),
tail_pause=0.22,
carrier_hz=150.0,
)
write_wav(OUT_DIR / "dm_critical.wav", dm_critical)
print(f"Generated 11 robotic WAV files in {OUT_DIR}")
if __name__ == "__main__":
build_all_sounds()
@@ -0,0 +1,3 @@
version https://git-lfs.github.com/spec/v1
oid sha256:19b08e539bdce2cefbcee335f513c24b6bc87792468c93a6cb22fe7aa8a9db90
size 21164
@@ -0,0 +1,3 @@
version https://git-lfs.github.com/spec/v1
oid sha256:fadc2782ae6a2459e4151fe0ad2d23ff2d061b74b53817391c8d9109ee00d321
size 16364
@@ -0,0 +1,3 @@
version https://git-lfs.github.com/spec/v1
oid sha256:9c58699ac691974880a9b49083a3f44ed95f1996aebfb85057e6b6bd012da2a2
size 18284
@@ -0,0 +1,3 @@
version https://git-lfs.github.com/spec/v1
oid sha256:2a88e78d6fb30fd6b9093fa7dad87d9c754c97afaf53b0006882f2be60329a01
size 30764
@@ -0,0 +1,3 @@
version https://git-lfs.github.com/spec/v1
oid sha256:ed26262d283e696b73452e63486b656c777a4fe24914090e07e8f95f7a5c2461
size 42098
@@ -0,0 +1,3 @@
version https://git-lfs.github.com/spec/v1
oid sha256:2e172036401b6c5d81ce922b6e5ed9e1bc39320646f8b7aa1df223f9e392fe90
size 52158
@@ -5,6 +5,7 @@ This file is part of sunnypilot and is licensed under the MIT License.
See the LICENSE.md file in the root directory for more details.
"""
import openpilot.cereal.messaging as messaging
from openpilot.cereal import log, custom
from opendbc.car import structs
@@ -23,10 +24,15 @@ class CarSpecificEventsSP:
self.CP_SP = CP_SP
self.low_speed_alert = False
self.sm = messaging.SubMaster(['carStateSP'])
def update(self, CS: structs.CarState, events: Events):
events_sp = EventsSP()
self.sm.update(0)
if self.sm['carStateSP'].stockSteerIntervention:
events_sp.add(EventNameSP.stockSteerIntervention)
if self.CP.brand == 'chrysler':
if self.CP.carFingerprint in RAM_DT:
# remove belowSteerSpeed event from CarSpecificEvents as RAM_DT uses a different logic
@@ -11,6 +11,7 @@ from opendbc.car.interfaces import CarInterfaceBase
from openpilot.common.params import Params
from openpilot.common.swaglog import cloudlog
from openpilot.sunnypilot.selfdrive.controls.lib.nnlc.helpers import get_nn_model_path
from openpilot.sunnypilot.selfdrive.controls.lib.pidd import PIDD_VERSION
from openpilot.sunnypilot.selfdrive.controls.lib.speed_limit.helpers import set_speed_limit_assist_availability
from openpilot.sunnypilot.sunnylink.statsd import STATSLOGSP
@@ -55,10 +56,18 @@ def _initialize_intelligent_cruise_button_management(CP: structs.CarParams, CP_S
CP_SP.pcmCruiseSpeed = False
def _initialize_torque_lateral_control(CI: CarInterfaceBase, CP: structs.CarParams, enforce_torque: bool, nnlc_enabled: bool) -> None:
def _initialize_torque_lateral_control(CI: CarInterfaceBase, CP: structs.CarParams, enforce_torque: bool, nnlc_enabled: bool,
params: Params | None = None) -> None:
if params is None:
params = Params()
if nnlc_enabled or enforce_torque:
CI.configure_torque_tune(CP.carFingerprint, CP.lateralTuning)
if enforce_torque and not nnlc_enabled and CP.steerControlType == structs.CarParams.SteerControlType.torque \
and params.get("TorqueControlTune") == PIDD_VERSION:
CP.lateralTuning.init('pid')
def _cleanup_unsupported_params(CP: structs.CarParams, CP_SP: structs.CarParamsSP, params: Params | None = None) -> None:
if params is None:
@@ -92,7 +101,7 @@ def setup_interfaces(CI: CarInterfaceBase, params: Params | None = None) -> None
enforce_torque = _enforce_torque_lateral_control(CI.CP, params)
nnlc_enabled = _initialize_neural_network_lateral_control(CI.CP, CI.CP_SP, params)
_initialize_intelligent_cruise_button_management(CI.CP, CI.CP_SP, params)
_initialize_torque_lateral_control(CI, CI.CP, enforce_torque, nnlc_enabled)
_initialize_torque_lateral_control(CI, CI.CP, enforce_torque, nnlc_enabled, params)
_cleanup_unsupported_params(CI.CP, CI.CP_SP)
try:
@@ -105,6 +114,8 @@ def setup_interfaces(CI: CarInterfaceBase, params: Params | None = None) -> None
def initialize_params(params) -> list[dict[str, Any]]:
keys: list = []
keys.append("RadarTracks")
# hyundai
keys.extend([
"HyundaiLongitudinalTuning",
@@ -6,6 +6,8 @@ See the LICENSE.md file in the root directory for more details.
"""
import time
import numpy as np
import openpilot.cereal.messaging as messaging
from openpilot.cereal import log, custom
@@ -17,6 +19,22 @@ from openpilot.sunnypilot.livedelay.helpers import get_lat_delay
from openpilot.sunnypilot.modeld_v2.modeld_base import ModelStateBase
from openpilot.sunnypilot.selfdrive.controls.lib.blinker_pause_lateral import BlinkerPauseLateral
from openpilot.sunnypilot.selfdrive.controls.lib.latcontrol_torque_v0 import LatControlTorque as LatControlTorqueV0
from openpilot.sunnypilot.selfdrive.controls.lib.pidd import LatControlPidd, pidd_selected
PATH_CURVATURE_LOOKAHEAD_SLICE = slice(2, 11) # ~0.04s to ~1.0s lookahead in T_IDXS
PATH_CURVATURE_MIN_SPEED = 1.0 # m/s
def path_curvature_ahead(model_v2) -> float:
vx = model_v2.velocity.x
oz = model_v2.orientationRate.z
if len(vx) < 11 or len(oz) < 11 or vx[0] < PATH_CURVATURE_MIN_SPEED:
return 0.0
vx_arr = np.maximum(np.asarray(vx, dtype=np.float64)[PATH_CURVATURE_LOOKAHEAD_SLICE], PATH_CURVATURE_MIN_SPEED)
oz_arr = np.asarray(oz, dtype=np.float64)[PATH_CURVATURE_LOOKAHEAD_SLICE]
return float(np.mean(oz_arr / vx_arr))
class ControlsExt(ModelStateBase):
@@ -30,11 +48,15 @@ class ControlsExt(ModelStateBase):
cloudlog.info("controlsd_ext is waiting for CarParamsSP")
self.CP_SP = messaging.log_from_bytes(params.get("CarParamsSP", block=True), custom.CarParamsSP)
cloudlog.info("controlsd_ext got CarParamsSP")
self.pidd: LatControlPidd | None = None
self.sm_services_ext = ['radarState', 'selfdriveStateSP']
self.pm_services_ext = ['carControlSP']
def initialize_lateral_control(self, lac, CI, dt):
if pidd_selected(self.CP):
self.pidd = LatControlPidd(self.CP, self.CP_SP, CI, dt)
return self.pidd
enforce_torque_control = self.params.get_bool("EnforceTorqueControl")
torque_versions = self.params.get("TorqueControlTune")
if not enforce_torque_control:
@@ -104,6 +126,8 @@ class ControlsExt(ModelStateBase):
CC_SP.intelligentCruiseButtonManagement.sendButton = icbm_src.sendButton
CC_SP.intelligentCruiseButtonManagement.vTarget = icbm_src.vTarget
CC_SP.pathCurvature = path_curvature_ahead(sm['modelV2'])
return CC_SP
@staticmethod
@@ -114,6 +138,13 @@ class ControlsExt(ModelStateBase):
pm.send('carControlSP', cc_sp_send)
def update_pidd_torque_params(self, sm: messaging.SubMaster) -> None:
torque_params = sm['lateralTorqueParameters']
if self.pidd is not None and sm.all_checks(['lateralTorqueParameters']) and torque_params.useParams:
self.pidd.update_torque_parameters(torque_params.latAccelFactorFiltered, torque_params.latAccelOffsetFiltered,
torque_params.frictionCoefficientFiltered)
def run_ext(self, sm: messaging.SubMaster, pm: messaging.PubMaster) -> None:
self.update_pidd_torque_params(sm)
CC_SP = self.state_control_ext(sm)
self.publish_ext(CC_SP, sm, pm)
@@ -1,4 +1,7 @@
{
"pidd": {
"version": "2.0"
},
"v1.0": {
"version": "1.0"
},
@@ -0,0 +1,180 @@
"""
Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors.
This file is part of sunnypilot and is licensed under the MIT License.
See the LICENSE.md file in the root directory for more details.
"""
import math
import numpy as np
from collections import deque
from opendbc.car.interfaces import get_torque_params
from opendbc.car.vehicle_model import VehicleModel
from openpilot.cereal import log
from openpilot.common.constants import ACCELERATION_DUE_TO_GRAVITY
from openpilot.common.filter_simple import FirstOrderFilter
from openpilot.common.pid import PIDController
from openpilot.selfdrive.controls.lib.latcontrol import LatControl
# gains are in lateral acceleration, scaled to torque per degree by each car's vehicle model and latAccelFactor
PIDD_VERSION = 2.0
INTERP_SPEEDS = [1.0, 1.5, 2.0, 3.0, 5.0, 7.5, 10.0, 15.0, 30.0]
KP_INTERP = [250.0, 120.0, 65.0, 30.0, 11.5, 5.5, 3.5, 2.0, 0.8]
TD_INTERP = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.15, 0.2]
HIGH_SPEED_BP = [25.0, 29.0]
TURN_RATE_BP = [5.0, 20.0]
TURN_LAT_ACCEL_BP = [0.18, 0.53]
DESIRED_ANGLE_BUFFER_SECONDS = 1.0
LIVE_LAT_ACCEL_FACTOR_RANGE = [1.0, 2.0]
LIVE_FRICTION_RANGE = [0.5, 2.0]
SWING_CAP_FRICTION = 1.3
def pidd_selected(CP):
return CP.steerControlType == 'torque' and CP.lateralTuning.which() == 'pid' and len(CP.lateralTuning.pid.kpBP) == 0 and \
CP.carFingerprint in get_torque_params()
def filter_rc(hz):
return 1 / (2 * math.pi * hz)
def lat_accel_per_deg(VM, v_ego):
return VM.calc_curvature(math.radians(1.0), v_ego, 0.0) * v_ego**2
class LatControlPidd(LatControl):
def __init__(self, CP, CP_SP, CI, dt):
super().__init__(CP, CP_SP, CI, dt)
torque_params = get_torque_params()[CP.carFingerprint]
self.VM = VehicleModel(CP)
self.pid = PIDController(0.0, 0.0, 0.0, pos_limit=self.steer_max, neg_limit=-self.steer_max)
self.offline_lat_accel_factor, self.offline_friction = float(torque_params['LAT_ACCEL_FACTOR']), float(torque_params['FRICTION'])
self.lat_accel_factor = self.friction = None
self.update_torque_parameters(self.offline_lat_accel_factor, 0.0, self.offline_friction)
self.error_filter = FirstOrderFilter(0.0, filter_rc(1.0), dt)
self.request_filter = FirstOrderFilter(0.0, filter_rc(3.0), dt, initialized=False)
self.error_rate_filter = FirstOrderFilter(0.0, 0.0354, dt)
self.wheel_angle_filter = FirstOrderFilter(0.0, filter_rc(10.0), dt, initialized=False)
self.wheel_rate_filter = FirstOrderFilter(0.0, 0.005, dt)
self.request_rate_ref = FirstOrderFilter(0.0, filter_rc(1.0), dt)
self.break_rate = FirstOrderFilter(0.0, filter_rc(0.5), dt)
self.break_rate2 = FirstOrderFilter(0.0, filter_rc(0.5), dt)
self.break_error = FirstOrderFilter(0.0, filter_rc(1.0), dt)
self.command_slow = FirstOrderFilter(0.0, filter_rc(0.5), dt, initialized=False)
self.last_error = 0.0
self.wheel_angle_held = None
self.swing = 0.0
buffer_len = int(DESIRED_ANGLE_BUFFER_SECONDS / dt)
self.desired_angle_buffer = deque([0.0] * buffer_len, maxlen=buffer_len)
self.delay_frames = int(np.clip(CP.steerActuatorDelay / dt + 1, 1, buffer_len))
self.rate_span_frames = max(1, int(0.1 / dt))
def update_torque_parameters(self, latAccelFactor, latAccelOffset, friction):
# a learned factor below the offline one would raise every gain
latAccelFactor = float(np.clip(latAccelFactor, *(r * self.offline_lat_accel_factor for r in LIVE_LAT_ACCEL_FACTOR_RANGE)))
friction = float(np.clip(friction, *(r * self.offline_friction for r in LIVE_FRICTION_RANGE)))
if (latAccelFactor, friction) == (self.lat_accel_factor, self.friction):
return
self.lat_accel_factor, self.friction = latAccelFactor, friction
self.kp = [kp * lat_accel_per_deg(self.VM, v) / latAccelFactor for kp, v in zip(KP_INTERP, INTERP_SPEEDS, strict=True)]
self.pid._k_p = (INTERP_SPEEDS, self.kp)
self.pid._k_i = (INTERP_SPEEDS, [kp / 6.0 for kp in self.kp])
self.pid._k_d = (INTERP_SPEEDS, [kp * td for kp, td in zip(self.kp, TD_INTERP, strict=True)])
def reset(self):
super().reset()
self.pid.reset()
self.swing = self.last_error = 0.0
self.command_slow.initialized = False
for f in (self.error_filter, self.error_rate_filter, self.wheel_rate_filter, self.request_rate_ref, self.break_error, self.break_rate, self.break_rate2):
f.x = 0.0
def update(self, active, CS, VM, params, steer_limited_by_safety, desired_curvature, calibrated_pose, curvature_limited, lat_delay):
pid_log = log.ControlsState.LateralPIDState.new_message()
pid_log.steeringAngleDeg = float(CS.steeringAngleDeg)
pid_log.steeringRateDeg = float(CS.steeringRateDeg)
high_speed = float(np.interp(CS.vEgo, HIGH_SPEED_BP, [0.0, 1.0]))
angle_steers_des_no_offset = self.request_filter.update(math.degrees(VM.get_steer_from_curvature(-desired_curvature, CS.vEgo, params.roll)))
angle_steers_des = angle_steers_des_no_offset + params.angleOffsetDeg
self.desired_angle_buffer.append(angle_steers_des)
expected_angle = self.desired_angle_buffer[-self.delay_frames]
request_rate = (self.desired_angle_buffer[-1] - self.desired_angle_buffer[-1 - self.rate_span_frames]) / (self.rate_span_frames * self.dt)
request_rate_ref = self.request_rate_ref.update(request_rate)
break_rate = self.break_rate2.update(self.break_rate.update(request_rate))
# a 1 Hz error filter lags enough for P to pump a 2 Hz wheel swing, so it opens up only while the request turns the wheel
error_filter_hz = float(np.interp(abs(request_rate_ref), TURN_RATE_BP, [1.0, 3.0]))
self.error_filter.update_alpha(filter_rc(float(np.interp(CS.vEgo, HIGH_SPEED_BP, [error_filter_hz, 1.0]))))
error = self.error_filter.update(expected_angle - CS.steeringAngleDeg)
# at highway speed, ignore the angle sensor toggling one count
held = self.wheel_angle_held if self.wheel_angle_held is not None else CS.steeringAngleDeg
wheel_backlash = 0.08 * high_speed
self.wheel_angle_held = held = CS.steeringAngleDeg - float(np.clip(CS.steeringAngleDeg - held, -wheel_backlash, wheel_backlash))
wheel_angle_last = self.wheel_angle_filter.x if self.wheel_angle_filter.initialized else held
wheel_rate = self.wheel_rate_filter.update((self.wheel_angle_filter.update(held) - wheel_angle_last) / self.dt)
wheel_swing = 0.0 if CS.steeringPressed else min(abs(wheel_rate - request_rate_ref), 60.0)
self.swing = max(wheel_swing, self.swing * (1.0 - self.dt))
pid_log.steeringAngleDesiredDeg = float(angle_steers_des)
pid_log.angleError = float(error)
if not active:
output_torque = 0.0
pid_log.active = False
self.reset()
else:
error_rate = self.error_rate_filter.update((error - self.last_error) / self.dt)
self.last_error = error
error_rate += high_speed * (-wheel_rate - error_rate)
ff = angle_steers_des_no_offset * lat_accel_per_deg(VM, CS.vEgo) / self.lat_accel_factor
ff += 0.4 * params.roll * ACCELERATION_DUE_TO_GRAVITY / self.lat_accel_factor
# break rack friction as soon as the request moves, before the error builds up
error_deadzone = error - float(np.clip(error, -0.3, 0.3))
turn_lat_accel = abs(desired_curvature) * max(CS.vEgo, 8.0) ** 2
friction_scale = float(np.interp(turn_lat_accel, TURN_LAT_ACCEL_BP, [0.6, 1.0]))
friction = self.friction * (friction_scale + high_speed * (0.1 - friction_scale))
friction_rate_gain = 0.75 - 0.25 * high_speed
ff += friction * float(np.tanh((error_deadzone + friction_rate_gain * request_rate) * 0.1887))
kp = float(np.interp(CS.vEgo, INTERP_SPEEDS, self.kp))
# damp the wheel toward the request's rate; the rack rings near 2 Hz without it
wheel_damp = 0.0 if CS.steeringPressed else (1.0 - high_speed) * kp * 0.05 * (wheel_rate - request_rate_ref)
ff -= wheel_damp
# half P on a straight, flat road; the cut goes through the feedforward so the integrator still holds a crown
kp_load = max(float(np.interp(turn_lat_accel, TURN_LAT_ACCEL_BP, [0.0, 1.0])),
float(np.interp(abs(params.roll) * ACCELERATION_DUE_TO_GRAVITY, [0.35, 0.7], [0.0, 1.0])))
kp_scale = 0.5 + 0.5 * kp_load
ff -= (1.0 - float(np.interp(CS.vEgo, [12.0, 18.0], [kp_scale, 1.0]))) * kp * error
ff += high_speed * 0.325 * self.friction * float(np.tanh((self.break_error.update(error) + 0.35 * break_rate) / 0.5))
freeze_integrator = steer_limited_by_safety or CS.steeringPressed or CS.vEgo < 5
error_rate_clean = error_rate - float(np.clip(error_rate, -0.3, 0.3))
output_torque = self.pid.update(error, error_rate=error_rate_clean, feedforward=ff, speed=CS.vEgo, freeze_integrator=freeze_integrator)
# a swing the request isn't asking for: pass only the command's slow part
command = output_torque + wheel_damp
self.command_slow.update(command)
if CS.steeringPressed:
self.command_slow.x = command
swing_gate = float(np.interp(self.swing, [16.0, 30.0], [0.0, 1.0])) * float(np.interp(CS.vEgo, [3.0, 5.0, 10.0, 14.0], [0.0, 1.0, 1.0, 0.0]))
swing_gate *= 1.0 - float(np.interp(abs(request_rate_ref), TURN_RATE_BP, [0.0, 1.0]))
swing_gate *= 1.0 - float(np.interp(turn_lat_accel, TURN_LAT_ACCEL_BP, [0.0, 1.0]))
swing_gate *= 1.0 - float(np.interp(abs(error), [3.0, 6.0], [0.0, 1.0]))
if not (CS.steeringPressed or CS.leftBlinker or CS.rightBlinker):
cap = SWING_CAP_FRICTION * self.friction
output_torque += swing_gate * float(np.clip(self.command_slow.x - command, -cap, cap))
output_torque = float(np.clip(output_torque, -self.steer_max, self.steer_max))
pid_log.active = True
pid_log.p = float(self.pid.p)
pid_log.i = float(self.pid.i)
pid_log.f = float(self.pid.f)
pid_log.output = float(output_torque)
pid_log.saturated = bool(self._check_saturation(self.steer_max - abs(output_torque) < 1e-3, CS, steer_limited_by_safety, curvature_limited))
return output_torque, angle_steers_des, pid_log
@@ -0,0 +1,127 @@
"""
Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors.
This file is part of sunnypilot and is licensed under the MIT License.
See the LICENSE.md file in the root directory for more details.
"""
import math
from types import SimpleNamespace
import numpy as np
import pytest
from opendbc.car.car_helpers import interfaces
from opendbc.car.honda.values import CAR as HONDA
from opendbc.car.hyundai.values import CAR as HYUNDAI
from opendbc.car.interfaces import get_torque_params
from opendbc.car.nissan.values import CAR as NISSAN
from opendbc.car.structs import car
from opendbc.car.toyota.values import CAR as TOYOTA
from opendbc.car.vehicle_model import VehicleModel
from openpilot.cereal import log
from openpilot.common.mock.generators import generate_deviceMotion
from openpilot.common.params import Params
from openpilot.common.realtime import DT_CTRL
from openpilot.common.test import OpenpilotTestCase
from openpilot.selfdrive.car.helpers import convert_to_capnp
from openpilot.selfdrive.locationd.helpers import Pose
from openpilot.selfdrive.locationd.torqued import TorqueEstimator
from openpilot.sunnypilot.selfdrive.car import interfaces as sunnypilot_interfaces
from openpilot.sunnypilot.selfdrive.controls.controlsd_ext import ControlsExt
from openpilot.sunnypilot.selfdrive.controls.lib.pidd import LatControlPidd, PIDD_VERSION
def setup_car(car_name):
CarInterface = interfaces[car_name]
CP = CarInterface.get_non_essential_params(car_name)
CP_SP = CarInterface.get_non_essential_params_sp(CP, car_name)
CI = CarInterface(CP, CP_SP)
sunnypilot_interfaces.setup_interfaces(CI)
return CI
def make_controller(CI):
return LatControlPidd(CI.CP.as_reader(), convert_to_capnp(CI.CP_SP).as_reader(), CI, DT_CTRL)
def drive(controller, CS, VM, angles, curvature=0.0):
params = log.VehicleParameters.new_message()
pose = Pose.from_device_motion(generate_deviceMotion().deviceMotion)
return [controller.update(True, CS, VM, params, False, curvature, pose, False, 0.2)[0] for CS.steeringAngleDeg in angles]
class TestPidd(OpenpilotTestCase):
def setup_method(self):
self.params = Params()
self.params.put_bool("EnforceTorqueControl", True, block=True)
self.params.put("TorqueControlTune", PIDD_VERSION, block=True)
def test_selected_on_any_torque_car(self):
for car_name in (HONDA.HONDA_CIVIC, TOYOTA.TOYOTA_RAV4, HYUNDAI.KIA_NIRO_EV):
assert setup_car(car_name).CP.lateralTuning.which() == 'pid'
def test_needs_enforce_torque(self):
self.params.remove("EnforceTorqueControl")
assert setup_car(HYUNDAI.KIA_NIRO_EV).CP.lateralTuning.which() == 'torque'
def test_not_on_angle_cars(self):
CI = setup_car(NISSAN.NISSAN_LEAF)
assert CI.CP.steerControlType == car.CarParams.SteerControlType.angle
assert not self.params.get_bool("EnforceTorqueControl")
def test_controlsd_builds_it(self):
CI = setup_car(HYUNDAI.KIA_NIRO_EV)
ext = SimpleNamespace(params=self.params, CP=CI.CP.as_reader(), CP_SP=convert_to_capnp(CI.CP_SP).as_reader())
assert isinstance(ControlsExt.initialize_lateral_control(ext, None, CI, DT_CTRL), LatControlPidd)
def test_selection_follows_car_params(self):
# params changing after card picked pidd must not leave controlsd with a pid that has no gains
CI = setup_car(HYUNDAI.KIA_NIRO_EV)
self.params.remove("EnforceTorqueControl")
self.params.put("TorqueControlTune", 1.0, block=True)
ext = SimpleNamespace(params=self.params, CP=CI.CP.as_reader(), CP_SP=convert_to_capnp(CI.CP_SP).as_reader())
assert isinstance(ControlsExt.initialize_lateral_control(ext, None, CI, DT_CTRL), LatControlPidd)
def test_damps_wheel_swing(self):
CI = setup_car(HONDA.HONDA_CIVIC)
VM = VehicleModel(CI.CP)
corr = {}
for pressed in (False, True):
controller = make_controller(CI)
CS = car.CarState.new_message(vEgo=8.0, steeringPressed=pressed)
angles = [2.0 * math.sin(2 * math.pi * 2.0 * i * DT_CTRL) for i in range(300)]
out = drive(controller, CS, VM, angles)[100:]
rate = [math.cos(2 * math.pi * 2.0 * i * DT_CTRL) for i in range(100, 300)]
corr[pressed] = float(np.corrcoef(out, rate)[0, 1])
assert corr[False] < corr[True] - 0.3
def test_output_within_steer_max(self):
CI = setup_car(HYUNDAI.KIA_NIRO_EV)
controller = make_controller(CI)
controller.pid.update = lambda *args, **kwargs: controller.steer_max
CS = car.CarState.new_message(vEgo=8.0)
out = drive(controller, CS, VehicleModel(CI.CP), [2.0 * math.sin(2 * math.pi * 2.5 * i * DT_CTRL) for i in range(500)])
assert max(abs(x) for x in out) <= controller.steer_max
def test_reset_clears_swing_gate(self):
CI = setup_car(HYUNDAI.KIA_NIRO_EV)
controller = make_controller(CI)
drive(controller, car.CarState.new_message(vEgo=8.0), VehicleModel(CI.CP), [30.0] * 200, curvature=-0.02)
controller.reset()
assert not controller.command_slow.initialized
def test_live_torque_params_rescale_gains(self):
controller = make_controller(setup_car(HYUNDAI.KIA_NIRO_EV))
kp = list(controller.kp)
controller.update_torque_parameters(2 * controller.lat_accel_factor, 0.0, controller.friction)
assert np.allclose(controller.kp, [k / 2 for k in kp])
assert np.allclose(controller.pid._k_p[1], controller.kp)
controller.update_torque_parameters(0.5 * controller.offline_lat_accel_factor, 0.0, 0.0)
assert np.allclose(controller.kp, kp)
def test_torqued_learns_under_pidd(self):
estimator = TorqueEstimator(setup_car(HYUNDAI.KIA_NIRO_EV).CP.as_reader())
offline = get_torque_params()[HYUNDAI.KIA_NIRO_EV]
assert estimator.offline_latAccelFactor == pytest.approx(offline['LAT_ACCEL_FACTOR'])
assert estimator.offline_friction == pytest.approx(offline['FRICTION'])
assert estimator.max_lataccel_factor > estimator.min_lataccel_factor
@@ -6,11 +6,13 @@ See the LICENSE.md file in the root directory for more details.
"""
import numpy as np
from opendbc.car.interfaces import get_torque_params
from opendbc.car.structs import car
from openpilot.common.params import Params
from openpilot.common.realtime import DT_MDL
from openpilot.sunnypilot import PARAMS_UPDATE_PERIOD
from openpilot.sunnypilot.selfdrive.controls.lib.pidd import pidd_selected
RELAXED_MIN_BUCKET_POINTS = np.array([1, 200, 300, 500, 500, 300, 200, 1])
@@ -37,6 +39,11 @@ class TorqueEstimatorExt:
def initialize_custom_params(self, decimated=False):
self.update_use_params()
if pidd_selected(self.CP):
torque_params = get_torque_params()[self.CP.carFingerprint]
self.offline_latAccelFactor = float(torque_params['LAT_ACCEL_FACTOR'])
self.offline_friction = float(torque_params['FRICTION'])
if self.enforce_torque_control_toggle:
if self._params.get_bool("LiveTorqueParamsRelaxedToggle"):
self.min_bucket_points = RELAXED_MIN_BUCKET_POINTS / (10 if decimated else 1)
@@ -249,6 +249,14 @@ EVENTS_SP: dict[int, dict[str, Alert | AlertCallbackType]] = {
Priority.LOW, VisualAlert.none, AudibleAlert.prompt, 0.1),
},
EventNameSP.stockSteerIntervention: {
ET.PERMANENT: Alert(
"TAKE CONTROL",
"Stock Emergency Assist: Risk of Collision",
AlertStatus.critical, AlertSize.mid,
Priority.HIGH, VisualAlert.steerRequired, AudibleAlert.none, 2.),
},
EventNameSP.bigModelReady: {
ET.PERMANENT: Alert(
"Big Model Ready",
@@ -0,0 +1,269 @@
"""
Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors.
This file is part of sunnypilot and is licensed under the MIT License.
See the LICENSE.md file in the root directory for more details.
"""
import os
import time
import wave
import numpy as np
from openpilot.cereal import custom, log
from openpilot.common.basedir import BASEDIR
from openpilot.common.swaglog import cloudlog
AudibleAlert = log.SelfdriveState.AudibleAlert
AudibleAlertSP = custom.SelfdriveStateSP.AudibleAlert
ROBOTIC_SOUNDS_DIR = os.path.join(BASEDIR, "openpilot/sunnypilot/selfdrive/assets/sounds/robotic")
ROBOTIC_SOUND_FILES: dict[int, str] = {
AudibleAlert.engage: "engage.wav",
AudibleAlert.disengage: "disengage.wav",
AudibleAlert.refuse: "refuse.wav",
AudibleAlert.prompt: "warning.wav",
AudibleAlert.promptRepeat: "warning_repeat.wav",
AudibleAlert.promptDistracted: "dm_warning.wav",
AudibleAlert.preAlert: "pre_alert.wav",
AudibleAlert.warningSoft: "critical.wav",
AudibleAlert.warningImmediate: "dm_critical.wav",
AudibleAlertSP.promptSingleLow: "prompt_single_low.wav",
AudibleAlertSP.promptSingleHigh: "prompt_single_high.wav",
}
# Custom reactive robotic chirp IDs (non-overlapping with AudibleAlert / AudibleAlertSP enums)
CHIRP_SPEED_UP = 1001
CHIRP_SPEED_DOWN = 1002
CHIRP_STARTLED = 1003
CHIRP_BOOST = 1004
CHIRP_BOOKMARK = 1005
CHIRP_BLINKER = 1006
REACTIVE_CHIRP_IDS = {
CHIRP_SPEED_UP,
CHIRP_SPEED_DOWN,
CHIRP_STARTLED,
CHIRP_BOOST,
CHIRP_BOOKMARK,
CHIRP_BLINKER,
}
SET_SPEED_NA = 255
CHIRP_COOLDOWN = 0.6 # minimum seconds between reactive chirps
def _adsr(n: int, sr: int, attack: float = 0.012, release: float = 0.035) -> np.ndarray:
env = np.ones(n, dtype=np.float32)
a_n = min(n // 2, int(attack * sr))
r_n = min(n // 2, int(release * sr))
if a_n > 0:
env[:a_n] = np.linspace(0.0, 1.0, a_n, dtype=np.float32)
if r_n > 0:
env[-r_n:] = np.linspace(1.0, 0.0, r_n, dtype=np.float32)
return env
def synth_emo_chirp(
f_start: float,
f_end: float,
duration: float,
sr: int = 48000,
vibrato_hz: float = 0.0,
vibrato_depth: float = 0.0,
gain: float = 0.85,
) -> np.ndarray:
"""Synthesize a bright, bubbly EMO-style harmonic chirp in pure NumPy."""
n = max(1, int(sr * duration))
t = np.arange(n, dtype=np.float32) / sr
p = t / max(duration, 1e-6)
s_curve = p * p * (3.0 - 2.0 * p)
freq = f_start + (f_end - f_start) * s_curve
if vibrato_hz > 0.0:
freq = freq + vibrato_depth * np.sin(2.0 * np.pi * vibrato_hz * t)
phase = 2.0 * np.pi * np.cumsum(freq) / sr
sig = (
0.66 * np.sin(phase)
+ 0.24 * np.sin(2.0 * phase + 0.35)
+ 0.10 * np.sin(3.0 * phase)
)
env = _adsr(n, sr, attack=min(0.012, duration * 0.2), release=min(0.045, duration * 0.35))
return np.clip(sig * env * gain, -0.98, 0.98).astype(np.float32)
def _sil(duration: float, sr: int = 48000) -> np.ndarray:
return np.zeros(int(sr * duration), dtype=np.float32)
def build_procedural_sounds(sr: int = 48000) -> dict[int, np.ndarray]:
"""Build bubbly EMO chirps in pure NumPy (used for reactive chirps and guaranteed WAV fallback)."""
return {
# Core alert fallbacks (in case WAV LFS files are unavailable on device)
AudibleAlert.engage: np.concatenate([
synth_emo_chirp(660, 1020, 0.10, sr, gain=0.86),
_sil(0.025, sr),
synth_emo_chirp(1020, 1580, 0.18, sr, vibrato_hz=24, vibrato_depth=28, gain=0.90),
]),
AudibleAlert.disengage: np.concatenate([
synth_emo_chirp(1080, 740, 0.12, sr, gain=0.82),
_sil(0.025, sr),
synth_emo_chirp(700, 440, 0.18, sr, gain=0.80),
]),
AudibleAlert.refuse: np.concatenate([
synth_emo_chirp(480, 340, 0.11, sr, vibrato_hz=32, vibrato_depth=28, gain=0.85),
_sil(0.04, sr),
synth_emo_chirp(390, 270, 0.15, sr, vibrato_hz=32, vibrato_depth=28, gain=0.85),
]),
AudibleAlert.preAlert: synth_emo_chirp(860, 1480, 0.20, sr, vibrato_hz=26, vibrato_depth=22, gain=0.84),
AudibleAlertSP.promptSingleLow: synth_emo_chirp(620, 500, 0.18, sr, gain=0.80),
AudibleAlertSP.promptSingleHigh: synth_emo_chirp(1080, 1420, 0.16, sr, gain=0.84),
AudibleAlert.prompt: np.concatenate([
synth_emo_chirp(920, 1340, 0.11, sr, gain=0.88),
_sil(0.03, sr),
synth_emo_chirp(1340, 1040, 0.16, sr, gain=0.86),
]),
AudibleAlert.promptRepeat: np.concatenate([
synth_emo_chirp(960, 1380, 0.11, sr, gain=0.88),
_sil(0.03, sr),
synth_emo_chirp(1380, 1060, 0.15, sr, gain=0.86),
_sil(0.28, sr),
]),
AudibleAlert.promptDistracted: np.concatenate([
synth_emo_chirp(840, 1280, 0.09, sr, gain=0.90),
_sil(0.025, sr),
synth_emo_chirp(980, 1480, 0.12, sr, vibrato_hz=22, vibrato_depth=20, gain=0.90),
_sil(0.30, sr),
]),
AudibleAlert.warningSoft: np.concatenate([
synth_emo_chirp(1380, 1680, 0.10, sr, gain=0.94),
_sil(0.025, sr),
synth_emo_chirp(1680, 1260, 0.14, sr, gain=0.94),
_sil(0.22, sr),
]),
AudibleAlert.warningImmediate: np.concatenate([
synth_emo_chirp(1520, 1880, 0.09, sr, gain=0.96),
_sil(0.02, sr),
synth_emo_chirp(1520, 1880, 0.09, sr, gain=0.96),
_sil(0.02, sr),
synth_emo_chirp(1880, 1400, 0.12, sr, gain=0.96),
_sil(0.18, sr),
]),
# Reactive chirps for driving & user interactions
CHIRP_SPEED_UP: np.concatenate([
synth_emo_chirp(880, 1180, 0.075, sr, gain=0.72),
_sil(0.015, sr),
synth_emo_chirp(1180, 1520, 0.09, sr, gain=0.75),
]),
CHIRP_SPEED_DOWN: np.concatenate([
synth_emo_chirp(1220, 940, 0.075, sr, gain=0.70),
_sil(0.015, sr),
synth_emo_chirp(940, 680, 0.09, sr, gain=0.70),
]),
CHIRP_STARTLED: np.concatenate([
synth_emo_chirp(720, 1680, 0.11, sr, vibrato_hz=38, vibrato_depth=45, gain=0.82),
_sil(0.02, sr),
synth_emo_chirp(1480, 980, 0.10, sr, gain=0.78),
]),
CHIRP_BOOST: np.concatenate([
synth_emo_chirp(640, 1040, 0.07, sr, gain=0.76),
_sil(0.015, sr),
synth_emo_chirp(1040, 1640, 0.13, sr, vibrato_hz=28, vibrato_depth=35, gain=0.80),
]),
CHIRP_BOOKMARK: np.concatenate([
synth_emo_chirp(980, 1380, 0.07, sr, gain=0.78),
_sil(0.02, sr),
synth_emo_chirp(1240, 1720, 0.10, sr, vibrato_hz=24, vibrato_depth=25, gain=0.82),
]),
CHIRP_BLINKER: synth_emo_chirp(920, 1180, 0.065, sr, gain=0.55),
}
class RoboticSoundPack:
"""Manages pre-loaded robotic voice/chirp buffers and reactive driving chirps for Soundd."""
def __init__(self, params, sample_rate: int = 48000):
self._params = params
self._sample_rate = sample_rate
self.enabled: bool = self._params.get_bool("MiciRoboticUI")
self.sounds: dict[int, np.ndarray] = {}
# Edge-detection state for reactive chirps
self._prev_set_speed: float = SET_SPEED_NA
self._prev_blinker: bool = False
self._last_chirp_time: float = 0.0
def load(self) -> None:
# Start with guaranteed pure-NumPy procedural chirps so soundd never fails if LFS WAVs are missing
self.sounds = build_procedural_sounds(self._sample_rate)
for alert_id, filename in ROBOTIC_SOUND_FILES.items():
path = os.path.join(ROBOTIC_SOUNDS_DIR, filename)
if not os.path.exists(path):
cloudlog.warning(f"Robotic sound file missing, using procedural fallback: {path}")
continue
try:
with wave.open(path, "r") as wavefile:
if (
wavefile.getnchannels() != 1
or wavefile.getsampwidth() != 2
or wavefile.getframerate() != self._sample_rate
):
cloudlog.warning(f"Robotic sound format mismatch, using procedural fallback: {path}")
continue
length = wavefile.getnframes()
if length > 0:
self.sounds[alert_id] = np.frombuffer(wavefile.readframes(length), dtype=np.int16).astype(np.float32) / (2**16 / 2)
except Exception as e:
cloudlog.warning(f"Failed to load robotic WAV (possible Git LFS pointer), using procedural fallback: {path} ({e})")
def refresh_param(self) -> bool:
"""Refresh MiciRoboticUI param; returns True if the enabled state changed."""
new_val = self._params.get_bool("MiciRoboticUI")
changed = new_val != self.enabled
self.enabled = new_val
return changed
def get_buffer(self, alert_id: int, default_sounds: dict[int, np.ndarray]) -> np.ndarray:
if self.enabled and alert_id in self.sounds:
return self.sounds[alert_id]
return default_sounds[alert_id]
def detect_reactive_chirp(self, sm, now: float | None = None) -> int | None:
"""Detect driving/user events that should emit a cute one-shot robotic chirp."""
if not self.enabled:
return None
t = time.monotonic() if now is None else now
if t - self._last_chirp_time < CHIRP_COOLDOWN:
return None
chirp: int | None = None
if sm.updated.get("userBookmark") or sm.updated.get("bookmarkButton"):
chirp = CHIRP_BOOKMARK
elif sm.updated.get("carState"):
cs = sm["carState"]
v_cruise = cs.vCruiseCluster
if v_cruise == 0.0 and sm.valid.get("controlsState"):
v_cruise = sm["controlsState"].deprecated.vCruise
cruise_set = 0 < v_cruise < SET_SPEED_NA
if cruise_set and self._prev_set_speed != SET_SPEED_NA and v_cruise != self._prev_set_speed:
chirp = CHIRP_SPEED_UP if v_cruise > self._prev_set_speed else CHIRP_SPEED_DOWN
self._prev_set_speed = v_cruise
blinker = bool(cs.leftBlinker or cs.rightBlinker)
if chirp is None and blinker and not self._prev_blinker:
chirp = CHIRP_BLINKER
self._prev_blinker = blinker
if chirp is None and not cs.standstill:
if cs.aEgo < -3.0:
chirp = CHIRP_STARTLED
elif cs.aEgo > 2.2:
chirp = CHIRP_BOOST
if chirp is not None:
self._last_chirp_time = t
return chirp
@@ -0,0 +1,25 @@
"""
Copyright (c) 2021-, sunnypilot, and a number of other contributors.
This file is part of sunnypilot and is licensed under the MIT License.
See the LICENSE.md file in the root directory for more details.
"""
# Parameters that should never be remotely modified
BLOCKED_PARAMS = {
"AdbEnabled",
"BluetoothAllowed",
"BluetoothEnabled",
"CompletedSunnylinkConsentVersion",
"CompletedTrainingVersion",
"GithubUsername", # Could grant SSH access
"GithubSshKeys", # Direct SSH key injection
"HasAcceptedTerms",
"HasAcceptedTermsSP",
"OnroadCycleRequested", # Prevent remote cycle trigger
"ParamsVersion", # Device-managed version counter
}
def is_local_param(key: str) -> bool:
return key.startswith("SunnylinkLocal")
@@ -44,18 +44,7 @@ DISALLOW_LOG_UPLOAD = threading.Event()
params = Params()
# Parameters that should never be remotely modified
BLOCKED_PARAMS = {
"AdbEnabled",
"CompletedSunnylinkConsentVersion",
"CompletedTrainingVersion",
"GithubUsername", # Could grant SSH access
"GithubSshKeys", # Direct SSH key injection
"HasAcceptedTerms",
"HasAcceptedTermsSP",
"OnroadCycleRequested", # Prevent remote cycle trigger
"ParamsVersion", # Device-managed version counter
}
from openpilot.sunnypilot.sunnylink.athena.params_guard import BLOCKED_PARAMS, is_local_param
def handle_long_poll(ws: WebSocket, exit_event: threading.Event | None) -> None:
@@ -166,7 +155,7 @@ def toggleLogUpload(enabled: bool):
@dispatcher.add_method
def getParamsAllKeys() -> list[str]:
keys: list[str] = [k.decode('utf-8') for k in Params().all_keys()]
return keys
return [key for key in keys if not is_local_param(key)]
@dispatcher.add_method
@@ -208,7 +197,7 @@ def getParams(params_keys: list[str], compression: bool = False) -> str | dict[s
ParamKeyType.BYTES.value: b"",
}
param_keys_validated = [key for key in params_keys if key in available_keys]
param_keys_validated = [key for key in params_keys if key in available_keys and not is_local_param(key)]
params_dict: dict[str, list[dict[str, str | bool | int]]] = {"params": []}
for key in param_keys_validated:
value = get_param_as_byte(key)
@@ -238,7 +227,7 @@ def getParams(params_keys: list[str], compression: bool = False) -> str | dict[s
def saveParams(params_to_update: dict[str, str], compression: bool = False) -> None:
for key, value in params_to_update.items():
# disallow modifications to blocked parameters
if key in BLOCKED_PARAMS:
if key in BLOCKED_PARAMS or is_local_param(key):
cloudlog.warning(f"sunnylinkd.saveParams.blocked: Attempted to modify blocked parameter '{key}'")
continue
@@ -58,3 +58,24 @@ class TestSunnylinkdMethods(OpenpilotTestCase):
assert len(self.saved_params) == 1
assert self.saved_params[0][0] == "SpeedLimitOffset"
assert self.saved_params[0][1] == "10"
def test_saveParams_refuses_local_and_bluetooth_params(self):
sunnylinkd.saveParams({
"SunnylinkLocalBleGrants": "e30=",
"SunnylinkLocalConnectPhoneRequest": "e30=",
"BluetoothAllowed": "MQ==",
"BluetoothEnabled": "MQ==",
"SpeedLimitOffset": "5",
})
assert [p[0] for p in self.saved_params] == ["SpeedLimitOffset"]
def test_local_params_are_hidden(self, mocker):
params = mocker.patch.object(sunnylinkd, "Params").return_value
params.all_keys.return_value = [b"SunnylinkEnabled", b"SunnylinkLocalBleGrants", b"SunnylinkLocalConnectPhoneWindow"]
mocker.patch.object(sunnylinkd, "get_param_as_byte", return_value=b"1")
assert sunnylinkd.getParamsAllKeys() == ["SunnylinkEnabled"]
response = sunnylinkd.getParams(["SunnylinkEnabled", "SunnylinkLocalBleGrants", "SunnylinkLocalConnectPhoneWindow"])
assert set(response) == {"SunnylinkEnabled", "params"}
assert "SunnylinkLocal" not in response["params"]

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