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
601 changed files with 26332 additions and 13099 deletions
+1
View File
@@ -2,5 +2,6 @@ Wen
REGIST
PullRequest
cancelled
indeces
FOF
NoO
-1
View File
@@ -11,7 +11,6 @@ openpilot/sunnypilot/modeld_v2/models/*.pkl filter=lfs diff=lfs merge=lfs -text
*.ttf filter=lfs diff=lfs merge=lfs -text
*.otf filter=lfs diff=lfs merge=lfs -text
*.wav filter=lfs diff=lfs merge=lfs -text
*.npz filter=lfs diff=lfs merge=lfs -text
openpilot/selfdrive/car/tests/test_models_segs.txt filter=lfs diff=lfs merge=lfs -text
openpilot/common/hardware/comma/updater filter=lfs diff=lfs merge=lfs -text
+1 -1
View File
@@ -1,6 +1,6 @@
ci:
- changed-files:
- any-glob-to-all-files: "{.github/**,**/test_*,**/test/**}"
- any-glob-to-all-files: "{.github/**,**/test_*,**/test/**,Jenkinsfile}"
chore:
- changed-files:
-56
View File
@@ -1,56 +0,0 @@
name: Compile and check the big warps
description: Compile the chestnut warps for each camera and warm up stock modeld on them, on the amd mock
runs:
using: composite
steps:
- run: ./tools/op.sh setup
shell: bash
- name: Build modeld deps
shell: bash
run: scons -j$(nproc) msgq_repo/msgq openpilot/common
- name: Compile big warp
shell: bash
run: |
export PYTHONPATH="${{ github.workspace }}/tinygrad_repo:${{ github.workspace }}"
CHESTNUT_TG_FLAGS="DEBUG=1 DEV=USB+AMD:LLVM FRAME_DEV=CPU FLOAT16=1 JIT_BATCH_SIZE=0 GMMU=0 CHECK_OOB=0 TC_OPT=2 TC_MIN_GLOBALS=32"
COMPILER="${{ github.workspace }}/tinygrad_repo/examples/openpilot"
MODELS_DIR="${{ github.workspace }}/openpilot/selfdrive/modeld/models"
MODEL_SIZE=$(python3 -c "from openpilot.common.transformations.model import MEDMODEL_INPUT_SIZE as s; print(f'{s[0]}x{s[1]}')")
for res in $(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}')"); do
CAM_W=$(echo $res | cut -d x -f1)
CAM_H=$(echo $res | cut -d x -f2)
STRIDE_INFO=$(python3 -c "
import sys
from openpilot.system.camerad.cameras.nv12_info import get_nv12_info
s,y,u,sz = get_nv12_info(int(sys.argv[1]), int(sys.argv[2]))
print(f'{s},{y},{u},{s*(y+u)}')
" $CAM_W $CAM_H)
WARP_PKL="${MODELS_DIR}/big_driving_warp_${res}_tinygrad.pkl"
python3 tinygrad_repo/test/mockgpu/usb_server.py env PYTHONPATH="$PYTHONPATH" ${CHESTNUT_TG_FLAGS} python3 "${COMPILER}/compile_warp.py" \
--frame ${CAM_W},${CAM_H},${STRIDE_INFO} \
--warp-to ${MODEL_SIZE} \
--layout yuv420 \
--frames 2 \
--benchmark-runs 0 \
--retargetable \
--output "${WARP_PKL}"
done
- name: Warm up stock modeld on the big warps
shell: bash
run: |
export PYTHONPATH="${{ github.workspace }}/tinygrad_repo:${{ github.workspace }}"
fail=0
for res in $(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}')"); do
echo "warming up stock modeld on ${res}"
python3 tinygrad_repo/test/mockgpu/usb_server.py env PYTHONPATH="$PYTHONPATH" GMMU=0 CHECK_OOB=0 python3 -c "
import sys
from openpilot.selfdrive.modeld.modeld import ModelState
ModelState(*map(int, sys.argv[1].split('x')), chestnut=True).warmup()
" $res || { echo "::error::stock modeld warmup failed on the ${res} big warp"; fail=1; }
done
exit $fail
+126 -40
View File
@@ -77,8 +77,9 @@ jobs:
build_small_model:
needs: resolve
if: ${{ inputs.target == 'small' }}
runs-on: ubuntu-24.04-arm
runs-on: [self-hosted, tici]
env:
MODELS_DIR: openpilot/selfdrive/modeld/models
COMPILER: tinygrad_repo/examples/openpilot
SMALL_ONNX: openpilot/selfdrive/modeld/models/driving_supercombo.onnx
SMALL_PKL: openpilot/selfdrive/modeld/models/driving_tinygrad.pkl
@@ -88,30 +89,39 @@ jobs:
submodules: recursive
- name: Pull small ONNX via LFS
run: ./lfs.py pull --exclude='' # ponytail: pulls every LFS file (lfs.py has no include filter); HF egress is free
run: git lfs pull -I "${{ env.SMALL_ONNX }}"
- uses: actions/setup-python@v5
with:
python-version: '3.12'
- name: Set up the qcom mock
uses: ./.github/workflows/setup-qcom-mock
with:
hf_token: ${{ secrets.HF_TOKEN }}
- name: Set environment variables
run: |
source /etc/profile
export UV_PROJECT_ENVIRONMENT=${HOME}/venv
export UV_PYTHON_PREFERENCE=managed
export UV_PYTHON_INSTALL_DIR=${HOME}/uv/python
export VIRTUAL_ENV=$UV_PROJECT_ENVIRONMENT
uv sync --frozen
printenv >> $GITHUB_ENV
- name: Disable powersave
run: |
source ${UV_PROJECT_ENVIRONMENT}/bin/activate
PYTHONPATH=$PYTHONPATH:${{ github.workspace }}/ ${{ github.workspace }}/scripts/manage-powersave.py --disable
- name: Compile small model from ONNX
run: |
export PYTHONPATH="${{ github.workspace }}/tinygrad_repo:${{ github.workspace }}"
TG_FLAGS="DEV=MOCK+QCOM HCQ_RUNTIME_DEV=CPU:LLVM:arm64,cortex-a75,fp-armv8,sha2,lse,neon,crc,aes IMAGE=1 FLOAT16=1 NOLOCALS=1 JIT_BATCH_SIZE=0 OPENPILOT_HACKS=1"
source ${UV_PROJECT_ENVIRONMENT}/bin/activate
export PYTHONPATH="${PYTHONPATH}:${{ github.workspace }}/tinygrad_repo:${{ github.workspace }}"
TG_FLAGS="DEV=QCOM IMAGE=1 FLOAT16=1 NOLOCALS=1 JIT_BATCH_SIZE=0 OPENPILOT_HACKS=1"
env ${TG_FLAGS} python3 ${{ github.workspace }}/${{ env.COMPILER }}/compile_onnx.py \
${{ github.workspace }}/${{ env.SMALL_ONNX }} \
${{ github.workspace }}/${{ env.SMALL_PKL }} \
--out-of-band --benchmark-runs 0
--out-of-band --benchmark-runs 1
- name: Prepare output
env:
MODEL_NAME: ${{ needs.resolve.outputs.safe_model_name }}
run: |
source ${UV_PROJECT_ENVIRONMENT}/bin/activate
export PYTHONPATH=${{ github.workspace }}
MODELS_DIR="${{ github.workspace }}/openpilot/selfdrive/modeld/models"
OUTPUT_DIR="${{ github.workspace }}/small_output"
@@ -143,11 +153,19 @@ jobs:
name: artifact-name-${{ needs.resolve.outputs.safe_model_name }}
path: ${{ github.workspace }}/small_output/artifact_name.txt
- name: Re-enable powersave
if: always()
run: |
source ${UV_PROJECT_ENVIRONMENT}/bin/activate
PYTHONPATH=$PYTHONPATH:${{ github.workspace }}/ ${{ github.workspace }}/scripts/manage-powersave.py --enable
build_big_model:
needs: resolve
if: ${{ inputs.target == 'big' }}
runs-on: ubuntu-24.04
runs-on: [self-hosted, chestnut]
env:
MODELS_DIR: openpilot/selfdrive/modeld/models
COMPILER: tinygrad_repo/examples/openpilot
BIG_PKL: openpilot/selfdrive/modeld/models/big_driving_tinygrad.pkl
steps:
- uses: actions/checkout@v4
@@ -155,23 +173,72 @@ jobs:
submodules: recursive
- name: Pull big PKL via LFS
run: ./lfs.py pull --exclude='' # ponytail: pulls every LFS file (lfs.py has no include filter); HF egress is free
run: git lfs pull -I "${{ env.BIG_PKL }}"
- uses: actions/setup-python@v5
with:
python-version: '3.12'
- name: Set environment variables
run: |
source /etc/profile
export UV_PROJECT_ENVIRONMENT=${HOME}/venv
export UV_PYTHON_PREFERENCE=managed
export UV_PYTHON_INSTALL_DIR=${HOME}/uv/python
export VIRTUAL_ENV=$UV_PROJECT_ENVIRONMENT
uv sync --frozen
printenv >> $GITHUB_ENV
- name: Install LLVM 20 and ROCm comgr for the amd mock
uses: ./.github/workflows/setup-amd-mock
with:
emu_cache: big-warp
- name: Disable powersave
run: |
source ${UV_PROJECT_ENVIRONMENT}/bin/activate
PYTHONPATH=$PYTHONPATH:${{ github.workspace }}/ ${{ github.workspace }}/scripts/manage-powersave.py --disable
- uses: ./.github/workflows/big-warp
- name: Wait for chestnut PCIe link
run: |
source ${UV_PROJECT_ENVIRONMENT}/bin/activate
export PYTHONPATH="${PYTHONPATH}:${{ github.workspace }}/tinygrad_repo:${{ github.workspace }}"
python3 -c "
import time
from openpilot.system.hardware.chestnut.flash import link_up
for i in range(10):
if link_up():
print(f'PCIe link up after {i+1} attempt(s)')
break
time.sleep(1)
else:
raise RuntimeError('Chestnut PCIe link not ready after 10 attempts')
"
- name: Compile big warp
run: |
source ${UV_PROJECT_ENVIRONMENT}/bin/activate
export PYTHONPATH="${PYTHONPATH}:${{ github.workspace }}/tinygrad_repo:${{ github.workspace }}"
CHESTNUT_TG_FLAGS="DEBUG=1 DEV=USB+AMD:LLVM FRAME_DEV=CPU FLOAT16=1 JIT_BATCH_SIZE=0 GMMU=0 TC_OPT=2 TC_MIN_GLOBALS=32"
COMPILER="${{ github.workspace }}/tinygrad_repo/examples/openpilot"
MODELS_DIR="${{ github.workspace }}/openpilot/selfdrive/modeld/models"
MODEL_SIZE=$(python3 -c "from openpilot.common.transformations.model import MEDMODEL_INPUT_SIZE as s; print(f'{s[0]}x{s[1]}')")
for res in $(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}')"); do
CAM_W=$(echo $res | cut -d x -f1)
CAM_H=$(echo $res | cut -d x -f2)
STRIDE_INFO=$(python3 -c "
import sys
from openpilot.system.camerad.cameras.nv12_info import get_nv12_info
s,y,u,sz = get_nv12_info(int(sys.argv[1]), int(sys.argv[2]))
print(f'{s},{y},{u},{sz}')
" $CAM_W $CAM_H)
WARP_PKL="${MODELS_DIR}/big_driving_warp_${res}_tinygrad.pkl"
env ${CHESTNUT_TG_FLAGS} python3 "${COMPILER}/compile_warp.py" \
--frame ${CAM_W},${CAM_H},${STRIDE_INFO} \
--warp-to ${MODEL_SIZE} \
--layout yuv420 \
--frames 2 \
--output "${WARP_PKL}"
done
- name: Prepare output
env:
MODEL_NAME: ${{ needs.resolve.outputs.safe_model_name }}
run: |
source ${UV_PROJECT_ENVIRONMENT}/bin/activate
export PYTHONPATH=${{ github.workspace }}
MODELS_DIR="${{ github.workspace }}/openpilot/selfdrive/modeld/models"
OUTPUT_DIR="${{ github.workspace }}/big_output"
@@ -205,6 +272,12 @@ jobs:
name: artifact-name-${{ needs.resolve.outputs.safe_model_name }}
path: ${{ github.workspace }}/big_output/artifact_name.txt
- name: Re-enable powersave
if: always()
run: |
source ${UV_PROJECT_ENVIRONMENT}/bin/activate
PYTHONPATH=$PYTHONPATH:${{ github.workspace }}/ ${{ github.workspace }}/scripts/manage-powersave.py --enable
upload_defaults:
needs: [ resolve, build_small_model, build_big_model, build_dm_model ]
if: |
@@ -223,7 +296,7 @@ jobs:
- name: Pull LFS for resolved ONNX files
if: ${{ needs.resolve.outputs.onnx_path != '' }}
run: ./lfs.py pull --exclude='' # ponytail: pulls every LFS file (lfs.py has no include filter); HF egress is free
run: git lfs pull -I "${{ needs.resolve.outputs.onnx_path }}"
- name: Install huggingface_hub
run: pip install --upgrade "huggingface_hub>=0.22.0"
@@ -332,7 +405,7 @@ jobs:
build_dm_model:
needs: resolve
if: ${{ inputs.target == 'dm' }}
runs-on: ubuntu-24.04-arm
runs-on: [self-hosted, tici]
env:
DM_ONNX: openpilot/selfdrive/modeld/models/dmonitoring_model.onnx
DM_PKL: openpilot/selfdrive/modeld/models/dmonitoring_model_tinygrad.pkl
@@ -342,34 +415,42 @@ jobs:
submodules: recursive
- name: Pull DM ONNX via LFS
run: ./lfs.py pull --exclude='' # ponytail: pulls every LFS file (lfs.py has no include filter); HF egress is free
run: git lfs pull -I "${{ env.DM_ONNX }}"
- uses: actions/setup-python@v5
with:
python-version: '3.12'
- name: Set environment variables
run: |
source /etc/profile
export UV_PROJECT_ENVIRONMENT=${HOME}/venv
export UV_PYTHON_PREFERENCE=managed
export UV_PYTHON_INSTALL_DIR=${HOME}/uv/python
export VIRTUAL_ENV=$UV_PROJECT_ENVIRONMENT
uv sync --frozen
printenv >> $GITHUB_ENV
- name: Set up the qcom mock
uses: ./.github/workflows/setup-qcom-mock
with:
hf_token: ${{ secrets.HF_TOKEN }}
- name: Disable powersave
run: |
source ${UV_PROJECT_ENVIRONMENT}/bin/activate
PYTHONPATH=$PYTHONPATH:${{ github.workspace }}/ ${{ github.workspace }}/scripts/manage-powersave.py --disable
- name: Compile DM model
run: |
export PYTHONPATH="${{ github.workspace }}/tinygrad_repo:${{ github.workspace }}"
source ${UV_PROJECT_ENVIRONMENT}/bin/activate
export PYTHONPATH="${PYTHONPATH}:${{ github.workspace }}/tinygrad_repo:${{ github.workspace }}"
TG_FLAGS="DEV=MOCK+QCOM HCQ_RUNTIME_DEV=CPU:LLVM:arm64,cortex-a75,fp-armv8,sha2,lse,neon,crc,aes IMAGE=1 FLOAT16=1 NOLOCALS=1 JIT_BATCH_SIZE=0 OPENPILOT_HACKS=1"
TG_FLAGS="DEV=QCOM IMAGE=1 FLOAT16=1 NOLOCALS=1 JIT_BATCH_SIZE=0 OPENPILOT_HACKS=1"
env ${TG_FLAGS} python3 \
taskset -c 7 env ${TG_FLAGS} python3 \
${{ github.workspace }}/tinygrad_repo/examples/openpilot/compile_onnx.py \
${{ github.workspace }}/${{ env.DM_ONNX }} \
${{ github.workspace }}/${{ env.DM_PKL }} \
--out-of-band --benchmark-runs 0
--out-of-band --benchmark-runs 1
- name: Compile DM warp
run: |
export PYTHONPATH="${{ github.workspace }}/tinygrad_repo:${{ github.workspace }}"
source ${UV_PROJECT_ENVIRONMENT}/bin/activate
export PYTHONPATH="${PYTHONPATH}:${{ github.workspace }}/tinygrad_repo:${{ github.workspace }}"
TG_FLAGS="DEV=MOCK+QCOM HCQ_RUNTIME_DEV=CPU:LLVM:arm64,cortex-a75,fp-armv8,sha2,lse,neon,crc,aes IMAGE=1 FLOAT16=1 NOLOCALS=1 JIT_BATCH_SIZE=0 OPENPILOT_HACKS=1"
TG_FLAGS="DEV=QCOM IMAGE=1 FLOAT16=1 NOLOCALS=1 JIT_BATCH_SIZE=0 OPENPILOT_HACKS=1"
COMPILER="${{ github.workspace }}/tinygrad_repo/examples/openpilot"
MODELS_DIR="${{ github.workspace }}/openpilot/selfdrive/modeld/models"
DM_SIZE=$(python3 -c "from openpilot.common.transformations.model import DM_INPUT_SIZE as s; print(f'{s[0]}x{s[1]}')")
@@ -384,13 +465,12 @@ jobs:
print(f'{s},{y},{u},{sz}')
" $CAM_W $CAM_H)
WARP_PKL="${MODELS_DIR}/dm_warp_${res}_tinygrad.pkl"
env ${TG_FLAGS} python3 "${COMPILER}/compile_warp.py" \
taskset -c 7 env ${TG_FLAGS} python3 "${COMPILER}/compile_warp.py" \
--frame ${CAM_W},${CAM_H},${STRIDE_INFO} \
--warp-to ${DM_SIZE} \
--layout luma \
--border-fill 16 \
--transform-device NPY \
--benchmark-runs 0 \
--output "${WARP_PKL}"
done
@@ -405,3 +485,9 @@ jobs:
with:
name: dm-model-${{ github.run_number }}
path: dm_output/
- name: Re-enable powersave
if: always()
run: |
source ${UV_PROJECT_ENVIRONMENT}/bin/activate
PYTHONPATH=$PYTHONPATH:${{ github.workspace }}/ ${{ github.workspace }}/scripts/manage-powersave.py --enable
@@ -11,11 +11,6 @@ on:
description: 'Custom name for the model (no date, only name)'
required: false
type: string
from_sunnypilot:
description: 'The ref is on sunnypilot/sunnypilot (custom models): skip trying commaai/openpilot first'
required: false
type: boolean
default: false
recompiled_dir:
description: 'Existing recompiled directory number (e.g. 1 for recompiled1)'
required: true
@@ -39,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
@@ -67,11 +67,6 @@ on:
description: 'Custom name for the model (no date, only name)'
required: false
type: string
from_sunnypilot:
description: 'The ref is on sunnypilot/sunnypilot (custom models): skip trying commaai/openpilot first'
required: false
type: boolean
default: false
is_20hz:
description: 'Is this a 20Hz model'
required: false
@@ -95,7 +90,7 @@ on:
- Release Models
- 2026 World Models
- 2026 Deep RL Models
- Custom sunnypilot Models
- Custom Merge Models
- Other
custom_model_folder:
description: 'Custom model folder name (if "Other" selected)'
@@ -117,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
@@ -137,10 +137,10 @@ jobs:
with:
upstream_branch: ${{ inputs.upstream_branch }}
custom_name: ${{ inputs.custom_name || inputs.upstream_branch }}
from_sunnypilot: ${{ inputs.from_sunnypilot || false }}
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"
+35 -64
View File
@@ -3,87 +3,58 @@ name: Compile warp for sunnypilot modeld
on:
workflow_dispatch:
env:
WARP_DIR: openpilot/sunnypilot/modeld_v2/models
jobs:
compile_warps:
strategy:
matrix:
include:
- target: qcom
runs-on: ubuntu-24.04-arm
prefix: driving_warp
flags: DEV=MOCK+QCOM IMAGE=1 FLOAT16=1 NOLOCALS=1 JIT_BATCH_SIZE=0 OPENPILOT_HACKS=1
args: --split-frames
- target: chestnut
runs-on: ubuntu-24.04
prefix: big_driving_warp
flags: DEV=MOCKUSB+AMD:LLVM FRAME_DEV=CPU FLOAT16=1 JIT_BATCH_SIZE=0 GMMU=0 CHECK_OOB=0 TC_OPT=2 TC_MIN_GLOBALS=32
args: ''
runs-on: ${{ matrix.runs-on }}
runs-on: [self-hosted, chestnut]
steps:
- uses: actions/checkout@v4
with:
submodules: recursive
- uses: actions/setup-python@v5
with:
python-version: '3.12'
- name: Set environment variables
run: |
source /etc/profile
export UV_PROJECT_ENVIRONMENT=${HOME}/venv
export UV_PYTHON_PREFERENCE=managed
export UV_PYTHON_INSTALL_DIR=${HOME}/uv/python
export VIRTUAL_ENV=$UV_PROJECT_ENVIRONMENT
uv sync --frozen
printenv >> $GITHUB_ENV
- name: Set up the qcom mock
if: matrix.target == 'qcom'
uses: ./.github/workflows/setup-qcom-mock
with:
hf_token: ${{ secrets.HF_TOKEN }}
- name: Install LLVM 20 and ROCm comgr for the amd mock
if: matrix.target == 'chestnut'
uses: ./.github/workflows/setup-amd-mock
with:
emu_cache: warp
- name: Install the amd mock build dependencies
if: matrix.target == 'chestnut'
run: python3 -m pip install -q numpy zstandard
- name: Disable powersave
run: |
source ${UV_PROJECT_ENVIRONMENT}/bin/activate
PYTHONPATH=$PYTHONPATH:${{ github.workspace }}/ ${{ github.workspace }}/scripts/manage-powersave.py --disable
- name: Compile Warp Kernels
run: |
export PYTHONPATH="${{ github.workspace }}/tinygrad_repo:${{ github.workspace }}"
mkdir -p "$WARP_DIR"
source ${UV_PROJECT_ENVIRONMENT}/bin/activate
export PYTHONPATH="${PYTHONPATH}:${{ github.workspace }}/tinygrad_repo:${{ github.workspace }}"
mkdir -p openpilot/sunnypilot/modeld_v2/models/
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}')")
echo "Model size: $MODEL_SIZE"
echo "Camera resolutions: $CAMERA_RES"
for res in $CAMERA_RES; do
FRAME_PARAM=$(python3 -c "from openpilot.system.camerad.cameras.nv12_info import get_nv12_info; w, h = map(int, '${res}'.split('x')); stride, y_h, uv_h, _ = get_nv12_info(w, h); print(f'{w},{h},{stride},{y_h},{uv_h},{stride * (y_h + uv_h)}')")
WARP_PKL="$WARP_DIR/${{ matrix.prefix }}_${res}_tinygrad.pkl"
echo "Compiling $WARP_PKL"
env ${{ matrix.flags }} python3 openpilot/sunnypilot/modeld_v2/compile_warp.py \
--frame ${FRAME_PARAM} --warp-to ${MODEL_SIZE} ${{ matrix.args }} --output "${WARP_PKL}"
WARP_PKL="openpilot/sunnypilot/modeld_v2/models/driving_warp_${res}_tinygrad.pkl"
echo "Compiling $WARP_PKL on QCOM"
taskset -c 7 env DEV=QCOM IMAGE=1 FLOAT16=1 NOLOCALS=1 JIT_BATCH_SIZE=0 OPENPILOT_HACKS=1 python3 openpilot/sunnypilot/modeld_v2/compile_warp.py \
--frame ${FRAME_PARAM} --warp-to ${MODEL_SIZE} --split-frames --output "${WARP_PKL}"
BIG_WARP_PKL="openpilot/sunnypilot/modeld_v2/models/big_driving_warp_${res}_tinygrad.pkl"
echo "Compiling $BIG_WARP_PKL on AMD"
taskset -c 7 env DEV=USB+AMD:LLVM FRAME_DEV=CPU FLOAT16=1 JIT_BATCH_SIZE=0 GMMU=0 TC_OPT=2 TC_MIN_GLOBALS=32 python3 openpilot/sunnypilot/modeld_v2/compile_warp.py \
--frame ${FRAME_PARAM} --warp-to ${MODEL_SIZE} --output "${BIG_WARP_PKL}"
done
- name: Replay their check frames on the mock and require the result bit for bit
env:
DEV: ${{ matrix.target == 'chestnut' && 'MOCKUSB+AMD' || 'MOCK+QCOM' }}
PYTHONPATH: ${{ github.workspace }}/tinygrad_repo:${{ github.workspace }}
run: python3 -m openpilot.sunnypilot.modeld_v2.mock_parity check "$WARP_DIR"/${{ matrix.prefix }}_*_tinygrad.pkl
- uses: actions/upload-artifact@v4
with:
name: warps-${{ matrix.target }}
path: ${{ env.WARP_DIR }}/${{ matrix.prefix }}_*_tinygrad.pkl
if-no-files-found: error
create_pr:
needs: compile_warps
runs-on: ubuntu-24.04
steps:
- uses: actions/checkout@v4
- uses: actions/download-artifact@v4
with:
pattern: warps-*
path: ${{ env.WARP_DIR }}
merge-multiple: true
- name: Re-enable powersave
if: always()
run: |
source ${UV_PROJECT_ENVIRONMENT}/bin/activate
PYTHONPATH=$PYTHONPATH:${{ github.workspace }}/ ${{ github.workspace }}/scripts/manage-powersave.py --enable
- name: Create Pull Request
uses: peter-evans/create-pull-request@9153d834b60caba6d51c9b9510b087acf9f33f83
+1 -1
View File
@@ -30,7 +30,7 @@ jobs:
&& fromJSON('["namespace-profile-amd64-8x16"]')
|| fromJSON('["ubuntu-24.04"]') }}
steps:
#- uses: commaai/timeout@v1 # TODO: figure out how to re-enable this. uv download is super slow right now...
- uses: commaai/timeout@v1
- uses: actions/checkout@v7
- run: ./tools/op.sh setup
+118 -40
View File
@@ -1,10 +1,8 @@
name: Sync comma's LFS
# Mirrors the LFS objects of upstream's tip from comma's HF bucket into sunnypilot's,
# so lfs.py clients (devices, CI) find every object in one bucket.
env:
UPSTREAM_BUCKET: 'commaai/openpilot-lfs'
SUNNYPILOT_BUCKET: 'sunnypilot/sunnypilot-lfs'
LFS_URL: 'https://huggingface.co/sunnypilot/sunnypilot-lfs.git/info/lfs'
LFS_PUSH_URL: 'https://huggingface.co/sunnypilot/sunnypilot-lfs.git/info/lfs'
on:
schedule:
@@ -27,57 +25,137 @@ jobs:
# Skip if PR is in draft mode
if: (github.event_name != 'pull_request' || (github.event_name == 'pull_request' && github.event.pull_request.draft == false)) && !github.event.pull_request.head.repo.fork
steps:
- name: Checkout upstream
- name: Checkout Repository
uses: actions/checkout@v4
with:
repository: 'commaai/openpilot'
ref: ${{ inputs.upstream_branch }}
lfs: false
- name: Install hf-xet
- name: LFS Fetch
run: |
python3 -m venv "$RUNNER_TEMP/lfs-venv"
"$RUNNER_TEMP/lfs-venv/bin/pip" install -q hf-xet==1.7.0
echo "$RUNNER_TEMP/lfs-venv/bin" >> "$GITHUB_PATH"
git lfs fetch || echo "::warning::some objects are missing on commaai/openpilot-lfs; mirroring the rest"
- name: Fetch from comma's bucket
run: OPENPILOT_LFS_BUCKET="$UPSTREAM_BUCKET" ./lfs.py pull --exclude=''
- name: Set up Git
run: |
git config --global user.name 'GitHub Action'
git config --global user.email 'action@github.com'
- name: Upload to sunnypilot's bucket
- name: Setup hf
env:
HF_TOKEN: ${{ secrets.HF_TOKEN }}
run: |
OPENPILOT_LFS_BUCKET="$SUNNYPILOT_BUCKET" python3 -c "
import lfs
objects = list(lfs.pointers_for_index())
lfs.upload(objects)
print(f'{len(objects)} objects present in {lfs.BUCKET}')
"
git config --global credential.helper store
echo "https://user:${HF_TOKEN}@huggingface.co" > ~/.git-credentials
mirror-git-lfs:
# Clients still on git-lfs (devices on an older updater) fetch from the .lfsconfig model repo, which lfs.py never uploads to
runs-on: ubuntu-latest
if: github.event_name != 'pull_request'
steps:
- uses: actions/checkout@v4
- name: Ensure branch
run: |
if git symbolic-ref -q HEAD >/dev/null; then
echo "Already on a branch, proceeding with push"
else
echo "Detached HEAD state detected, creating temporary branch"
git checkout -b temp_branch
fi
- name: Update LFS Config
run: |
echo '[lfs]' > .lfsconfig
echo ' url = ${{ env.LFS_URL }}' >> .lfsconfig
echo ' pushurl = ${{ env.LFS_PUSH_URL }}' >> .lfsconfig
echo ' locksverify = false' >> .lfsconfig
- name: Configure LFS transfer settings
run: |
git config lfs.activitytimeout 300
git config lfs.transfer.maxretries 5
git config lfs.concurrenttransfers 4
git config lfs.allowincompletepush true
- name: Push LFS
id: sync-and-commit
run: |
git lfs ls-files -l
for attempt in 1 2 3; do
echo "Push attempt $attempt..."
git lfs push --all origin && exit 0
echo "Attempt $attempt failed, retrying in 30s..."
sleep 30
done
echo "All push attempts failed"
exit 1
- name: Checkout sunnypilot
uses: actions/checkout@v4
with:
repository: 'sunnypilot/sunnypilot'
path: sunnypilot
fetch-depth: 0
filter: blob:limit=1k
lfs: false
- name: Fetch what the model repo lacks from sunnypilot's bucket
run: |
python3 -c "
import lfs
objects = dict(lfs.pointers_for_index().keys())
missing = sorted(objects.keys() - lfs.endpoint_objects(objects).keys())
lfs.parallel(lfs.download_one, [(oid, objects[oid]) for oid in missing])
for oid in missing:
print(oid)
" > missing.txt
echo "$(wc -l < missing.txt) objects missing from the model repo"
- name: Upload to the model repo
- name: Reference objects on sunnypilot-lfs
env:
HF_TOKEN: ${{ secrets.HF_TOKEN }}
run: |
git config --global credential.https://huggingface.co.helper '!f() { echo username=hf; echo "password=$HF_TOKEN"; }; f'
xargs -r git lfs push --object-id origin < missing.txt
set -euo pipefail
GIT_LFS_SKIP_SMUDGE=1 git clone --quiet https://huggingface.co/sunnypilot/sunnypilot-lfs hf-lfs
mkdir -p hf-lfs/all
cat > scan_pointers.py <<'EOF'
import re, subprocess, sys, threading
repo = sys.argv[1]
chk = subprocess.run(["git", "-C", repo, "cat-file", "--batch-all-objects",
"--batch-check=%(objectname) %(objecttype) %(objectsize)"],
capture_output=True, text=True, check=True).stdout
small = [f[0] for f in (l.split() for l in chk.splitlines()) if f[1] == "blob" and int(f[2]) < 1024]
p = subprocess.Popen(["git", "-C", repo, "cat-file", "--batch=%(objectsize)"],
stdin=subprocess.PIPE, stdout=subprocess.PIPE)
def feed():
for sha in small:
p.stdin.write(sha.encode() + b"\n")
p.stdin.close()
threading.Thread(target=feed, daemon=True).start()
rx = re.compile(rb"^version https://git-lfs\.github\.com/spec/v1\noid sha256:([0-9a-f]{64})\nsize ([0-9]+)\n")
seen = {}
for _ in small:
n = int(p.stdout.readline()); body = p.stdout.read(n); p.stdout.read(1)
m = rx.match(body)
if m:
seen.setdefault(m.group(1).decode(), m.group(2).decode())
for oid, size in sorted(seen.items()):
print(oid, size)
EOF
for repo in . sunnypilot; do
python3 scan_pointers.py "$repo"
done | sort -u | while read -r oid size; do
[ -e "hf-lfs/all/$oid" ] && continue
printf 'version https://git-lfs.github.com/spec/v1\noid sha256:%s\nsize %s\n' "$oid" "$size" > "hf-lfs/all/$oid"
echo "$oid"
done > new_oids.txt
echo "new pointer files: $(wc -l < new_oids.txt)"
dropped=0
while mapfile -t -n 100 chunk && ((${#chunk[@]})); do
body=$(for oid in "${chunk[@]}"; do
size=$(awk '/^size /{print $2}' "hf-lfs/all/$oid")
printf '{"oid":"%s","size":%s}\n' "$oid" "$size"
done | jq -s '{operation:"download",transfers:["basic"],objects:.}')
for attempt in 1 2 3 4 5; do
resp=$(curl -sS -u "user:${HF_TOKEN}" -w '\n%{http_code}' \
-H 'Accept: application/vnd.git-lfs+json' -H 'Content-Type: application/vnd.git-lfs+json' \
--data "$body" "${LFS_URL}/objects/batch") && [ "$(tail -n1 <<<"$resp")" = 200 ] && break
echo "batch check attempt $attempt failed ($(tail -n1 <<<"$resp")), retrying in 60s"; sleep 60
done
[ "$(tail -n1 <<<"$resp")" = 200 ] || { echo "batch check failed"; exit 1; }
for oid in $(sed '$d' <<<"$resp" | jq -r '.objects[] | select(.error) | .oid'); do
rm -f "hf-lfs/all/$oid"; dropped=$((dropped+1))
done
done < new_oids.txt
echo "dropped (not on HF): $dropped"
cd hf-lfs
git add -A all
if git diff --cached --quiet; then
echo "nothing new to reference"
exit 0
fi
git commit -q -m "Reference $(git diff --cached --name-only | wc -l | tr -d ' ') new LFS objects"
git push origin HEAD:main
+1 -1
View File
@@ -36,5 +36,5 @@ jobs:
run: BRANCH=__nightly tools/release/build_stripped.sh
- name: Push chestnut nightly
run: |
./lfs.py pull --exclude=''
git lfs pull --exclude=''
INCLUDE_BIG_MODEL=1 BRANCH=__nightly-chestnut tools/release/build_stripped.sh
@@ -1,62 +0,0 @@
name: Set up tinygrad's qcom mock
description: The a630 compiler, checked against what an a630 compiled, and the kernels earlier builds compiled
inputs:
hf_token:
description: Records a passed compiler check on HF so the next build skips it
default: ''
runs:
using: composite
steps:
- name: Install the qcom mock build dependencies
id: deps
shell: bash
run: |
python3 -m pip install -q numpy zstandard tinymesa==25.2.7.2
if [ "$RUNNER_ARCH" = ARM64 ]; then # the qcomcl rootfs's compiler loads in this python, no qemu
sudo apt-get -qq update && sudo apt-get -qq install -y --no-install-recommends aria2
FS=$(PYTHONPATH="$GITHUB_WORKSPACE/tinygrad_repo" python3 -c "from tinygrad.helpers import fetch; print(fetch('https://git.tinygrad.win/tinygrad/images/releases/download/v2/qcomcl.tar.gz', extract=True))")
echo "LLVM_QCOM_PATH=$FS/usr/lib/libllvm-qcom.so" >> "$GITHUB_ENV"
echo "compiler=native-$(sha256sum "$FS/usr/lib/libllvm-qcom.so" | cut -c1-16)" >> "$GITHUB_OUTPUT"
else
sudo apt-get -qq update && sudo apt-get -qq install -y --no-install-recommends qemu-user-static aria2
echo "compiler=qemu-$(dpkg-query -W -f='${Version}' qemu-user-static)" >> "$GITHUB_OUTPUT"
fi
- name: Compiler check passed before with all of it identical?
id: compiler
shell: bash
env:
KEY: qcom-compiler-parity-${{ steps.deps.outputs.compiler }}-${{ 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') }}
run: |
MARKER="ci/qcom-compiler-parity/$(printf '%s' "$KEY" | tr -c 'A-Za-z0-9._-' '_').txt"
CODE=$(curl -s -o /dev/null -w '%{http_code}' -I -L "https://huggingface.co/datasets/sunnypilot/sunnypilot_models_v1/resolve/main/$MARKER")
echo "$MARKER: HTTP $CODE"
{ echo "key=$KEY"; echo "marker=$MARKER"; echo "passed=$([ "$CODE" = 200 ] && echo true || echo false)"; } >> "$GITHUB_OUTPUT"
- name: Check the off-device qcom compiler builds the a630's bytes
if: steps.compiler.outputs.passed != 'true'
shell: bash
run: |
# every kernel an a630 has compiled must compile to the same bytes here before a model is built here
TG="$GITHUB_WORKSPACE/tinygrad_repo"
PYTHONPATH="$TG" python3 "$TG/test/device/qcom/compiler_parity.py" check "$TG/test/mockgpu/qcom/a630_compiled.pkl.xz"
- name: Remember the compiler check passed
if: steps.compiler.outputs.passed != 'true' && inputs.hf_token != ''
shell: bash
env:
HF_TOKEN: ${{ inputs.hf_token }}
KEY: ${{ steps.compiler.outputs.key }}
MARKER: ${{ steps.compiler.outputs.marker }}
run: |
python3 -m pip install -q --upgrade "huggingface_hub>=0.34"
printf '%s\n%s\n' "$KEY" "$GITHUB_SERVER_URL/$GITHUB_REPOSITORY/actions/runs/$GITHUB_RUN_ID" > "$RUNNER_TEMP/marker.txt"
hf upload --repo-type dataset sunnypilot/sunnypilot_models_v1 "$RUNNER_TEMP/marker.txt" "$MARKER" \
--commit-message "qcom compiler parity passed: $KEY" || echo "::warning::could not record the pass, the next build checks again"
- name: Kernels compiled by earlier builds
uses: actions/cache@v4
with:
path: ~/.cache/tinygrad/cache.db
key: qcom-kernels-${{ steps.compiler.outputs.key }}-${{ github.run_id }}
restore-keys: qcom-kernels-${{ steps.compiler.outputs.key }}-
+108 -37
View File
@@ -1,7 +1,9 @@
name: Build Model from Upstream
env:
BUILD_DIR: "/data/openpilot"
OUTPUT_DIR: ${{ github.workspace }}/output
SCONS_CACHE_DIR: ${{ github.workspace }}/release/ci/scons_cache
UPSTREAM_REPO: "commaai/openpilot"
TINYGRAD_PATH: ${{ github.workspace }}/tinygrad_repo
MODELS_DIR: ${{ github.workspace }}/openpilot/selfdrive/modeld/models
@@ -18,11 +20,6 @@ on:
description: 'Custom name for the model (no date, only name)'
required: false
type: string
from_sunnypilot:
description: 'The ref is on sunnypilot/sunnypilot (custom models): skip trying commaai/openpilot first'
required: false
type: boolean
default: false
is_20hz:
description: 'Is this a 20Hz model'
required: false
@@ -38,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:
@@ -49,11 +51,6 @@ on:
description: 'Custom name for the model (no date, only name)'
required: false
type: string
from_sunnypilot:
description: 'The ref is on sunnypilot/sunnypilot (custom models): skip trying commaai/openpilot first'
required: false
type: boolean
default: false
is_20hz:
description: 'Is this a 20Hz model'
required: false
@@ -67,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 }}]
@@ -82,7 +84,6 @@ jobs:
# Note: To allow dynamic models from both openpilot and sunnypilot (merges/mashups), we try commaai as default,
# and fallback to sunnypilot if the ref checkout fails.
- name: Checkout commaai/openpilot
if: ${{ !inputs.from_sunnypilot }}
id: checkout_upstream
continue-on-error: true
uses: actions/checkout@v4
@@ -94,7 +95,7 @@ jobs:
path: openpilot
- name: Fallback to sunnypilot/sunnypilot
if: inputs.from_sunnypilot || steps.checkout_upstream.outcome == 'failure'
if: steps.checkout_upstream.outcome == 'failure'
uses: actions/checkout@v4
with:
repository: sunnypilot/sunnypilot
@@ -119,13 +120,9 @@ jobs:
for f in "$@"; do
grep -qs "^version https://git-lfs" "$f" || continue
OID=$(awk -F'sha256:' '/^oid/{print $2}' "$f"); SIZE=$(awk '/^size/{print $2}' "$f")
HREF=""
for B in sunnypilot/sunnypilot-lfs commaai/openpilot-lfs; do # lfs.py's buckets (commaai/openpilot#39206)
if curl -fsSL --retry 3 -r 0-0 -o /dev/null "https://huggingface.co/buckets/$B/resolve/sha256/$OID"; then HREF="https://huggingface.co/buckets/$B/resolve/sha256/$OID"; break; fi
done
[ -n "$HREF" ] || 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" \
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 // empty')
if [ -z "$HREF" ]; then # not in openpilot's LFS: comma also publishes models to openpilot_driving_models
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"
@@ -137,9 +134,7 @@ jobs:
}
UPSTREAM_PKL=selfdrive/modeld/models/big_driving_tinygrad.pkl
if [ "${{ inputs.target_hardware }}" != "chestnut" ]; then
LFS_EXCLUDE="**/selfdrive/modeld/models/big_*.onnx,**/selfdrive/modeld/models/dmonitoring_*.onnx,**/selfdrive/modeld/models/big_*.pkl,**/selfdrive/modeld/models/dmonitoring_*.pkl"
TOP=$(git rev-parse --show-toplevel)
if [ -f "$TOP/lfs.py" ]; then (cd "$TOP" && ./lfs.py pull --exclude="$LFS_EXCLUDE"); else git lfs pull -X "$LFS_EXCLUDE"; fi || true
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
@@ -174,36 +169,92 @@ jobs:
if-no-files-found: error
build_model:
runs-on: ${{ inputs.target_hardware == 'chestnut' && 'ubuntu-24.04' || 'ubuntu-24.04-arm' }}
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
- uses: actions/setup-python@v5
- 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: inputs.target_hardware == 'chestnut'
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: inputs.target_hardware == 'chestnut'
run: python3 -m pip install -q numpy zstandard
if: env.MOCK_BUILD == 'true' && inputs.target_hardware == 'chestnut'
run: |
python3 -m pip install -q numpy zstandard
- name: Set up the qcom mock
if: inputs.target_hardware != 'chestnut'
uses: ./.github/workflows/setup-qcom-mock
- 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:
hf_token: ${{ secrets.HF_TOKEN }}
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
source /etc/profile;
export UV_PROJECT_ENVIRONMENT=${HOME}/venv
export UV_PYTHON_PREFERENCE=managed
export UV_PYTHON_INSTALL_DIR=${HOME}/uv/python
export VIRTUAL_ENV=$UV_PROJECT_ENVIRONMENT
uv sync --frozen
printenv >> $GITHUB_ENV
- name: Setup build environment
if: env.MOCK_BUILD != 'true'
run: |
mkdir -p "${BUILD_DIR}/"
sudo find $BUILD_DIR/ -mindepth 1 -delete
echo "Starting build stage..."
echo "BUILD_DIR: ${BUILD_DIR}"
echo "CI_DIR: ${CI_DIR}"
echo "VERSION: ${{ steps.set-env.outputs.version }}"
echo "UV_PROJECT_ENVIRONMENT: ${UV_PROJECT_ENVIRONMENT}"
echo "VIRTUAL_ENV: ${VIRTUAL_ENV}"
source ${UV_PROJECT_ENVIRONMENT}/bin/activate
PYTHONPATH=$PYTHONPATH:${{ github.workspace }}/ ${{ github.workspace }}/scripts/manage-powersave.py --disable
rm -rf ${{ env.MODELS_DIR }}/*.onnx*
- name: Download model artifacts
uses: actions/download-artifact@v4
@@ -213,18 +264,28 @@ jobs:
- name: Build Model
run: |
export CHECK_OOB=0 GMMU=0 # as test/mockgpu runs the amd mock
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=MOCK+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=MOCKUSB+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"
@@ -239,15 +300,17 @@ 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 PYTHONPATH="$TINYGRAD_PATH" python3 "$TINYGRAD_PATH/test/mockgpu/usb_server.py" env DEV=USB+AMD PYTHONPATH="$UPSTREAM_TG:${{ github.workspace }}" 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} python3 openpilot/sunnypilot/modeld_v2/compile_modeld_v2.py \
"$NEW_ARCH_ONNX" "$OUTPUT_PKL" --device-input "*" --benchmark-runs 0
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."
# Detect model type and build compile args
@@ -296,7 +359,7 @@ jobs:
if [ -n "$MODEL_TYPE" ]; then
echo "Detected: $MODEL_TYPE -> $OUTPUT_PKL"
env ${TG_FLAGS} python3 "$COMPILE_MODELD" \
env ${TG_FLAGS} $TASKSET python3 "$COMPILE_MODELD" \
--model-type $MODEL_TYPE \
--model-size $MODEL_SIZE \
--camera-resolutions $CAMERA_RES \
@@ -306,6 +369,7 @@ jobs:
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 }}
@@ -322,6 +386,7 @@ jobs:
--include='/${{ inputs.target_hardware == 'chestnut' && 'big_' || '' }}driving_tinygrad.pkl' \
--exclude='*' \
--delete-excluded \
$([ "$MOCK_BUILD" = "true" ] || echo --chown=comma:comma) \
${{ env.MODELS_DIR }}/ ${{ env.OUTPUT_DIR }}/
python3 "${{ github.workspace }}/release/ci/model_generator.py" \
@@ -348,3 +413,9 @@ jobs:
with:
name: artifact-name-${{ inputs.custom_name || inputs.upstream_branch }}
path: ${{ env.OUTPUT_DIR }}/artifact_name.txt
- name: Re-enable powersave
if: always() && env.MOCK_BUILD != 'true'
run: |
source ${UV_PROJECT_ENVIRONMENT}/bin/activate
PYTHONPATH=$PYTHONPATH:${{ github.workspace }}/ ${{ github.workspace }}/scripts/manage-powersave.py --enable
@@ -112,7 +112,7 @@ jobs:
concurrency:
group: build-${{ github.head_ref || github.ref_name }}
cancel-in-progress: false
runs-on: ubuntu-24.04-arm
runs-on: [self-hosted, tici]
if: ${{
(always() && !cancelled() && !failure()) &&
needs.prepare_strategy.result == 'success' &&
@@ -127,61 +127,57 @@ jobs:
submodules: recursive
ref: ${{ env.SOURCE_BRANCH }}
repository: ${{ github.event.pull_request.head.repo.fork && github.event.pull_request.head.repo.full_name || github.repository }}
- run: ./lfs.py pull --exclude=''
- run: git lfs pull
- name: Import the AGNOS system image this commit pins
- name: Set environment variables
run: |
read -r URL HASH HASH_RAW < <(python3 -c "import json; p = next(p for p in json.load(open('openpilot/common/hardware/comma/agnos.json')) if p['name'] == 'system'); print(p['url'], p['hash'], p['hash_raw'])")
curl -fsSL --retry 3 "$URL" | xz -dc -T0 > "$RUNNER_TEMP/system.sparse.img"
echo "$HASH $RUNNER_TEMP/system.sparse.img" | sha256sum -c
sudo apt-get -qq update && sudo apt-get -qq install -y --no-install-recommends android-sdk-libsparse-utils
simg2img "$RUNNER_TEMP/system.sparse.img" "$RUNNER_TEMP/system.img" && rm "$RUNNER_TEMP/system.sparse.img"
echo "$HASH_RAW $RUNNER_TEMP/system.img" | sha256sum -c
sudo mkdir -p /mnt/agnos && sudo mount -o loop,ro "$RUNNER_TEMP/system.img" /mnt/agnos
sudo tar -C /mnt/agnos --exclude=./etc/resolv.conf -c . | docker import - agnos # a symlink into /run: docker writes its own
sudo umount /mnt/agnos && rm "$RUNNER_TEMP/system.img"
- name: Build Main Project in AGNOS
run: |
cat > "$RUNNER_TEMP/build.sh" <<'EOF'
set -e
source /etc/profile
set -x
# Set up common environment
source /etc/profile;
export UV_PROJECT_ENVIRONMENT=${HOME}/venv
export UV_PYTHON_PREFERENCE=managed
export UV_PYTHON_INSTALL_DIR=${HOME}/uv/python
export VIRTUAL_ENV=$UV_PROJECT_ENVIRONMENT
mkdir -p "$HOME"
git config --global --add safe.directory '*'
cat /VERSION
clang --version | head -1
cd /src
uv sync
printenv >> $GITHUB_ENV
- name: Setup build environment
run: |
mkdir -p "${BUILD_DIR}/"
sudo find $BUILD_DIR/ -mindepth 1 -delete
echo "Starting build stage..."
echo "BUILD_DIR: ${BUILD_DIR}"
echo "CI_DIR: ${CI_DIR}"
echo "VERSION: ${{ needs.prepare_strategy.outputs.version }}"
echo "UV_PROJECT_ENVIRONMENT: ${UV_PROJECT_ENVIRONMENT}"
echo "VIRTUAL_ENV: ${VIRTUAL_ENV}"
echo "-------"
if [[ "${{ runner.debug }}" == "1" ]]; then
printenv
fi
source ${UV_PROJECT_ENVIRONMENT}/bin/activate
PYTHONPATH=$PYTHONPATH:${{ github.workspace }}/ ${{ github.workspace }}/scripts/manage-powersave.py --disable
- name: Build Main Project
run: |
export PYTHONPATH="$BUILD_DIR:$BUILD_DIR/msgq_repo:$BUILD_DIR/opendbc_repo:$BUILD_DIR/rednose_repo:$BUILD_DIR/teleoprtc_repo:$BUILD_DIR/tinygrad_repo"
./tools/release/release_files.py | xargs -0 cp -pR --parents -t "$BUILD_DIR" --
pip install -q tinymesa==25.2.7.2
# scons passes the warp commands only PATH, TMPDIR and PYTHONPATH, so the mock goes into the command itself
sed -i "s/'DEV=QCOM /'DEV=MOCK+QCOM HCQ_RUNTIME_DEV=CPU:LLVM:arm64,cortex-a75,fp-armv8,sha2,lse,neon,crc,aes /" "$BUILD_DIR/openpilot/selfdrive/modeld/SConscript"
grep -q "'DEV=MOCK+QCOM " "$BUILD_DIR/openpilot/selfdrive/modeld/SConscript"
# msgq builds the ION vision buffers only when /dev/ion exists; the device has one, the runner does not
touch /dev/ion
SCONS_CACHE=/data/scons_cache
# outside the checkout, which is wiped each run. /data/scons_cache is the device's, not ours.
SCONS_CACHE="$RUNNER_WORKSPACE/scons_cache"
mkdir -p "$SCONS_CACHE"
cd $BUILD_DIR
rm -rf /tmp/* || true
echo "Building locationd..."
# -j1: parallel rednose generators OOM the device
scons -j1 cache_dir="$SCONS_CACHE" --minimal \
openpilot/selfdrive/locationd
echo "Building rest of sunnypilot"
sudo rm -rf /tmp/* || true
mkdir -p "$BUILD_DIR/tmp"
export TMPDIR="$BUILD_DIR/tmp"
SKIP_TINYGRAD_COMPILE=1 scons -j$(nproc) cache_dir="$SCONS_CACHE" --minimal
SKIP_TINYGRAD_COMPILE=1 /usr/bin/time -v scons -j$(nproc) cache_dir="$SCONS_CACHE" --minimal
touch ${BUILD_DIR}/prebuilt
EOF
sudo mkdir -p "$BUILD_DIR" && sudo chown -R "$(id -u):$(id -g)" /data
# AGNOS mounts these at boot (usr/comma/boot.sh); its uv and pip shims remount / read-only and resize /tmp
# /root: scons drops HOME, so tinygrad's compile cache lands in root's home
docker run --rm --privileged -e CI=true -e HOME=/data/media/0/github -e BUILD_DIR \
--tmpfs /tmp:rw,exec,nosuid,nodev,size=150m,nr_inodes=1m,mode=1777 --tmpfs /var:rw,exec,nosuid,nodev,size=128m,mode=755 \
--tmpfs /home:rw,exec,nosuid,nodev,size=100m,mode=755 --tmpfs /root:rw,exec,nosuid,nodev,size=1g,mode=700 \
-v "$GITHUB_WORKSPACE:/src" -v /data:/data -v "$RUNNER_TEMP/build.sh:/build.sh:ro" agnos bash /build.sh
sudo chown -R "$(id -u):$(id -g)" "$BUILD_DIR"
if [[ "${{ runner.debug }}" == "1" ]]; then
ls -la ${BUILD_DIR}
fi
- name: Strip release tree
run: |
@@ -194,7 +190,7 @@ jobs:
find . -name '__pycache__' -type d -exec rm -rf {} +
find . -name 'SConstruct' -delete
find . -name 'SConscript' -delete
rm -rf .sconsign.dblite tools/release/ release/
rm -rf .sconsign.dblite Jenkinsfile tools/release/ release/
rm -f openpilot/selfdrive/modeld/models/*.onnx*
rm -f openpilot/sunnypilot/modeld*/models/*.onnx*
find openpilot/third_party/ -name '*x86*' -exec rm -r {} +
@@ -213,6 +209,12 @@ jobs:
path: prebuilt.tar.gz
compression-level: 0
- name: Re-enable powersave
if: always()
run: |
source ${UV_PROJECT_ENVIRONMENT}/bin/activate
PYTHONPATH=$PYTHONPATH:${{ github.workspace }}/ ${{ github.workspace }}/scripts/manage-powersave.py --enable
prepare_chestnut:
needs: [ prepare_strategy ]
runs-on: ubuntu-24.04
@@ -597,8 +599,7 @@ jobs:
CHESTNUT_BRANCH="${{ needs.prepare_strategy.outputs.new_branch }}-chestnut"
cp .lfsconfig "${{ env.OUTPUT_DIR }}/"
echo 'openpilot/selfdrive/modeld/models/big_*_tinygrad.pkl filter=lfs diff=lfs merge=lfs -text' > "${{ env.OUTPUT_DIR }}/.gitattributes"
python3 -m venv "$RUNNER_TEMP/lfs-venv" && "$RUNNER_TEMP/lfs-venv/bin/pip" install -q hf-xet==1.7.0
export PATH="$RUNNER_TEMP/lfs-venv/bin:$PATH" # publish.sh runs lfs.py install; its pre-push uploads to the HF bucket
git lfs install
git config --global credential.helper store
echo "https://user:${HF_TOKEN}@huggingface.co" > ~/.git-credentials
@@ -3,6 +3,8 @@ name: Build dev
env:
DEFAULT_SOURCE_BRANCH: "master"
DEFAULT_TARGET_BRANCH: "master-dev"
LFS_URL: 'https://gitlab.com/sunnypilot/public/sunnypilot-new-lfs.git/info/lfs'
LFS_PUSH_URL: 'ssh://git@gitlab.com/sunnypilot/public/sunnypilot-new-lfs.git'
on:
push:
@@ -64,6 +66,15 @@ jobs:
git config --global user.name 'github-actions[bot]'
git config --global user.email 'github-actions[bot]@users.noreply.github.com'
- name: Set up SSH
uses: webfactory/ssh-agent@v0.9.0
with:
ssh-private-key: ${{ secrets.SSH_PRIVATE_KEY }}
- name: Add GitLab public keys
run: |
ssh-keyscan -H gitlab.com >> ~/.ssh/known_hosts
- name: Set up Python
uses: actions/setup-python@v5
with:
@@ -156,6 +167,13 @@ jobs:
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
- name: Update LFS Config
run: |
echo '[lfs]' > .lfsconfig
echo ' url = ${{ env.LFS_URL }}' >> .lfsconfig
echo ' pushurl = ${{ env.LFS_PUSH_URL }}' >> .lfsconfig
echo ' locksverify = false' >> .lfsconfig
- name: Restore workflows from source
run: |
TARGET_BRANCH="${{ inputs.target_branch || env.DEFAULT_TARGET_BRANCH }}"
-26
View File
@@ -1,26 +0,0 @@
name: Test big warps with stock modeld
on:
pull_request:
paths:
- 'openpilot/selfdrive/modeld/**'
- 'tinygrad_repo'
- 'openpilot/system/camerad/cameras/nv12_info.py'
- '.github/workflows/big-warp/**'
- '.github/workflows/test-big-warp.yaml'
workflow_dispatch:
jobs:
big-warp:
runs-on: ubuntu-24.04
timeout-minutes: 30
steps:
- uses: actions/checkout@v4
with:
submodules: recursive
- name: Pull big PKL via LFS
run: ./lfs.py pull --exclude=''
- uses: ./.github/workflows/setup-amd-mock
with:
emu_cache: big-warp
- uses: ./.github/workflows/big-warp
+52 -1
View File
@@ -68,6 +68,7 @@ jobs:
generate-matrix:
runs-on: ubuntu-latest
outputs:
models: ${{ steps.set-matrix.outputs.models }}
chestnut: ${{ steps.set-matrix.outputs.chestnut }}
qcom: ${{ steps.set-matrix.outputs.qcom }}
steps:
@@ -81,22 +82,59 @@ jobs:
with open("openpilot/sunnypilot/models/fetcher.py", "r") as f:
urls = re.findall(r"MODEL_URL(?:_CHESTNUT)?\s*=\s*[\"'"'"']([^\"'"'"']+)[\"'"'"']", f.read())
chestnut, qcom = [], []
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:
name: Test ${{ matrix.artifact.file_name }}
needs: generate-matrix
runs-on: ubuntu-latest
container: ghcr.io/commaai/openpilot-base:latest
strategy:
fail-fast: false
matrix:
artifact: ${{ fromJson(needs.generate-matrix.outputs.models) }}
steps:
- uses: actions/checkout@v4
with:
submodules: true
- name: Download model
env:
HF_TOKEN: ${{ secrets.HF_TOKEN }}
MODEL_URL: ${{ matrix.artifact.download_uri.url }}
MODEL_FILE: ${{ matrix.artifact.file_name }}
shell: bash
run: |
mkdir -p /tmp/models
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 "/tmp/models/$MODEL_FILE" "$MODEL_URL"
- name: Run Model Compatibility Test
env:
MODEL_BASE_NAME: ${{ matrix.artifact.file_name }}
MODEL_DIR: "/tmp/models"
run: |
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
@@ -161,3 +199,16 @@ jobs:
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
+4 -3
View File
@@ -45,7 +45,7 @@ jobs:
with:
timeout_minutes: 2
max_attempts: 3
command: ./lfs.py pull
command: git lfs pull
- name: Build devel
timeout-minutes: 3
run: TARGET_DIR=$STRIPPED_DIR tools/release/build_stripped.sh
@@ -102,7 +102,7 @@ jobs:
key: scons-${{ runner.os }}-${{ github.job }}-${{ github.sha }}
restore-keys: scons-${{ runner.os }}-${{ github.job }}-
- name: Building openpilot
run: tools/op.sh build
run: scons
static_analysis:
name: static analysis
@@ -140,7 +140,7 @@ jobs:
key: scons-${{ runner.os }}-${{ github.job }}-${{ github.sha }}
restore-keys: scons-${{ runner.os }}-${{ github.job }}-
- name: Build openpilot
run: tools/op.sh build
run: scons
- name: Run unit tests
timeout-minutes: ${{ contains(runner.name, 'nsc') && 2 || 999 }}
env:
@@ -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') ||
+1
View File
@@ -62,6 +62,7 @@ docs/_site/
openpilot/selfdrive/pandad/pandad
openpilot/cereal/services.h
openpilot/cereal/gen
openpilot/cereal/messaging/bridge
openpilot/selfdrive/ui/translations/tmp
openpilot/selfdrive/car/tests/cars_dump
openpilot/system/camerad/camerad
+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>
+4
View File
@@ -0,0 +1,4 @@
[lfs]
url = https://gitlab.com/commaai/openpilot-lfs.git/info/lfs
pushurl = ssh://git@gitlab.com/commaai/openpilot-lfs.git
locksverify = false
+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>
Vendored
+320
View File
@@ -0,0 +1,320 @@
def retryWithDelay(int maxRetries, int delay, Closure body) {
for (int i = 0; i < maxRetries; i++) {
try {
return body()
} catch (Exception e) {
sleep(delay)
}
}
throw Exception("Failed after ${maxRetries} retries")
}
def device(String ip, String step_label, String cmd) {
withCredentials([file(credentialsId: 'id_rsa', variable: 'key_file')]) {
def ssh_cmd = """
ssh -o ControlMaster=no -o ControlPath=none -o ConnectTimeout=5 -o ServerAliveInterval=5 -o ServerAliveCountMax=12 -o BatchMode=yes -o StrictHostKeyChecking=no -i ${key_file} 'comma@${ip}' exec setpriv --pdeathsig HUP /usr/bin/bash <<'END'
set -e
export TERM=xterm-256color
trap 'kill 0' HUP # stop this process group on SSH disconnect
export CI=1
export PYTHONWARNINGS=error
export PYTHONFAULTHANDLER=1
export COMMA_CACHE=/data/tmp/comma_download_cache
#export LOGPRINT=debug # this has gotten too spammy...
export TEST_DIR=${env.TEST_DIR}
export SOURCE_DIR=${env.SOURCE_DIR}
export GIT_BRANCH=${env.GIT_BRANCH}
export GIT_COMMIT=${env.GIT_COMMIT}
export CI_ARTIFACTS_TOKEN=${env.CI_ARTIFACTS_TOKEN}
export GITHUB_COMMENTS_TOKEN=${env.GITHUB_COMMENTS_TOKEN}
export AZURE_TOKEN='${env.AZURE_TOKEN}'
# only use 1 thread since most require real hardware that can't be shared
export PYTEST_ADDOPTS="-n0 -s"
export GIT_SSH_COMMAND="ssh -i /data/gitkey"
source ~/.bash_profile
if [ -f /AGNOS ]; then
source /etc/profile
rm -rf /tmp/tmp*
rm -rf ~/.commacache
rm -rf /dev/shm/*
rm -rf /dev/tmp/tmp*
if ! systemctl is-active --quiet systemd-resolved; then
echo "restarting resolved"
sudo systemctl start systemd-resolved
sleep 3
fi
# restart aux USB
if [ -e /sys/bus/usb/drivers/hub/3-0:1.0 ]; then
echo "restarting aux usb"
echo "3-0:1.0" | sudo tee /sys/bus/usb/drivers/hub/unbind
sleep 0.5
echo "3-0:1.0" | sudo tee /sys/bus/usb/drivers/hub/bind
fi
fi
if [ -f /data/openpilot/launch_env.sh ]; then
source /data/openpilot/launch_env.sh
fi
export LD_LIBRARY_PATH="\$(python -c 'import ffmpeg; print(ffmpeg.LIB_DIR)'):/usr/local/lib:\${LD_LIBRARY_PATH:-}"
ln -snf ${env.TEST_DIR} /data/pythonpath
cd ${env.TEST_DIR} || true
time ( ${cmd} ) &
wait \$!
END"""
sh script: ssh_cmd, label: step_label
}
}
def deviceStage(String stageName, String deviceType, List extra_env, def steps) {
stage(stageName) {
if (currentBuild.result != null) {
return
}
if (isReplay()) {
error("REPLAYING TESTS IS NOT ALLOWED. FIX THEM INSTEAD.")
}
def extra = extra_env.collect { "export ${it}" }.join('\n');
def branch = env.BRANCH_NAME ?: 'master';
def gitDiff = sh returnStdout: true, script: 'curl -s -H "Authorization: Bearer ${GITHUB_COMMENTS_TOKEN}" https://api.github.com/repos/commaai/openpilot/compare/master...${GIT_BRANCH} | jq .files[].filename || echo "/"', label: 'Getting changes'
lock(resource: "", label: deviceType, inversePrecedence: true, variable: 'device_ip', quantity: 1, resourceSelectStrategy: 'random') {
docker.image('ghcr.io/commaai/alpine-ssh').inside('--user=root') {
timeout(time: 35, unit: 'MINUTES') {
retry (3) {
def date = sh(script: 'date', returnStdout: true).trim();
device(device_ip, "set time", "date -s '" + date + "'")
device(device_ip, "git checkout", extra + "\n" + readFile("openpilot/selfdrive/test/setup_device_ci.sh"))
}
steps.each { item ->
def name = item[0]
def cmd = item[1]
def args = item[2]
def diffPaths = args.diffPaths ?: []
def cmdTimeout = args.timeout ?: 9999
if (branch != "master" && !branch.contains("__jenkins_loop_") && diffPaths && !hasPathChanged(gitDiff, diffPaths)) {
println "Skipping ${name}: no changes in ${diffPaths}."
return
} else {
timeout(time: cmdTimeout, unit: 'SECONDS') {
device(device_ip, name, cmd)
}
}
}
}
}
}
}
}
def hasPathChanged(String gitDiff, List<String> paths) {
for (path in paths) {
if (gitDiff.contains(path)) {
return true
}
}
return false
}
def isReplay() {
def replayClass = "org.jenkinsci.plugins.workflow.cps.replay.ReplayCause"
return currentBuild.rawBuild.getCauses().any{ cause -> cause.toString().contains(replayClass) }
}
def setupCredentials() {
withCredentials([
string(credentialsId: 'azure_token', variable: 'AZURE_TOKEN'),
]) {
env.AZURE_TOKEN = "${AZURE_TOKEN}"
}
withCredentials([
string(credentialsId: 'ci_artifacts_pat', variable: 'CI_ARTIFACTS_TOKEN'),
]) {
env.CI_ARTIFACTS_TOKEN = "${CI_ARTIFACTS_TOKEN}"
}
withCredentials([
string(credentialsId: 'post_comments_github_pat', variable: 'GITHUB_COMMENTS_TOKEN'),
]) {
env.GITHUB_COMMENTS_TOKEN = "${GITHUB_COMMENTS_TOKEN}"
}
}
def step(String name, String cmd, Map args = [:]) {
return [name, cmd, args]
}
def chestnutStage(String name = "chestnut") {
deviceStage(name, "mici-chestnut-ci", ["UNSAFE=1", "CHESTNUT=1"], [
step("build", "./openpilot/selfdrive/test/chestnut.sh"),
step("model replay", "openpilot/selfdrive/test/process_replay/model_replay.py --chestnut"),
step("onroad tests", "./openpilot/selfdrive/test/test_onroad.py TestChestnutOnroad", [timeout: 120]),
])
}
node {
env.CI = "1"
env.PYTHONWARNINGS = "error"
env.TEST_DIR = "/data/openpilot"
env.SOURCE_DIR = "/data/openpilot_source/"
setupCredentials()
env.GIT_BRANCH = checkout(scm).GIT_BRANCH
env.GIT_COMMIT = checkout(scm).GIT_COMMIT
if (env.JOB_BASE_NAME == 'chestnut-stresstest') {
sh 'git fetch --no-tags origin nightly-chestnut'
env.GIT_COMMIT = sh(script: 'git show FETCH_HEAD:git_src_commit', returnStdout: true).trim()
if (!(env.GIT_COMMIT ==~ /[0-9a-f]{40}/)) {
error("invalid nightly-chestnut source commit")
}
def results = []
try {
timeout(time: 12, unit: 'HOURS') {
for (int run = 1; run <= 100; run++) {
results << "run ${run}: INCOMPLETE"
try {
chestnutStage("chestnut ${run}/100")
results[run - 1] = "run ${run}: PASS"
} catch (hudson.AbortException e) {
results[run - 1] = "run ${run}: FAIL"
echo e.toString()
}
}
}
} finally {
writeFile file: 'chestnut_stress_report.txt', text: "commit: ${env.GIT_COMMIT}\ncompleted: ${results.count { !it.endsWith('INCOMPLETE') }}/100\n" + results.join('\n') + '\n'
archiveArtifacts artifacts: 'chestnut_stress_report.txt'
}
if (results.any { !it.endsWith('PASS') }) {
error("chestnut stress test failed")
}
return
}
def excludeBranches = ['__nightly', '__nightly-chestnut', 'devel', 'devel-staging',
'release-tizi', 'release-tizi-staging', 'release-mici', 'release-mici-staging', 'testing-closet*', 'hotfix-*']
def excludeRegex = excludeBranches.join('|').replaceAll('\\*', '.*')
if (env.BRANCH_NAME != 'master' && !env.BRANCH_NAME.contains('__jenkins_loop_')) {
properties([
disableConcurrentBuilds(abortPrevious: true)
])
}
try {
if (env.BRANCH_NAME == 'devel-staging') {
deviceStage("build release-tizi-staging", "tizi-needs-can", [], [
step("build release-tizi-staging", "RELEASE_BRANCH=release-tizi-staging,release-mici-staging $SOURCE_DIR/tools/release/build_release.sh"),
])
}
if (env.BRANCH_NAME == '__nightly') {
parallel (
'nightly': {
deviceStage("build nightly", "tizi-needs-can", [], [
step("build nightly", "RELEASE_BRANCH=nightly $SOURCE_DIR/tools/release/build_release.sh"),
])
},
'nightly-dev': {
deviceStage("build nightly-dev", "tizi-needs-can", [], [
step("build nightly-dev", "PANDA_DEBUG_BUILD=1 RELEASE_BRANCH=nightly-dev $SOURCE_DIR/tools/release/build_release.sh"),
])
},
)
}
if (env.BRANCH_NAME == '__nightly-chestnut') {
parallel (
'nightly-chestnut': {
deviceStage("build nightly-chestnut", "mici-chestnut-ci", ["CHESTNUT=1"], [
step("build nightly-chestnut", "SCONSFLAGS=-j4 INCLUDE_BIG_MODEL=1 RELEASE_BRANCH=nightly-chestnut $SOURCE_DIR/tools/release/build_release.sh TestChestnutOnroad"),
])
},
'nightly-chestnut-dev': {
deviceStage("build nightly-chestnut-dev", "mici-chestnut-ci", ["CHESTNUT=1"], [
step("build nightly-chestnut-dev", "SCONSFLAGS=-j4 INCLUDE_BIG_MODEL=1 PANDA_DEBUG_BUILD=1 RELEASE_BRANCH=nightly-chestnut-dev $SOURCE_DIR/tools/release/build_release.sh TestChestnutOnroad"),
])
},
)
}
if (!env.BRANCH_NAME.matches(excludeRegex)) {
parallel (
'onroad tests': {
deviceStage("onroad", "tizi-needs-can", ["UNSAFE=1"], [
step("build openpilot", "cd openpilot/system/manager && ./build.py"),
step("check dirty", "tools/release/check-dirty.sh"),
step("onroad tests", "./openpilot/selfdrive/test/test_onroad.py", [timeout: 60]),
])
},
'HW + Unit Tests': {
deviceStage("tizi-hardware", "tizi-common", ["UNSAFE=1"], [
step("build", "cd openpilot/system/manager && ./build.py"),
step("test power draw", "./openpilot/selfdrive/test/test_power_draw.py"),
step("test encoder", "./openpilot/system/loggerd/tests/test_encoder.py", [diffPaths: ["openpilot/system/loggerd/"]]),
step("test manager", "./openpilot/system/manager/test/test_manager.py"),
])
},
'camerad OX03C10': {
deviceStage("OX03C10", "tizi-ox03c10", ["UNSAFE=1"], [
step("build", "cd openpilot/system/manager && ./build.py"),
step("test pandad", "./openpilot/selfdrive/pandad/tests/test_pandad.py"),
step("test camerad", "./openpilot/system/camerad/test/test_camerad.py", [timeout: 90]),
])
},
'camerad OS04C10': {
deviceStage("OS04C10", "tici-os04c10", ["UNSAFE=1"], [
step("build", "cd openpilot/system/manager && ./build.py"),
step("test pandad", "./openpilot/selfdrive/pandad/tests/test_pandad.py"),
step("test camerad", "./openpilot/system/camerad/test/test_camerad.py", [timeout: 90]),
])
},
'sensord': {
deviceStage("LSM + MMC", "tizi-lsmc", ["UNSAFE=1"], [
step("build", "cd openpilot/system/manager && ./build.py"),
step("test sensord", "./openpilot/system/sensord/tests/test_sensord.py"),
])
},
'replay': {
deviceStage("model-replay", "tizi-replay", ["UNSAFE=1"], [
step("build", "cd openpilot/system/manager && ./build.py", [diffPaths: ["openpilot/selfdrive/modeld/", "tinygrad_repo", "openpilot/selfdrive/test/process_replay/model_replay.py"]]),
step("model replay", "openpilot/selfdrive/test/process_replay/model_replay.py", [diffPaths: ["openpilot/selfdrive/modeld/", "tinygrad_repo", "openpilot/selfdrive/test/process_replay/model_replay.py"]]),
])
},
'tizi': {
deviceStage("tizi", "tizi", ["UNSAFE=1"], [
step("build openpilot", "cd openpilot/system/manager && ./build.py"),
step("test pandad loopback", "./openpilot/selfdrive/pandad/tests/test_pandad_loopback.py"),
step("test pandad spi", "./openpilot/selfdrive/pandad/tests/test_pandad_spi.py"),
step("test amp", "./openpilot/common/hardware/comma/tests/test_amplifier.py"),
])
},
'chestnut': {
chestnutStage()
},
)
}
} catch (Exception e) {
currentBuild.result = 'FAILED'
throw e
}
}
+1 -5
View File
@@ -6,11 +6,7 @@ Version 0.11.3 (2026-XX-XX)
* slowing down for curves
* adjusting speed based on surrounding traffic
* This behavior was previously available with openpilot's "Experimental mode", but is now out of beta and always enabled
* With openpilot deciding the speed to drive, the set speed is treated as a maximum speed openpilot will not exceed
* Driving personalities retuned to be more distinct
* Always-on sleep detection
* Improved comma four UI
* Romanian translation thanks to adriantabirta!
* With openpilot deciding which speed to drive, the car's cruise speed is treated as a maximum speed openpilot will not exceed
Version 0.11.2 (2026-10-14)
=======================
+35 -34
View File
@@ -6,8 +6,6 @@ import platform
import shlex
import importlib
import numpy as np
import nanobind
import eigen
import SCons.Errors
from SCons.Defaults import _stripixes
@@ -57,11 +55,24 @@ assert arch in [
"Darwin", # macOS arm64 (x86 not supported)
]
pkg_names = ['acados', 'capnproto', 'ffmpeg', 'json11', 'ncurses', 'zstd']
pkg_names = ['acados', 'capnproto', 'eigen', 'ffmpeg', 'json11', 'ncurses', 'zeromq', 'zstd']
pkgs = [importlib.import_module(name) for name in pkg_names]
acados = pkgs[pkg_names.index('acados')]
ffmpeg = pkgs[pkg_names.index('ffmpeg')]
# Shared package ships .so/.dylib; older device venvs still have static .a only.
# Keep static link deps (x264/z/va/drm) when the installed package is static so
# COMMA_HARDWARE CI works without upgrading the device venv yet.
# TODO: drop the static fallback once device venvs have comma-deps-ffmpeg>=7.1.0.post94
_ffmpeg_lib_names = os.listdir(ffmpeg.LIB_DIR) if os.path.isdir(ffmpeg.LIB_DIR) else []
ffmpeg_shared = any(
n.startswith('libavcodec.so') or (n.startswith('libavcodec') and n.endswith('.dylib'))
for n in _ffmpeg_lib_names
)
ffmpeg_libs = ['avformat', 'avcodec', 'swresample', 'avutil']
if not ffmpeg_shared:
ffmpeg_libs += ['x264', 'z']
if arch != "Darwin":
ffmpeg_libs += ['va', 'va-drm', 'drm']
acados_include_dirs = [
acados.INCLUDE_DIR,
os.path.join(acados.INCLUDE_DIR, "blasfeo", "include"),
@@ -149,11 +160,12 @@ env = Environment(
"#rednose_repo/rednose/helpers",
[x.LIB_DIR for x in pkgs],
],
RPATH=[ffmpeg.LIB_DIR],
RPATH=[ffmpeg.LIB_DIR] if ffmpeg_shared else [],
CYTHONCFILESUFFIX=".cpp",
COMPILATIONDB_USE_ABSPATH=True,
REDNOSE_ROOT="#rednose_repo",
tools=["default", "compilation_db", "rednose_filter"],
toolpath=["#rednose_repo/site_scons/site_tools"],
tools=["default", "cython", "compilation_db", "rednose_filter"],
toolpath=["#msgq_repo/site_scons/site_tools", "#rednose_repo/site_scons/site_tools"],
)
# SCons' Darwin linker tool doesn't define the variables used to expand RPATH.
if arch == "Darwin":
@@ -219,20 +231,6 @@ else:
np_version = SCons.Script.Value(np.__version__)
Export('envCython', 'np_version')
# ********** nanobind build environment **********
envNanobind = env.Clone(LIBS=[])
nanobind_dir = os.path.dirname(nanobind.__file__)
envNanobind.Append(CPPPATH=[sysconfig.get_paths()['include'], nanobind.include_dir(), os.path.join(nanobind_dir, "ext", "robin_map", "include"),
os.path.join(eigen.INCLUDE_DIR, "eigen3")],
CCFLAGS=["-fvisibility=hidden"])
envNanobind["CCFLAGS"] = [f for f in envNanobind["CCFLAGS"] if not f.startswith("-Wshadow")]
envNanobind["NANOBIND_SOURCE"] = os.path.join(nanobind_dir, "src", "nb_combined.cpp")
if arch == "Darwin":
envNanobind["LINKFLAGS"] = env["LINKFLAGS"] + ["-bundle", "-undefined", "dynamic_lookup"]
else:
envNanobind["LINKFLAGS"] = ["-pthread", "-shared"]
Export('envNanobind')
Export('env', 'arch', 'acados', 'release', 'ffmpeg_libs')
# Setup cache dir
@@ -256,11 +254,14 @@ def prune_cache_dir(target=None, source=None, env=None):
# Build common module
SConscript(['openpilot/common/SConscript'])
Import('_common')
common = [_common, 'json11']
common = [_common, 'json11', 'zmq']
Export('common')
# Build messaging (cereal + msgq + socketmaster + their dependencies)
SConscript(['msgq_repo/SConscript'])
# Enable swaglog include in submodules
env_swaglog = env.Clone()
env_swaglog['CXXFLAGS'].append('-DSWAGLOG="\\"common/swaglog.h\\""')
SConscript(['msgq_repo/SConscript'], exports={'env': env_swaglog})
SConscript(['openpilot/cereal/SConscript'])
@@ -304,7 +305,7 @@ if GetOption('extras') and arch != "comma_arm64":
env.CompilationDatabase('compile_commands.json')
# progress output
def get_scons_nodes(nodes):
def count_scons_nodes(nodes):
seen = set()
stack = list(nodes)
@@ -313,26 +314,26 @@ def get_scons_nodes(nodes):
if node in seen:
continue
seen.add(node)
# Only scan directories; generated sources are not ready yet.
stack += (node.prerequisites or []) + node.children(scan=isinstance(node, SCons.Node.FS.Dir))
executor = node.get_executor()
if executor is not None:
stack += executor.get_all_prerequisites() + executor.get_all_children()
return seen
return len(seen)
progress_interval = 5
progress_nodes = get_scons_nodes(env.arg2nodes(BUILD_TARGETS or [Dir('.')], env.fs.Entry))
progress_total = max(1, len(progress_nodes))
progress_count = 0
progress_total = max(1, count_scons_nodes(env.arg2nodes(BUILD_TARGETS or [Dir('.')], env.fs.Entry)))
def progress_function(node):
if node not in progress_nodes:
global progress_count
if progress_count >= progress_total:
return
progress_nodes.remove(node)
if len(progress_nodes) % progress_interval:
return
progress = round(100. * (1 - len(progress_nodes) / progress_total), 1)
progress_count = min(progress_count + progress_interval, progress_total)
progress = round(100. * progress_count / progress_total, 1)
sys.stderr.write("\rBuilding: %5.1f%%" % progress if sys.stderr.isatty() else "progress: %.1f\n" % progress)
if progress == 100. and sys.stderr.isatty():
sys.stderr.write("\n")
sys.stderr.flush()
Progress(progress_function)
Progress(progress_function, interval=progress_interval)
AddPostAction(BUILD_TARGETS or [Dir('.')], prune_cache_dir)
-199
View File
@@ -1,199 +0,0 @@
# a UP's DUT starts each job with an empty /data: these come back from master's last good job, as it left them
cache = ["/data/scons_cache"]
[env]
PYTHONPATH = "/data/ci/tree/openpilot" # the tree
TERM = "xterm-256color"
PYTHONWARNINGS = "error"
PYTHONFAULTHANDLER = "1"
COMMA_CACHE = "/data/tmp/comma_download_cache"
# as launch_env.sh sets for openpilot on a device
OMP_NUM_THREADS = "1"
MKL_NUM_THREADS = "1"
NUMEXPR_NUM_THREADS = "1"
OPENBLAS_NUM_THREADS = "1"
VECLIB_MAXIMUM_THREADS = "1"
# with the submodule package symlinks launch_chffrplus.sh makes
[steps.build]
name = "Build openpilot"
run = """
for p in msgq_repo/msgq opendbc_repo/opendbc rednose_repo/rednose teleoprtc_repo/teleoprtc tinygrad_repo/tinygrad; do ln -sfn "$p" "${p#*/}"; done
tools/op.sh build
"""
[steps.flash-chestnut]
name = "Flash Chestnut"
run = "sudo python3 openpilot/system/hardware/chestnut/flash.py"
# jobs run on comma fours, and on a comma 3x only where it differs, like its camera sensor
[jobs.onroad]
runs-on = "up-can"
timeout-minutes = 35
[[jobs.onroad.steps]]
uses = "build"
[[jobs.onroad.steps]]
name = "Check dirty"
run = "tools/release/check-dirty.sh"
# the UP replays the CAN until the step ends
[[jobs.onroad.steps]]
name = "Onroad tests"
run = "openpilot/tools/replay/can_replay.py && ./openpilot/selfdrive/test/test_onroad.py TestOnroad"
timeout-minutes = 1.5
[jobs.hardware]
runs-on = "up-mici"
timeout-minutes = 35
[[jobs.hardware.steps]]
uses = "build"
[[jobs.hardware.steps]]
name = "Encoder"
run = "./openpilot/system/loggerd/tests/test_encoder.py"
[[jobs.hardware.steps]]
name = "Manager"
run = "./openpilot/system/manager/test/test_manager.py"
[[jobs.hardware.steps]]
name = "Power draw"
run = "./openpilot/selfdrive/test/test_power_draw.py"
[jobs.install]
runs-on = "up-mici"
timeout-minutes = 45
[[jobs.install.steps]]
name = "Install this branch on a fresh mici"
run = 'scripts/test_mici_install.sh "https://installer.comma.ai/${GIT_REPO%/*}/$GIT_BRANCH" "$GIT_COMMIT"'
timeout-minutes = 20
[[jobs.install.steps]]
name = "Install the release on a fresh mici"
run = "scripts/test_mici_install.sh https://openpilot.comma.ai origin/release-mici"
timeout-minutes = 20
[jobs.replay]
runs-on = "up-mici"
timeout-minutes = 35
[[jobs.replay.steps]]
uses = "build"
[[jobs.replay.steps]]
name = "Model replay"
run = "openpilot/selfdrive/test/process_replay/model_replay.py"
[jobs.pandad]
runs-on = "up-mici"
timeout-minutes = 35
[[jobs.pandad.steps]]
uses = "build"
[[jobs.pandad.steps]]
name = "Pandad"
run = "./openpilot/selfdrive/pandad/tests/test_pandad.py"
[[jobs.pandad.steps]]
name = "Pandad loopback"
run = "./openpilot/selfdrive/pandad/tests/test_pandad_loopback.py"
[[jobs.pandad.steps]]
name = "Pandad SPI"
run = "./openpilot/selfdrive/pandad/tests/test_pandad_spi.py"
[jobs.camerad]
runs-on = "up-mici" # TODO: re-enable up-tres
timeout-minutes = 35
[[jobs.camerad.steps]]
uses = "build"
[[jobs.camerad.steps]]
name = "Camerad"
run = "./openpilot/system/camerad/test/test_camerad.py"
timeout-minutes = 1.5
[jobs.sensord]
runs-on = "up-mici"
timeout-minutes = 35
[[jobs.sensord.steps]]
uses = "build"
[[jobs.sensord.steps]]
name = "Sensord"
run = "./openpilot/system/sensord/tests/test_sensord.py"
# a comma four with a Chestnut on its aux port, which runs the big model
[jobs.chestnut]
runs-on = "chestnut"
timeout-minutes = 35
[[jobs.chestnut.steps]]
uses = "build"
[[jobs.chestnut.steps]]
uses = "flash-chestnut"
[[jobs.chestnut.steps]]
name = "Model replay"
run = "openpilot/selfdrive/test/process_replay/model_replay.py --chestnut"
[[jobs.chestnut.steps]]
name = "Onroad tests"
run = "./openpilot/selfdrive/test/test_onroad.py TestChestnutOnroad"
timeout-minutes = 2
[steps.release]
name = "Build and test the release"
run = """
trap 'rm -rf /data/gitkey /data/pandaextra' EXIT
printf '%s\n' "$RELEASE_KEY" > /data/gitkey && chmod 600 /data/gitkey
mkdir -p /data/pandaextra/certs && printf '%s\n' "$PANDA_RELEASE_KEY" > /data/pandaextra/certs/release
unset RELEASE_KEY PANDA_RELEASE_KEY
export GIT_SSH_COMMAND="ssh -i /data/gitkey -o StrictHostKeyChecking=accept-new"
git config remote.origin.url git@github.com:commaai/openpilot.git
if [ -n "${UP_REMOTE:-}" ]; then openpilot/tools/replay/can_replay.py; fi
tools/release/build_release.sh $RELEASE_TESTS
"""
[jobs.nightly]
runs-on = "up-can"
timeout-minutes = 90
push = ["nightly"]
env = { RELEASE_TESTS = "TestOnroad" }
steps = [{ uses = "build" }, { uses = "release" }]
[jobs.nightly-dev]
runs-on = "up-can"
timeout-minutes = 90
push = ["nightly-dev"]
env = { RELEASE_TESTS = "TestOnroad", PANDA_DEBUG_BUILD = "1" }
steps = [{ uses = "build" }, { uses = "release" }]
[jobs.release-staging]
runs-on = "up-can"
timeout-minutes = 90
push = ["release-tizi-staging", "release-mici-staging"]
env = { RELEASE_TESTS = "TestOnroad" }
steps = [{ uses = "build" }, { uses = "release" }]
[jobs.nightly-chestnut]
runs-on = "chestnut"
timeout-minutes = 150
push = ["nightly-chestnut"]
env = { RELEASE_TESTS = "TestChestnutOnroad TestChestnutDrive", INCLUDE_BIG_MODEL = "1", SCONSFLAGS = "-j4" }
steps = [{ uses = "build" }, { uses = "flash-chestnut" }, { uses = "release" }]
[jobs.nightly-chestnut-dev]
runs-on = "chestnut"
timeout-minutes = 90
push = ["nightly-chestnut-dev"]
env = { RELEASE_TESTS = "TestChestnutOnroad", INCLUDE_BIG_MODEL = "1", SCONSFLAGS = "-j4", PANDA_DEBUG_BUILD = "1" }
steps = [{ uses = "build" }, { uses = "flash-chestnut" }, { uses = "release" }]
+1 -26
View File
@@ -5,8 +5,6 @@ openpilot ALC and openpilot LDW do not automatically drive the vehicle or reduce
While changing lanes, openpilot is not capable of looking next to you or checking your blind spot. Only nudge the wheel to initiate a lane change after you have confirmed it's safe to do so.
Unexpected steering may occur. openpilot ALC may not steer to avoid stopped or slow-moving vehicles, cross traffic, construction barriers or cones, motorcycles, children, pedestrians, animals, or other objects on the road.
Many factors can impact the performance of openpilot ALC and openpilot LDW, causing them to be unable to function as intended. These include, but are not limited to:
* Poor visibility (heavy rain, snow, fog, etc.) or weather conditions that may interfere with sensor operation.
@@ -15,14 +13,6 @@ Many factors can impact the performance of openpilot ALC and openpilot LDW, caus
* The device is mounted incorrectly.
* When in sharp curves, like on-off ramps, intersections etc...; openpilot is designed to be limited in the amount of steering torque it can produce.
* In the presence of restricted lanes or construction zones.
* When the lane markings are unclear, worn, missing, or they cross each other.
* Tar marks, shadows, road cracks, temporary or construction lane markings, or other road imperfections.
* When lanes merge or split.
* When entering a highway on-ramp or exiting an off-ramp.
* On roads with intersections or roundabouts.
* On slippery roads.
* When towing a trailer.
* When entering or exiting a tunnel.
* When driving on highly banked roads or in presence of strong cross-wind.
* Extremely hot or cold temperatures.
* Bright light (due to oncoming headlights, direct sunlight, etc.).
@@ -34,8 +24,6 @@ The list above does not represent an exhaustive list of situations that may inte
openpilot ACC and openpilot FCW are not systems that allow careless or inattentive driving. It is still necessary for the driver to pay close attention to the vehicle’s surroundings and to be ready to re-take control of the gas and the brake at all times.
openpilot ACC may not stop your vehicle in time to avoid a collision with a vehicle that quickly stops in front of you. openpilot ACC may occasionally cause your vehicle to brake when not required or when you are not expecting it.
Many factors can impact the performance of openpilot ACC and openpilot FCW, causing them to be unable to function as intended. These include, but are not limited to:
* Poor visibility (heavy rain, snow, fog, etc.) or weather conditions that may interfere with sensor operation.
@@ -47,20 +35,9 @@ Many factors can impact the performance of openpilot ACC and openpilot FCW, caus
* In presence of traffic signs or stop lights, which are not detected by openpilot at this time.
* When the posted speed limit is below the user selected set speed. openpilot does not detect speed limits at this time.
* In presence of vehicles in the same lane that are not moving.
* When a vehicle you are following moves out of your driving path and a stationary or slow-moving vehicle or object is in front of you.
* Narrow vehicles, such as bicycles or motorcycles.
* Vehicles or objects only partially in the driving lane.
* On curves, openpilot ACC may not detect a vehicle in the same lane, and may accelerate to the set speed.
* Cross traffic.
* Oncoming vehicles.
* Animals or objects in the road.
* Rare objects such as trailers, ramps, cargo, open doors, etc. protruding from vehicles.
* When abrupt braking maneuvers are required. openpilot is designed to be limited in the amount of deceleration and acceleration that it can produce.
* When surrounding vehicles perform close cut-ins from neighbor lanes.
* Driving on hills, narrow, or winding roads.
* On slippery roads.
* When towing a trailer.
* When entering or exiting a tunnel.
* Extremely hot or cold temperatures.
* Bright light (due to oncoming headlights, direct sunlight, etc.).
* Interference from other equipment that generates radar waves.
@@ -69,9 +46,7 @@ The list above does not represent an exhaustive list of situations that may inte
## Limitations of openpilot DM
openpilot DM displays a series of escalating warnings. Disregard of these warnings may result in openpilot being unavailable for a period of time.
openpilot DM should not be considered an exact measurement of the alertness of the driver. openpilot DM cannot always detect if the driver is tired or inattentive.
openpilot DM should not be considered an exact measurement of the alertness of the driver.
Many factors can impact the performance of openpilot DM, causing it to be unable to function as intended. These include, but are not limited to:
-6
View File
@@ -4,12 +4,6 @@ openpilot is an Adaptive Cruise Control (ACC) and Automated Lane Centering (ALC)
Like other ACC and ALC systems, openpilot is a failsafe passive system and it requires the
driver to be alert and to pay attention at all times.
openpilot is not an autonomous driving system. It is not a collision avoidance system or a
substitute for safe and attentive driving. The driver is always responsible for the safe
operation of the vehicle and must be ready to take control at any time. The driver can override
openpilot at any time by braking, accelerating, or steering the vehicle. openpilot may
disengage without warning. Read the [limitations](https://github.com/commaai/openpilot/blob/master/docs/LIMITATIONS.md) carefully before using openpilot.
To assist the driver in maintaining alertness, openpilot includes a driver monitoring feature
that alerts when it detects driver distraction.
+5
View File
@@ -12,6 +12,11 @@ function agnos_init {
# set success flag for current boot slot
sudo abctl --set_success
# TODO: do this without udev in AGNOS
# udev does this, but sometimes we startup faster
sudo chgrp gpu /dev/adsprpc-smd /dev/ion /dev/kgsl-3d0
sudo chmod 660 /dev/adsprpc-smd /dev/ion /dev/kgsl-3d0
# Check if AGNOS update is required
if [ "$(< /VERSION)" != "$AGNOS_VERSION" ]; then
AGNOS_PY="$DIR/openpilot/common/hardware/comma/agnos.py"
+10 -1
View File
@@ -6,8 +6,17 @@ export NUMEXPR_NUM_THREADS=1
export OPENBLAS_NUM_THREADS=1
export VECLIB_MAXIMUM_THREADS=1
# models get lower priority than ui
# - ui is ~5ms
# - modeld is 20ms
# - DM is 10ms
# in order to run ui at 60fps (16.67ms), we need to allow
# it to preempt the model workloads. we have enough
# headroom for this until ui is moved to the CPU.
export QCOM_PRIORITY=12
if [ -z "$AGNOS_VERSION" ]; then
export AGNOS_VERSION="20.6"
export AGNOS_VERSION="19.9-sunnypilot.3"
fi
export STAGING_ROOT="/data/safe_staging"
-563
View File
@@ -1,563 +0,0 @@
#!/usr/bin/env python3
"""A small Git LFS client backed by a Hugging Face bucket."""
import argparse
import concurrent.futures
import contextlib
import fcntl
import fnmatch
import functools
import hashlib
import http.client
import io
import json
import os
from pathlib import Path
import re
import shutil
import subprocess
import sys
import tempfile
import time
import urllib.error
import urllib.request
POINTER_VERSION = "https://git-lfs.github.com/spec/v1"
POINTER_RE = re.compile(rb"\Aversion " + POINTER_VERSION.encode() + rb"\noid sha256:([0-9a-f]{64})\nsize ([0-9]+)\n\Z")
BUCKET = os.environ.get("OPENPILOT_LFS_BUCKET", "sunnypilot/sunnypilot-lfs")
ZERO = "0" * 40
RANGES = 8
RANGE_MIN = 16 << 20
TRUE_VALUES = ("1", "ON", "YES", "TRUE")
def git(*args, stdin=None, check=True):
return subprocess.run(["git", *args], input=stdin, capture_output=True, check=check).stdout
ROOT, GIT_DIR = map(Path, git("rev-parse", "--path-format=absolute", "--show-toplevel", "--git-common-dir").decode().splitlines())
STORE = GIT_DIR / "lfs" / "objects"
# TODO: Remove this helper and its call once migration from stock Git LFS is no longer supported.
def remove_git_lfs_hooks(directory):
for name in ("pre-push", "post-checkout", "post-commit", "post-merge"):
path = directory / name
if not path.is_file() or path.is_symlink() or path.stat().st_size > 1024:
continue
lines = [line.strip() for line in path.read_text(errors="replace").splitlines() if line.strip()]
commands = {f'git lfs {name} "$@"'}
if name == "pre-push":
commands.update(('git lfs push --stdin $*', 'git lfs push --stdin "$@"'))
if lines and re.fullmatch(r'exec "?[^"]*/git-lfs"? pre-push "\$@"', lines[-1]): # hooks from tools/op.sh (#38775, #39114)
commands.add(lines[-1])
has_lfs_guard = len(lines) == 3 and lines[1].startswith("command -v git-lfs ")
if lines[:1] == ["#!/bin/sh"] and lines[-1] in commands and (len(lines) == 2 or has_lfs_guard):
path.unlink()
def write_executable(path, data):
# replace atomically so git never runs a partly written script
with tempfile.NamedTemporaryFile(dir=path.parent, prefix=f".{path.name}-", delete=False) as tmp:
tmp.write(data)
os.chmod(tmp.name, 0o755)
os.replace(tmp.name, path)
def install():
script = GIT_DIR / "lfs.py"
hook = Path(git("rev-parse", "--path-format=absolute", "--git-path", "hooks/pre-push").decode().strip())
remove_git_lfs_hooks(hook.parent)
remove_git_lfs_hooks(hook.parent / "post-commit.d") # where `op post-commit` moves an existing post-commit hook
hook_script = '#!/bin/sh\nexec "$(git rev-parse --git-common-dir)/lfs.py" pre-push "$@"\n'
custom_hook = hook.is_file() and hook.read_text(errors="replace") != hook_script
if Path(__file__).resolve() != script:
write_executable(script, Path(__file__).read_bytes())
script.chmod(0o755)
if custom_hook:
# keep it so pulls and updates still work; pushes won't upload LFS objects until the hook runs lfs.py
print(f"lfs.py: keeping custom hook {hook}; add this line to it to upload LFS objects on push: {hook_script.splitlines()[-1]}", file=sys.stderr)
else:
hook.parent.mkdir(parents=True, exist_ok=True)
write_executable(hook, hook_script.encode())
# TODO: Remove legacy worktree filter cleanup once migration from stock Git LFS is no longer supported.
git("config", "--worktree", "--remove-section", "filter.lfs", check=False)
git("config", "--local", "filter.lfs.process", '"$(git rev-parse --git-common-dir)/lfs.py" filter-process')
# a client that can't run fails git rather than committing raw files; failed downloads still leave the pointer
git("config", "--local", "filter.lfs.required", "true")
def object_path(oid):
return STORE / oid[:2] / oid[2:4] / oid
def pointer(oid, size):
return f"version {POINTER_VERSION}\noid sha256:{oid}\nsize {size}\n".encode()
def parse_pointer(data):
match = POINTER_RE.match(data)
return (match[1].decode(), int(match[2])) if match else None
@contextlib.contextmanager
def object_lock(oid):
path = GIT_DIR / "lfs" / "locks" / (oid + ".lock")
path.parent.mkdir(parents=True, exist_ok=True)
with path.open("a+b") as lock:
fcntl.flock(lock, fcntl.LOCK_EX)
yield
def valid(path, size):
return path.is_file() and path.stat().st_size == size
def hash_file(path):
digest = hashlib.sha256()
with path.open("rb") as stream:
for chunk in iter(lambda: stream.read(1024 * 1024), b""):
digest.update(chunk)
return digest.hexdigest()
def store(chunks):
STORE.mkdir(parents=True, exist_ok=True)
with tempfile.TemporaryDirectory(prefix="incoming-", dir=STORE) as directory:
tmp = Path(directory) / "object"
digest, size = hashlib.sha256(), 0
with tmp.open("xb") as out:
for chunk in chunks:
out.write(chunk)
digest.update(chunk)
size += len(chunk)
if size == 0:
return b""
if size <= 1024:
data = tmp.read_bytes()
if parse_pointer(data):
return data
oid = digest.hexdigest()
dst = object_path(oid)
with object_lock(oid):
if not valid(dst, size):
dst.parent.mkdir(parents=True, exist_ok=True)
os.replace(tmp, dst)
else:
dst.touch()
return pointer(oid, size)
def transfer_workers():
return int(git("config", "--get", "--default", "16", "lfs.concurrenttransfers"))
def parallel(function, arguments, workers=None):
if workers is None:
workers = transfer_workers()
with concurrent.futures.ThreadPoolExecutor(max_workers=workers) as pool:
futures = [pool.submit(function, *args) for args in arguments]
return [future.result() for future in futures]
def hf_request(url, **kwargs):
request = urllib.request.Request(url, **kwargs)
if os.environ.get("HF_HUB_DISABLE_IMPLICIT_TOKEN", "").upper() not in TRUE_VALUES:
hf_home = Path(os.environ.get("HF_HOME", Path(os.environ.get("XDG_CACHE_HOME", "~/.cache")) / "huggingface")).expanduser()
token_path = Path(os.environ.get("HF_TOKEN_PATH", hf_home / "token")).expanduser()
token = os.environ.get("HF_TOKEN") or os.environ.get("HUGGING_FACE_HUB_TOKEN")
if not token and token_path.is_file():
token = token_path.read_text().strip()
if token:
request.add_unredirected_header("Authorization", f"Bearer {token.strip()}")
return request
def object_info(objects):
keys = [f"sha256/{oid}" for oid in objects]
found = {}
for start in range(0, len(keys), 1000):
request = hf_request(f"https://huggingface.co/api/buckets/{BUCKET}/paths-info",
data=json.dumps({"paths": keys[start:start + 1000]}).encode(), headers={"Content-Type": "application/json"})
with urllib.request.urlopen(request, timeout=30) as response:
found.update((item["path"], item["size"]) for item in json.load(response))
return found
def download_http(oid, size, path, span=None, url=None, headers=None):
ranges = min(RANGES, max(1, (size + RANGE_MIN - 1) // RANGE_MIN))
if span is None and ranges > 1:
# each range writes its own slice of one preallocated file
with path.open("wb") as out:
out.truncate(size)
parallel(download_http, [(oid, size, path, (i * size // ranges, (i + 1) * size // ranges - 1), url, headers) for i in range(ranges)], ranges)
return
if url is None:
request = hf_request(f"https://huggingface.co/buckets/{BUCKET}/resolve/sha256/{oid}")
else:
request = urllib.request.Request(url, headers=headers or {})
if span is not None:
request.add_header("Range", f"bytes={span[0]}-{span[1]}")
expected_size = size if span is None else span[1] - span[0] + 1
for attempt in range(4):
try:
with urllib.request.urlopen(request, timeout=30) as response, path.open("wb" if span is None else "r+b") as out:
if span is not None and (response.status != 206 or response.headers.get("Content-Range") != f"bytes {span[0]}-{span[1]}/{size}"):
raise RuntimeError(f"invalid range response for {oid}")
out.seek(0 if span is None else span[0])
written = 0
while chunk := response.read(1024 * 1024):
out.write(chunk)
written += len(chunk)
if written != expected_size:
raise http.client.HTTPException(f"incomplete download for {oid}")
return
except (urllib.error.URLError, http.client.HTTPException, TimeoutError, ConnectionError) as error:
retryable = not isinstance(error, urllib.error.HTTPError) or error.code in (408, 429) or 500 <= error.code < 600
if not retryable or attempt == 3:
raise
time.sleep(2 ** attempt)
@functools.cache
def lfs_config(key):
# like stock git-lfs: git config first, then .lfsconfig
value = git("config", "--get", f"lfs.{key}", check=False).decode().strip()
return value or git("config", "-f", str(ROOT / ".lfsconfig"), "--get", f"lfs.{key}", check=False).decode().strip()
def endpoint_objects(objects):
"""oid -> (href, headers) for the objects the git-lfs server at lfs.url has. A fork's own objects aren't in the bucket."""
found = {}
items = list(objects.items())
for start in range(0, len(items), 100):
body = {"operation": "download", "transfers": ["basic"], "objects": [{"oid": oid, "size": size} for oid, size in items[start:start + 100]]}
request = urllib.request.Request(lfs_config("url").rstrip("/") + "/objects/batch", data=json.dumps(body).encode(),
headers={"Accept": "application/vnd.git-lfs+json", "Content-Type": "application/vnd.git-lfs+json"})
with urllib.request.urlopen(request, timeout=30) as response:
for item in json.load(response)["objects"]:
if download := item.get("actions", {}).get("download"):
found[item["oid"]] = (download["href"], download.get("header", {}))
return found
def download_one(oid, size):
dst = object_path(oid)
with object_lock(oid):
if valid(dst, size):
dst.touch()
return dst
dst.parent.mkdir(parents=True, exist_ok=True)
with tempfile.TemporaryDirectory(prefix=f"{oid}-", dir=dst.parent) as directory:
tmp = Path(directory) / "object"
try:
download_http(oid, size, tmp)
except urllib.error.HTTPError as error:
if error.code != 404 or not lfs_config("url") or oid not in (found := endpoint_objects({oid: size})):
raise
download_http(oid, size, tmp, url=found[oid][0], headers=found[oid][1])
if tmp.stat().st_size != size or hash_file(tmp) != oid:
raise RuntimeError(f"sha256 mismatch for {oid}")
os.replace(tmp, dst)
return dst
def excluded(name, patterns):
for pattern in filter(None, patterns.split(",")):
pattern = pattern.strip().lstrip("/").rstrip("/")
paths = [name, *(str(p) for p in Path(name).parents)]
if "/" not in pattern:
paths.extend(Path(name).parts)
if pattern and any(fnmatch.fnmatchcase(path, pattern) for path in paths):
return True
return False
def smudge(data, name, exclude, pool=None):
if os.environ.get("GIT_LFS_SKIP_SMUDGE", "").upper() in TRUE_VALUES or excluded(name, exclude):
return data
parsed = parse_pointer(data)
if not parsed:
return data
oid, size = parsed
if pool is not None and not valid(object_path(oid), size):
return pool.submit(download_one, oid, size)
return download_one(oid, size)
def read_packets(stream):
while True:
header = stream.read(4)
if len(header) != 4:
raise EOFError
length = int(header, 16)
if length == 0:
return
if length < 4:
raise RuntimeError("unsupported pkt-line control packet")
yield stream.read(length - 4)
def write_packets(source):
if isinstance(source, bytes):
source = (source,)
for chunk in source:
for start in range(0, len(chunk), 65512):
packet = chunk[start : start + 65512]
sys.stdout.buffer.write(f"{len(packet) + 4:04x}".encode() + packet)
sys.stdout.buffer.write(b"0000")
sys.stdout.buffer.flush()
def filter_process():
exclude = lfs_config("fetchexclude")
list(read_packets(sys.stdin.buffer))
write_packets((b"git-filter-server\n", b"version=2\n"))
capabilities = {line.rstrip(b"\n") for line in read_packets(sys.stdin.buffer)}
write_packets(capability + b"\n" for capability in (b"capability=clean", b"capability=smudge", b"capability=delay")
if capability in capabilities)
pending, ready, pointers = {}, {}, {}
with concurrent.futures.ThreadPoolExecutor(max_workers=transfer_workers()) as pool:
while True:
try:
fields = dict(line.rstrip(b"\n").split(b"=", 1) for line in read_packets(sys.stdin.buffer))
except EOFError:
return
if fields[b"command"] == b"list_available_blobs":
if pending:
concurrent.futures.wait(pending.values(), return_when=concurrent.futures.FIRST_COMPLETED)
available = [name for name, future in pending.items() if future.done()]
for name in available:
ready[name] = pending.pop(name)
write_packets(b"pathname=" + name + b"\n" for name in available)
write_packets(b"status=success\n")
continue
content = read_packets(sys.stdin.buffer)
name = fields[b"pathname"]
if fields[b"command"] == b"clean":
result = store(content)
else:
data = b"".join(content)
if name in ready: # git sends no content when it asks again for a delayed blob
data = pointers.pop(name)
try:
result = ready.pop(name).result() if name in ready else smudge(data, os.fsdecode(name), exclude,
pool if fields.get(b"can-delay") == b"1" else None)
except Exception as error:
print(f"lfs.py: {os.fsdecode(name)}: {error}; leaving the pointer, run ./lfs.py pull to retry", file=sys.stderr)
result = data
if isinstance(result, concurrent.futures.Future):
pending[name] = result
pointers[name] = data
write_packets(b"status=delayed\n")
continue
write_packets(b"status=success\n")
if isinstance(result, Path):
with result.open("rb") as source_stream:
write_packets(iter(lambda: source_stream.read(65512), b""))
else:
write_packets(result)
write_packets(())
def cat_small(oids):
checked = git("cat-file", "--batch-check=%(objectname) %(objecttype) %(objectsize)", stdin=("\n".join(oids) + "\n").encode()).decode().splitlines()
small = [line.split()[0] for line in checked if len(line.split()) == 3 and line.split()[1] == "blob" and int(line.split()[2]) <= 1024]
stream = io.BytesIO(git("cat-file", "--batch", stdin=("\n".join(small) + "\n").encode()))
for oid in small:
size = int(stream.readline().split()[2])
yield oid, stream.read(size)
stream.read(1)
def pointers_for_index():
paths = {}
for entry in filter(None, git("-C", str(ROOT), "ls-files", "--stage", "-z").split(b"\0")):
metadata, path = entry.split(b"\t", 1)
mode, oid, stage = metadata.split()
if stage == b"0" and mode in (b"100644", b"100755"):
paths.setdefault(oid.decode(), []).append(path.decode(errors="surrogateescape"))
found = {}
for oid, data in cat_small(paths):
if parsed := parse_pointer(data):
found.setdefault(parsed, []).extend(paths[oid])
return found
def prune():
heads, blobs = [], set()
for directory in [GIT_DIR, *(GIT_DIR / "worktrees").glob("*")]:
args = ("-C", str(ROOT), "--git-dir", str(directory))
if head := git(*args, "rev-parse", "--verify", "--quiet", "HEAD", check=False).decode().strip():
heads.append(head)
entries = git(*args, "ls-files", "--stage", "-z")
blobs.update(entry.split(b"\t", 1)[0].split()[1].decode() for entry in entries.split(b"\0") if entry)
stashes = git("reflog", "show", "--format=%H %P", "refs/stash", check=False).decode().split()
for ref in set(heads + stashes):
entries = git("ls-tree", "-r", "-z", ref)
blobs.update(entry.split(b"\t", 1)[0].split()[2].decode() for entry in entries.split(b"\0") if entry)
remote = git("config", "--get", "--default", "origin", "lfs.pruneremotetocheck").decode().strip()
blobs.update(git("rev-list", "--objects", "--no-object-names", *heads, *stashes, "--all", "--not",
f"--remotes={remote}").decode().splitlines())
retained = {parsed[0] for _oid, data in cat_small(blobs) if (parsed := parse_pointer(data))}
cutoff = time.time() - 7 * 24 * 60 * 60 # noqa: TID251
removed, freed = 0, 0
for path in STORE.glob("??/??/*"):
if path.name in retained or not re.fullmatch(r"[0-9a-f]{64}", path.name):
continue
with object_lock(path.name):
if path.is_file() and path.stat().st_mtime < cutoff:
freed += path.stat().st_size
path.unlink()
removed += 1
print(f"Pruned {removed} objects ({freed / 1024**2:.1f} MiB)")
def pull(exclude=None):
install()
found = pointers_for_index()
if exclude is None:
exclude = lfs_config("fetchexclude")
if exclude:
found = {obj: kept for obj, paths in found.items() if (kept := [path for path in paths if not excluded(path, exclude)])}
parallel(download_one, found)
materialized = []
for (oid, size), paths in found.items():
for name in paths:
relative = Path(name)
if any((ROOT / part).is_symlink() for part in (relative, *relative.parents)):
continue
path = ROOT / relative
try:
if path.stat().st_size > 1024 or parse_pointer(path.read_bytes()) != (oid, size):
continue
except (FileNotFoundError, IsADirectoryError):
continue
with tempfile.TemporaryDirectory(prefix=path.name + "-", dir=path.parent) as directory:
tmp = shutil.copyfile(object_path(oid), Path(directory) / "object")
shutil.copymode(path, tmp)
Path(tmp).replace(path)
materialized.append(name)
if materialized:
# Clear pointer stat data without changing staged blob IDs or modes.
entries = git("--literal-pathspecs", "-C", str(ROOT), "ls-files", "--stage", "-z", "--", *materialized)
git("update-index", "-z", "--index-info", stdin=entries)
git("update-index", "-q", "--refresh", check=False)
def bucket_request(path, data=None):
headers = {"Content-Type": "application/x-ndjson"} if data is not None else {}
request = hf_request(f"https://huggingface.co/api/buckets/{BUCKET}/{path}", data=data, headers=headers)
for attempt in range(4):
try:
with urllib.request.urlopen(request, timeout=30) as response:
return response.read(), response.headers
except (urllib.error.URLError, http.client.HTTPException, TimeoutError, ConnectionError) as error:
retryable = not isinstance(error, urllib.error.HTTPError) or error.code in (408, 429) or 500 <= error.code < 600
if not retryable or attempt == 3:
raise
time.sleep(2 ** attempt)
def upload_xet(objects, upload_files):
def connection():
_, headers = bucket_request("xet-write-token")
return headers["X-Xet-Cas-Url"], (headers["X-Xet-Access-Token"], int(headers["X-Xet-Token-Expiration"]))
oids = list(objects)
for start in range(0, len(oids), 100):
batch = oids[start:start + 100]
paths = [object_path(oid) for oid in batch]
endpoint, token = connection()
infos = upload_files([str(path) for path in paths], endpoint, token, lambda: connection()[1], None, "bucket", skip_sha256=True)
payload = b"".join(json.dumps({"type": "addFile", "path": f"sha256/{oid}", "xetHash": info.hash,
"mtime": int(path.stat().st_mtime * 1000)}).encode() + b"\n"
for oid, path, info in zip(batch, paths, infos, strict=True))
bucket_request("batch", payload)
def upload(objects):
objects = dict(objects)
if not objects:
return
existing = object_info(objects)
pending = {}
for oid, size in objects.items():
key = f"sha256/{oid}"
if key in existing:
if existing[key] != size:
raise RuntimeError(f"invalid bucket object {oid}: size {existing[key]}, expected {size}")
continue
pending[oid] = size
if not pending:
return
try:
from hf_xet import upload_files
except ImportError:
raise RuntimeError("Missing hf-xet: run 'uv sync' and activate .venv.") from None
for oid, size in pending.items():
path = object_path(oid)
if not valid(path, size):
raise RuntimeError(f"missing local LFS object {oid}")
if hash_file(path) != oid:
raise RuntimeError(f"local sha256 mismatch for {oid}")
upload_xet(pending, upload_files)
uploaded = object_info(pending)
for oid, size in pending.items():
if uploaded.get(f"sha256/{oid}") != size:
raise RuntimeError(f"uploaded object {oid} is missing or has the wrong size")
def pre_push(remote):
if os.environ.get("GIT_LFS_SKIP_PUSH", "").upper() in TRUE_VALUES:
return
input_data = sys.stdin.buffer.read()
updates = (line.decode().split() for line in input_data.splitlines())
local_oids = [local_oid for _local_ref, local_oid, _remote_ref, _remote_oid in updates if local_oid != ZERO]
if not local_oids:
return
output = git("rev-list", "--objects", "--no-object-names", *local_oids, "--not", f"--remotes={remote}")
object_ids = output.decode().splitlines()
objects = [parsed for _oid, data in cat_small(object_ids) if (parsed := parse_pointer(data))]
try:
upload(objects)
except urllib.error.HTTPError as error:
if error.code not in (401, 403):
raise
if lfs_config("url"):
# without write access to the bucket, a fork's objects only need to be on its own LFS server
in_bucket = object_info(dict(objects)) # upload() asked this too, but doesn't return it
pending = {oid: size for oid, size in objects if f"sha256/{oid}" not in in_bucket}
if missing := sorted(pending.keys() - endpoint_objects(pending).keys()):
sys.exit(f"lfs.py: {len(missing)} LFS objects are in neither {BUCKET} nor {lfs_config('url')}, push them first: " +
f"git lfs push --object-id {remote} {' '.join(missing)}")
return
sys.exit(f"lfs.py: uploading LFS objects to {BUCKET} needs a Hugging Face token with write access (hf auth login, or set HF_TOKEN)")
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("command", choices=("filter-process", "pull", "pre-push", "install", "ls-files", "prune"))
parser.add_argument("remote", nargs="?", default="origin")
parser.add_argument("url", nargs="?")
parser.add_argument("--exclude", help="comma-separated path globs to leave as pointers; overrides lfs.fetchexclude")
args = parser.parse_args()
if args.command == "filter-process":
filter_process()
elif args.command == "pull":
pull(args.exclude)
elif args.command == "pre-push":
pre_push(args.remote)
elif args.command == "install":
install()
elif args.command == "prune":
prune()
elif args.command == "ls-files":
for (oid, _size), paths in pointers_for_index().items():
for path in paths:
print(f"{oid} {path}")
if __name__ == "__main__":
main()
+1
View File
@@ -15,6 +15,7 @@ cereal = env.Library('cereal', [f'gen/cpp/{s}.c++' for s in all_output])
# Build messaging
services_h = env.Command(['services.h'], ['services.py'], 'python3 ' + cereal_dir.path + '/services.py > $TARGET')
env.Program('messaging/bridge', ['messaging/bridge.cc', 'messaging/msgq_to_zmq.cc', 'messaging/bridge_zmq.cc'], LIBS=[msgq, common, 'pthread'])
socketmaster = env.Library('socketmaster', ['messaging/socketmaster.cc'])
+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 {
+15 -21
View File
@@ -100,7 +100,6 @@ struct OnroadEvent @0xc4fa6047f024e718 {
startupNoControl @62;
startupNoSecOcKey @63;
startupMaster @64;
startupCruiseCanceled @105;
fcw @65;
steerSaturated @66;
belowEngageSpeed @67;
@@ -121,7 +120,10 @@ struct OnroadEvent @0xc4fa6047f024e718 {
steerTimeLimit @83;
vehicleSensorsInvalid @84;
locationdTemporaryError @85;
locationdPermanentError @86;
paramsdTemporaryError @87;
paramsdPermanentError @88;
actuatorsApiUnavailable @89;
espActive @90;
personalityChanged @91;
aeb @92;
@@ -137,9 +139,6 @@ struct OnroadEvent @0xc4fa6047f024e718 {
usbErrorDEPRECATED @78;
audioFeedbackDEPRECATED @97;
bigModelReadyDEPRECATED @101;
locationdPermanentErrorDEPRECATED @86;
paramsdPermanentErrorDEPRECATED @88;
actuatorsApiUnavailableDEPRECATED @89;
}
}
@@ -591,29 +590,25 @@ struct PandaState @0xa7649e2575e4591e {
interruptRateGmlanDEPRECATED @6;
interruptRateInterrupts @7;
interruptRateSpiDma @8;
selfTestCpu @9;
selfTestRam @10;
selfTestFlash @11;
ecc @12;
outputReadback @13;
dma @14;
interruptRateSpiCs @9;
interruptRateUart1 @10;
interruptRateUart2 @11;
interruptRateUart3 @12;
interruptRateUart5 @13;
interruptRateUartDma @14;
interruptRateUsb @15;
clock @16;
interruptMissing @17;
interruptRateTim1 @16;
interruptRateTim3 @17;
registerDivergent @18;
interruptRateKlineInit @19;
interruptRateClockSource @20;
interruptRateTick @21;
interruptRateExti @22;
interruptRateSpi @23;
adc @24;
interruptRateUart7 @24;
sirenMalfunction @25;
heartbeatLoopWatchdog @26;
interruptRateSoundDma @27;
mpu @28;
timer @29;
safetyRedundancy @30;
# Update max fault type in pandad when adding faults
# Update max fault type in boardd when adding faults
}
enum PandaType @0x8a58adf93e5b3751 {
@@ -837,8 +832,7 @@ struct SelfdriveState {
refuse @3;
warningSoft @4;
warningImmediateSystem @5;
warningImmediateUser @11;
warningImmediate @5;
prompt @6;
promptRepeat @7;
@@ -1246,6 +1240,7 @@ struct LongitudinalPlan @0xe00b5b3eba12876c {
shouldStop @37: Bool;
allowThrottle @38: Bool;
allowBrake @39: Bool;
accelBoost @40 :Float32;
solverExecutionTime @35 :Float32;
@@ -1287,7 +1282,6 @@ struct LongitudinalPlan @0xe00b5b3eba12876c {
gpsTrajectory @12 :Deprecated.GpsTrajectory;
gpsPlannerActive @19 :Bool;
personality @36 :LongitudinalPersonality;
accelBoost @40 :Float32;
}
}
struct UiPlan {
+11 -5
View File
@@ -1,6 +1,6 @@
# must be built with scons
from msgq import fake_event_handle, drain_sock_raw, MultiplePublishersError, IpcError, \
Poller, SubSocket, PubSocket, SocketEventHandle, toggle_fake_events, \
Context, Poller, SubSocket, PubSocket, SocketEventHandle, toggle_fake_events, \
set_fake_prefix, get_fake_prefix, delete_fake_prefix, wait_for_one_event
import msgq
import os
@@ -15,6 +15,7 @@ from openpilot.common.utils import MovingAverage
__all__ = (
"NO_TRAVERSAL_LIMIT",
"Context",
"FrequencyTracker",
"IpcError",
"MultiplePublishersError",
@@ -36,6 +37,7 @@ __all__ = (
"recv_one_or_none",
"recv_one_retry",
"recv_sock",
"reset_context",
"set_fake_prefix",
"sub_sock",
"toggle_fake_events",
@@ -51,14 +53,18 @@ def pub_sock(endpoint: str) -> PubSocket:
return msgq.pub_sock(endpoint, segment_size)
def sub_sock(endpoint: str, poller: Poller | None = None,
def sub_sock(endpoint: str, poller: Poller | None = None, addr: str = "127.0.0.1",
conflate: bool = False, timeout: int | None = None) -> SubSocket:
service = SERVICE_LIST.get(endpoint)
segment_size = service.queue_size if service else 0
return msgq.sub_sock(endpoint, poller=poller, conflate=conflate,
return msgq.sub_sock(endpoint, poller=poller, addr=addr, conflate=conflate,
timeout=timeout, segment_size=segment_size)
def reset_context():
msgq.context = Context()
def log_from_bytes(dat: bytes, struct: capnp.lib.capnp._StructModule = log.Event) -> capnp.lib.capnp._DynamicStructReader:
with struct.from_bytes(dat, traversal_limit_in_words=NO_TRAVERSAL_LIMIT) as msg:
return msg
@@ -175,7 +181,7 @@ class FrequencyTracker:
class SubMaster:
def __init__(self, services: list[str], poll: str | None = None,
ignore_alive: list[str] | None = None, ignore_avg_freq: list[str] | None = None,
ignore_valid: list[str] | None = None, frequency: float | None = None):
ignore_valid: list[str] | None = None, addr: str = "127.0.0.1", frequency: float | None = None):
self.frame = -1
self.services = services
self.seen = dict.fromkeys(services, False)
@@ -210,7 +216,7 @@ class SubMaster:
for s in services:
p = self.poller if s not in self.non_polled_services else None
self.sock[s] = sub_sock(s, poller=p, conflate=True)
self.sock[s] = sub_sock(s, poller=p, addr=addr, conflate=True)
try:
data = new_message(s)
+72
View File
@@ -0,0 +1,72 @@
#include <cassert>
#include "openpilot/cereal/messaging/msgq_to_zmq.h"
#include "openpilot/cereal/services.h"
#include "common/util.h"
ExitHandler do_exit;
static std::vector<std::string> get_services(const std::string &whitelist_str, bool zmq_to_msgq) {
std::vector<std::string> service_list;
for (const auto& it : services) {
std::string name = it.second.name;
bool in_whitelist = whitelist_str.find(name) != std::string::npos;
if (zmq_to_msgq && !in_whitelist) {
continue;
}
service_list.push_back(name);
}
return service_list;
}
void msgq_to_zmq(const std::vector<std::string> &endpoints, const std::string &ip) {
MsgqToZmq bridge;
bridge.run(endpoints, ip);
}
void zmq_to_msgq(const std::vector<std::string> &endpoints, const std::string &ip) {
auto poller = std::make_unique<BridgeZmqPoller>();
auto pub_context = std::make_unique<Context>();
auto sub_context = std::make_unique<BridgeZmqContext>();
std::map<BridgeZmqSubSocket *, PubSocket *> sub2pub;
for (auto endpoint : endpoints) {
auto pub_sock = new PubSocket();
auto sub_sock = new BridgeZmqSubSocket();
size_t queue_size = services.at(endpoint).queue_size;
pub_sock->connect(pub_context.get(), endpoint, true, queue_size);
sub_sock->connect(sub_context.get(), endpoint, ip, false);
poller->registerSocket(sub_sock);
sub2pub[sub_sock] = pub_sock;
}
while (!do_exit) {
for (auto sub_sock : poller->poll(100)) {
std::unique_ptr<Message> msg(sub_sock->receive(true));
if (msg) {
sub2pub[sub_sock]->sendMessage(msg.get());
}
}
}
// Clean up allocated sockets
for (auto &[sub_sock, pub_sock] : sub2pub) {
delete sub_sock;
delete pub_sock;
}
}
int main(int argc, char **argv) {
bool is_zmq_to_msgq = argc > 2;
std::string ip = is_zmq_to_msgq ? argv[1] : "127.0.0.1";
std::string whitelist_str = is_zmq_to_msgq ? std::string(argv[2]) : "";
std::vector<std::string> endpoints = get_services(whitelist_str, is_zmq_to_msgq);
if (is_zmq_to_msgq) {
zmq_to_msgq(endpoints, ip);
} else {
msgq_to_zmq(endpoints, ip);
}
return 0;
}
+170
View File
@@ -0,0 +1,170 @@
#include "openpilot/cereal/messaging/bridge_zmq.h"
#include <cassert>
#include <cstring>
#include <unistd.h>
static size_t fnv1a_hash(const std::string &str) {
const size_t fnv_prime = 0x100000001b3;
size_t hash_value = 0xcbf29ce484222325;
for (char c : str) {
hash_value ^= (unsigned char)c;
hash_value *= fnv_prime;
}
return hash_value;
}
// FIXME: This is a hack to get the port number from the socket name, might have collisions.
static int get_port(std::string endpoint) {
size_t hash_value = fnv1a_hash(endpoint);
int start_port = 8023;
int max_port = 65535;
return start_port + (hash_value % (max_port - start_port));
}
BridgeZmqContext::BridgeZmqContext() {
context = zmq_ctx_new();
}
BridgeZmqContext::~BridgeZmqContext() {
if (context != nullptr) {
zmq_ctx_term(context);
}
}
void BridgeZmqMessage::init(size_t sz) {
size = sz;
data = new char[size];
}
void BridgeZmqMessage::init(char *d, size_t sz) {
size = sz;
data = new char[size];
memcpy(data, d, size);
}
void BridgeZmqMessage::close() {
if (size > 0) {
delete[] data;
}
data = nullptr;
size = 0;
}
BridgeZmqMessage::~BridgeZmqMessage() {
close();
}
int BridgeZmqSubSocket::connect(BridgeZmqContext *context, std::string endpoint, std::string address, bool conflate, bool check_endpoint) {
sock = zmq_socket(context->getRawContext(), ZMQ_SUB);
if (sock == nullptr) {
return -1;
}
zmq_setsockopt(sock, ZMQ_SUBSCRIBE, "", 0);
if (conflate) {
int arg = 1;
zmq_setsockopt(sock, ZMQ_CONFLATE, &arg, sizeof(int));
}
int reconnect_ivl = 500;
zmq_setsockopt(sock, ZMQ_RECONNECT_IVL_MAX, &reconnect_ivl, sizeof(reconnect_ivl));
full_endpoint = "tcp://" + address + ":";
if (check_endpoint) {
full_endpoint += std::to_string(get_port(endpoint));
} else {
full_endpoint += endpoint;
}
return zmq_connect(sock, full_endpoint.c_str());
}
void BridgeZmqSubSocket::setTimeout(int timeout) {
zmq_setsockopt(sock, ZMQ_RCVTIMEO, &timeout, sizeof(int));
}
Message *BridgeZmqSubSocket::receive(bool non_blocking) {
zmq_msg_t msg;
assert(zmq_msg_init(&msg) == 0);
int flags = non_blocking ? ZMQ_DONTWAIT : 0;
int rc = zmq_msg_recv(&msg, sock, flags);
Message *ret = nullptr;
if (rc >= 0) {
ret = new BridgeZmqMessage;
ret->init((char *)zmq_msg_data(&msg), zmq_msg_size(&msg));
}
zmq_msg_close(&msg);
return ret;
}
BridgeZmqSubSocket::~BridgeZmqSubSocket() {
if (sock != nullptr) {
zmq_close(sock);
}
}
int BridgeZmqPubSocket::connect(BridgeZmqContext *context, std::string endpoint, bool check_endpoint) {
sock = zmq_socket(context->getRawContext(), ZMQ_PUB);
if (sock == nullptr) {
return -1;
}
full_endpoint = "tcp://*:";
if (check_endpoint) {
full_endpoint += std::to_string(get_port(endpoint));
} else {
full_endpoint += endpoint;
}
// ZMQ pub sockets cannot be shared between processes, so we need to ensure pid stays the same.
pid = getpid();
return zmq_bind(sock, full_endpoint.c_str());
}
int BridgeZmqPubSocket::sendMessage(Message *message) {
assert(pid == getpid());
return zmq_send(sock, message->getData(), message->getSize(), ZMQ_DONTWAIT);
}
int BridgeZmqPubSocket::send(char *data, size_t size) {
assert(pid == getpid());
return zmq_send(sock, data, size, ZMQ_DONTWAIT);
}
BridgeZmqPubSocket::~BridgeZmqPubSocket() {
if (sock != nullptr) {
zmq_close(sock);
}
}
void BridgeZmqPoller::registerSocket(BridgeZmqSubSocket *socket) {
assert(num_polls + 1 < (sizeof(polls) / sizeof(polls[0])));
polls[num_polls].socket = socket->getRawSocket();
polls[num_polls].events = ZMQ_POLLIN;
sockets.push_back(socket);
num_polls++;
}
std::vector<BridgeZmqSubSocket *> BridgeZmqPoller::poll(int timeout) {
std::vector<BridgeZmqSubSocket *> ret;
int rc = zmq_poll(polls, num_polls, timeout);
if (rc < 0) {
return ret;
}
for (size_t i = 0; i < num_polls; i++) {
if (polls[i].revents) {
ret.push_back(sockets[i]);
}
}
return ret;
}
+72
View File
@@ -0,0 +1,72 @@
#pragma once
#include <cstddef>
#include <string>
#include <vector>
#include <zmq.h>
#include "msgq/ipc.h"
class BridgeZmqContext {
public:
BridgeZmqContext();
void *getRawContext() { return context; }
~BridgeZmqContext();
private:
void *context = nullptr;
};
class BridgeZmqMessage : public Message {
public:
void init(size_t size);
void init(char *data, size_t size);
void close();
size_t getSize() { return size; }
char *getData() { return data; }
~BridgeZmqMessage();
private:
char *data = nullptr;
size_t size = 0;
};
class BridgeZmqSubSocket {
public:
int connect(BridgeZmqContext *context, std::string endpoint, std::string address, bool conflate = false, bool check_endpoint = true);
void setTimeout(int timeout);
Message *receive(bool non_blocking = false);
void *getRawSocket() { return sock; }
~BridgeZmqSubSocket();
private:
void *sock = nullptr;
std::string full_endpoint;
};
class BridgeZmqPubSocket {
public:
int connect(BridgeZmqContext *context, std::string endpoint, bool check_endpoint = true);
int sendMessage(Message *message);
int send(char *data, size_t size);
void *getRawSocket() { return sock; }
~BridgeZmqPubSocket();
private:
void *sock = nullptr;
std::string full_endpoint;
int pid = -1;
};
class BridgeZmqPoller {
public:
void registerSocket(BridgeZmqSubSocket *socket);
std::vector<BridgeZmqSubSocket *> poll(int timeout);
private:
static constexpr size_t MAX_BRIDGE_ZMQ_POLLERS = 128;
std::vector<BridgeZmqSubSocket *> sockets;
zmq_pollitem_t polls[MAX_BRIDGE_ZMQ_POLLERS] = {};
size_t num_polls = 0;
};
+1 -2
View File
@@ -15,7 +15,7 @@
class SubMaster {
public:
SubMaster(const std::vector<const char *> &service_list, const std::vector<const char *> &poll = {},
const std::vector<const char *> &ignore_alive = {});
const char *address = nullptr, const std::vector<const char *> &ignore_alive = {});
void update(int timeout = 1000);
void update_msgs(uint64_t current_time, const std::vector<std::pair<std::string, cereal::Event::Reader>> &messages);
inline bool allAlive(const std::vector<const char *> &service_list = {}) { return all_(service_list, false, true); }
@@ -77,7 +77,6 @@ public:
PubMaster(const std::vector<const char *> &service_list);
inline int send(const char *name, capnp::byte *data, size_t size) { return sockets_.at(name)->send((char *)data, size); }
int send(const char *name, MessageBuilder &msg);
inline bool all_readers_updated(const char *name) { return sockets_.at(name)->all_readers_updated(); }
~PubMaster();
private:
+146
View File
@@ -0,0 +1,146 @@
#include "openpilot/cereal/messaging/msgq_to_zmq.h"
#include <cassert>
#include "openpilot/cereal/services.h"
#include "common/util.h"
extern ExitHandler do_exit;
// Max messages to process per socket per poll
constexpr int MAX_MESSAGES_PER_SOCKET = 50;
static std::string recv_zmq_msg(void *sock) {
zmq_msg_t msg;
zmq_msg_init(&msg);
std::string ret;
if (zmq_msg_recv(&msg, sock, 0) > 0) {
ret.assign((char *)zmq_msg_data(&msg), zmq_msg_size(&msg));
}
zmq_msg_close(&msg);
return ret;
}
void MsgqToZmq::run(const std::vector<std::string> &endpoints, const std::string &ip) {
zmq_context = std::make_unique<BridgeZmqContext>();
msgq_context = std::make_unique<Context>();
// Create ZMQPubSockets for each endpoint
for (const auto &endpoint : endpoints) {
auto &socket_pair = socket_pairs.emplace_back();
socket_pair.endpoint = endpoint;
socket_pair.pub_sock = std::make_unique<BridgeZmqPubSocket>();
int ret = socket_pair.pub_sock->connect(zmq_context.get(), endpoint);
if (ret != 0) {
printf("Failed to create ZMQ publisher for [%s]: %s\n", endpoint.c_str(), zmq_strerror(zmq_errno()));
return;
}
}
// Start ZMQ monitoring thread to monitor socket events
std::thread thread(&MsgqToZmq::zmqMonitorThread, this);
// Main loop for processing messages
while (!do_exit) {
{
std::unique_lock lk(mutex);
cv.wait(lk, [this]() { return do_exit || !sub2pub.empty(); });
if (do_exit) break;
for (auto sub_sock : msgq_poller->poll(100)) {
// Process messages for each socket
BridgeZmqPubSocket *pub_sock = sub2pub.at(sub_sock);
for (int i = 0; i < MAX_MESSAGES_PER_SOCKET; ++i) {
auto msg = std::unique_ptr<Message>(sub_sock->receive(true));
if (!msg) break;
while (pub_sock->sendMessage(msg.get()) == -1) {
if (errno != EINTR) break;
}
}
}
}
util::sleep_for(1); // Give zmqMonitorThread a chance to acquire the mutex
}
thread.join();
}
void MsgqToZmq::zmqMonitorThread() {
std::vector<zmq_pollitem_t> pollitems;
// Set up ZMQ monitor for each pub socket
for (int i = 0; i < socket_pairs.size(); ++i) {
std::string addr = "inproc://op-bridge-monitor-" + std::to_string(i);
zmq_socket_monitor(socket_pairs[i].pub_sock->getRawSocket(), addr.c_str(), ZMQ_EVENT_ACCEPTED | ZMQ_EVENT_DISCONNECTED);
void *monitor_socket = zmq_socket(zmq_context->getRawContext(), ZMQ_PAIR);
zmq_connect(monitor_socket, addr.c_str());
pollitems.emplace_back(zmq_pollitem_t{.socket = monitor_socket, .events = ZMQ_POLLIN});
}
while (!do_exit) {
int ret = zmq_poll(pollitems.data(), pollitems.size(), 1000);
if (ret < 0) {
if (errno == EINTR) {
// Due to frequent EINTR signals from msgq, introduce a brief delay (200 ms)
// to reduce CPU usage during retry attempts.
util::sleep_for(200);
}
continue;
}
for (int i = 0; i < pollitems.size(); ++i) {
if (pollitems[i].revents & ZMQ_POLLIN) {
// First frame in message contains event number and value
std::string frame = recv_zmq_msg(pollitems[i].socket);
if (frame.empty()) continue;
uint16_t event_type = *(uint16_t *)(frame.data());
// Second frame in message contains event address
frame = recv_zmq_msg(pollitems[i].socket);
if (frame.empty()) continue;
std::unique_lock lk(mutex);
auto &pair = socket_pairs[i];
if (event_type & ZMQ_EVENT_ACCEPTED) {
printf("socket [%s] connected\n", pair.endpoint.c_str());
if (++pair.connected_clients == 1) {
// Create new MSGQ subscriber socket and map to ZMQ publisher
pair.sub_sock = std::make_unique<MSGQSubSocket>();
size_t queue_size = services.at(pair.endpoint).queue_size;
pair.sub_sock->connect(msgq_context.get(), pair.endpoint, "127.0.0.1", false, true, queue_size);
sub2pub[pair.sub_sock.get()] = pair.pub_sock.get();
registerSockets();
}
} else if (event_type & ZMQ_EVENT_DISCONNECTED) {
printf("socket [%s] disconnected\n", pair.endpoint.c_str());
if (pair.connected_clients == 0 || --pair.connected_clients == 0) {
// Remove MSGQ subscriber socket from mapping and reset it
sub2pub.erase(pair.sub_sock.get());
pair.sub_sock.reset(nullptr);
registerSockets();
}
}
cv.notify_one();
}
}
}
// Clean up monitor sockets
for (int i = 0; i < pollitems.size(); ++i) {
zmq_socket_monitor(socket_pairs[i].pub_sock->getRawSocket(), nullptr, 0);
zmq_close(pollitems[i].socket);
}
cv.notify_one();
}
void MsgqToZmq::registerSockets() {
msgq_poller = std::make_unique<MSGQPoller>();
for (const auto &socket_pair : socket_pairs) {
if (socket_pair.sub_sock) {
msgq_poller->registerSocket(socket_pair.sub_sock.get());
}
}
}
+36
View File
@@ -0,0 +1,36 @@
#pragma once
#include <condition_variable>
#include <map>
#include <memory>
#include <mutex>
#include <string>
#include <vector>
#include "msgq/impl_msgq.h"
#include "openpilot/cereal/messaging/bridge_zmq.h"
class MsgqToZmq {
public:
MsgqToZmq() {}
void run(const std::vector<std::string> &endpoints, const std::string &ip);
protected:
void registerSockets();
void zmqMonitorThread();
struct SocketPair {
std::string endpoint;
std::unique_ptr<BridgeZmqPubSocket> pub_sock;
std::unique_ptr<MSGQSubSocket> sub_sock;
int connected_clients = 0;
};
std::unique_ptr<Context> msgq_context;
std::unique_ptr<BridgeZmqContext> zmq_context;
std::mutex mutex;
std::condition_variable cv;
std::unique_ptr<MSGQPoller> msgq_poller;
std::map<SubSocket *, BridgeZmqPubSocket *> sub2pub;
std::vector<SocketPair> socket_pairs;
};
+20 -4
View File
@@ -1,6 +1,7 @@
#include <assert.h>
#include <stdlib.h>
#include <string>
#include <mutex>
#include "openpilot/cereal/services.h"
#include "openpilot/cereal/messaging/messaging.h"
@@ -14,6 +15,21 @@ static inline bool inList(const std::vector<const char *> &list, const char *val
return false;
}
class MessageContext {
public:
MessageContext() : ctx_(nullptr) {}
~MessageContext() { delete ctx_; }
inline Context *context() {
std::call_once(init_flag, [=]() { ctx_ = Context::create(); });
return ctx_;
}
private:
Context *ctx_;
std::once_flag init_flag;
};
MessageContext message_context;
struct SubMaster::SubMessage {
std::string name;
SubSocket *socket = nullptr;
@@ -28,13 +44,13 @@ struct SubMaster::SubMessage {
};
SubMaster::SubMaster(const std::vector<const char *> &service_list, const std::vector<const char *> &poll,
const std::vector<const char *> &ignore_alive) {
poller_ = new Poller();
const char *address, const std::vector<const char *> &ignore_alive) {
poller_ = Poller::create();
for (auto name : service_list) {
assert(services.count(std::string(name)) > 0);
service serv = services.at(std::string(name));
SubSocket *socket = SubSocket::create(name, true, serv.queue_size);
SubSocket *socket = SubSocket::create(message_context.context(), name, address ? address : "127.0.0.1", true, true, serv.queue_size);
assert(socket != 0);
bool is_polled = inList(poll, name) || poll.empty();
if (is_polled) poller_->registerSocket(socket);
@@ -172,7 +188,7 @@ PubMaster::PubMaster(const std::vector<const char *> &service_list) {
for (auto name : service_list) {
assert(services.count(name) > 0);
service serv = services.at(std::string(name));
PubSocket *socket = PubSocket::create(name, serv.queue_size);
PubSocket *socket = PubSocket::create(message_context.context(), name, true, serv.queue_size);
assert(socket);
sockets_[name] = socket;
}
+2 -2
View File
@@ -11,9 +11,9 @@ common_libs = [
_common = env.Library('common', common_libs, LIBS="json11")
Export('_common')
params_python = env.SharedLibrary('params_c', 'params_c.cc', LIBS=[_common, 'json11'])
params_python = env.SharedLibrary('params_c', 'params_c.cc', LIBS=[_common, 'zmq', 'json11'])
common_python = [params_python]
Export('common_python')
if GetOption('extras'):
env.Program('tests/test_swaglog', 'tests/test_swaglog.cc', LIBS=[_common, 'json11', 'pthread'])
env.Program('tests/test_swaglog', 'tests/test_swaglog.cc', LIBS=[_common, 'json11', 'zmq', 'pthread'])
-1
View File
@@ -3,7 +3,6 @@ from openpilot.common.api.comma_connect import API_HOST as API_HOST, CommaConnec
class Api:
def __init__(self, dongle_id):
self.dongle_id = dongle_id
self.service = CommaConnectApi(dongle_id)
def request(self, method, endpoint, **params):
-3
View File
@@ -137,7 +137,6 @@ class AtClient:
def send_raw(self, data: bytes) -> None:
self._ensure_serial()
assert self._serial is not None
self._serial.reset_input_buffer()
self._serial.write(data)
self._serial.flush()
@@ -157,11 +156,9 @@ class AtClient:
def _send(self, cmd: str) -> None:
if DEBUG:
print(f"SER >> {cmd}", file=sys.stderr)
assert self._serial is not None
self._serial.write((cmd + "\r").encode("ascii"))
def _expect(self) -> list[str]:
assert self._serial is not None
lines: list[str] = []
while True:
raw = self._serial.readline()
+3 -3
View File
@@ -13,7 +13,7 @@ import capnp
T = TypeVar("T")
_EDGE_SLOTS = 16
_MINIMAL_EXAMPLES = 1
_MINIMAL_EXAMPLES = 10
_INTEGER_RANGES = {
"int8": (-2**7, 2**7 - 1),
"int16": (-2**15, 2**15 - 1),
@@ -42,8 +42,8 @@ class Fuzzy:
draw_index = self._draw_index
self._draw_index += 1
# Start with one minimal example, then interleave systematic
# boundaries and random values at every draw site.
# Preserve the cheap minimal prefix Hypothesis produced, then interleave
# systematic boundaries and random values at every draw site.
if self.example_index < _MINIMAL_EXAMPLES:
return edges[0]
search_example = self.example_index - _MINIMAL_EXAMPLES
+1
View File
@@ -13,6 +13,7 @@ public:
static std::string get_name() { return ""; }
static cereal::InitData::DeviceType get_device_type() { return cereal::InitData::DeviceType::UNKNOWN; }
static std::string get_serial() { return "cccccc"; }
static std::map<std::string, std::string> get_init_logs(bool route_log = false) {
return {};
+3 -3
View File
@@ -69,6 +69,9 @@ class HardwareBase(ABC):
except Exception:
return default
def booted(self) -> bool:
return True
def reboot(self, reason=None):
print("REBOOT!")
@@ -112,9 +115,6 @@ class HardwareBase(ABC):
def get_network_metered(self, network_type) -> bool:
return network_type not in (NetworkType.none, NetworkType.wifi, NetworkType.ethernet)
def get_voltage(self):
return 0
def get_current_power_draw(self):
return 0
+18 -18
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,29 +56,29 @@
},
{
"name": "boot",
"url": "https://commadist.azureedge.net/agnosupdate/boot-2388598cda7c5c09a44b8f2683ff473d7ce8096a545a1c4ea2ff1cff65456c5a.img.xz",
"hash": "2388598cda7c5c09a44b8f2683ff473d7ce8096a545a1c4ea2ff1cff65456c5a",
"hash_raw": "2388598cda7c5c09a44b8f2683ff473d7ce8096a545a1c4ea2ff1cff65456c5a",
"size": 46897152,
"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": "3519123cc1ec417e56ed2bdd449094e6e6e38ecb610ea4452dd44d5bdce5604c"
"ondevice_hash": "43739cdc82df6616ecaa1360bfb36e0eaf92f53bdd6fbc033f30e2830e7452a4"
},
{
"name": "system",
"url": "https://commadist.azureedge.net/agnosupdate/system-ec939431c59751372e34d669fce1b08494b391019534b5d7f690b87991ea159e.img.xz",
"hash": "6042848e01cd245df7570fc96cff28c831b4d3713e4321ee38735cb4e4591593",
"hash_raw": "ec939431c59751372e34d669fce1b08494b391019534b5d7f690b87991ea159e",
"size": 2147483648,
"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": "b2fc71b9071ddb0664a7e3a837df8d57ee36a2befabd8f044eb8be8d73ee66b7",
"ondevice_hash": "17aec6e1a6570613cf795e2e23f743b946201202633306bdc30b935c805bc3fd",
"alt": {
"hash": "ec939431c59751372e34d669fce1b08494b391019534b5d7f690b87991ea159e",
"url": "https://commadist.azureedge.net/agnosupdate/system-ec939431c59751372e34d669fce1b08494b391019534b5d7f690b87991ea159e.img",
"size": 2147483648
"hash": "d2ee705bfb45ce9a7ca70840a3cf9563ef30946d3e26d0233d63d8a7439a3a93",
"url": "https://huggingface.co/sunnypilot/agnos/resolve/main/system-d2ee705bfb45ce9a7ca70840a3cf9563ef30946d3e26d0233d63d8a7439a3a93.img",
"size": 4718592000
}
}
]
@@ -1,6 +1,7 @@
#pragma once
#include <cassert>
#include <fstream>
#include <map>
#include <string>
#include <algorithm> // for std::clamp
@@ -28,6 +29,24 @@ public:
return it->second;
}
static std::string get_serial() {
static std::string serial("");
if (serial.empty()) {
std::ifstream stream("/proc/cmdline");
std::string cmdline;
std::getline(stream, cmdline);
auto start = cmdline.find("serialno=");
if (start == std::string::npos) {
serial = "cccccc";
} else {
auto end = cmdline.find(" ", start + 9);
serial = cmdline.substr(start + 9, end - start - 9);
}
}
return serial;
}
static void set_ir_power(int percent) {
auto device = get_device_type();
if (device == cereal::InitData::DeviceType::TIZI) {
+16 -23
View File
@@ -1,5 +1,4 @@
import configparser
import glob
import json
import os
import socket
@@ -29,25 +28,9 @@ def affine_irq(val, action):
print(f"No IRQs found for '{action}'")
return
# power save takes the big cores offline; their IRQs stay where the kernel moved them until the cores come back
# and the IRQs are affined again
online = Path(f"/sys/devices/system/cpu/cpu{val}/online")
if online.exists() and online.read_text().strip() == "0":
return
for i in irqs:
sudo_write(str(val), f"/proc/irq/{i}/smp_affinity_list")
_hwmon: dict[str, tuple[Path | None, float]] = {}
def hwmon(name: str) -> Path | None:
"""the hwmon device with this name, hwmon numbering depends on probe order. None until its driver has probed, or on
devices without it (the comma four has no INA231): the scan costs ~3 ms, so a miss is only scanned again after 10 s"""
path, scanned = _hwmon.get(name, (None, -10.))
if path is None and time.monotonic() - scanned >= 10.:
path = next((Path(p).parent for p in sorted(glob.glob("/sys/class/hwmon/hwmon*/name")) if Path(p).read_text().strip() == name), None)
_hwmon[name] = (path, time.monotonic())
return path
@lru_cache
def get_device_type():
# lru_cache and cache can cause memory leaks when used in classes
@@ -118,11 +101,11 @@ class HardwareComma(HardwareBase):
return self.get_cmdline()['androidboot.serialno']
def get_voltage(self):
with open(f"{hwmon('ina231')}/in1_input") as f:
with open("/sys/class/hwmon/hwmon1/in1_input") as f:
return int(f.read())
def get_current(self):
with open(f"{hwmon('ina231')}/curr1_input") as f:
with open("/sys/class/hwmon/hwmon1/curr1_input") as f:
return int(f.read())
def set_ir_power(self, percent: int):
@@ -265,7 +248,7 @@ class HardwareComma(HardwareBase):
return self.get_modem_state().get('temperatures', [])
def get_current_power_draw(self):
return (self.read_param_file(f"{hwmon('ina231')}/power1_input", int) / 1e6)
return (self.read_param_file("/sys/class/hwmon/hwmon1/power1_input", int) / 1e6)
def get_som_power_draw(self):
return (self.read_param_file("/sys/class/power_supply/bms/voltage_now", int) * self.read_param_file("/sys/class/power_supply/bms/current_now", int) / 1e12)
@@ -373,9 +356,12 @@ class HardwareComma(HardwareBase):
# *** IRQ config ***
# move these off the default core, and off the cores AGNOS keeps for everything but openpilot
affine_irq(2, "msm_vidc") # encoders
affine_irq(2, "i2c_geni") # sensors
# mask off big cluster from default affinity
sudo_write("f", "/proc/irq/default_smp_affinity")
# move these off the default core
affine_irq(1, "msm_vidc") # encoders
affine_irq(1, "i2c_geni") # sensors
# *** GPU config ***
# https://github.com/commaai/agnos-kernel-sdm845/blob/master/arch/arm64/boot/dts/qcom/sdm845-gpu.dtsi#L216
@@ -432,6 +418,13 @@ class HardwareComma(HardwareBase):
time.sleep(0.01)
gpio_set(GPIO.STM_BOOT0, False)
def booted(self):
# this normally boots within 8s, but on rare occasions takes 30+s
encoder_state = sudo_read("/sys/kernel/debug/msm_vidc/core0/info")
if "Core state: 0" in encoder_state and (time.monotonic() < 60*2):
return False
return True
if __name__ == "__main__":
t = HardwareComma()
t.initialize_hardware()
+632
View File
@@ -0,0 +1,632 @@
#!/usr/bin/env python3
import fcntl
import json
import logging
import os
import select
import signal
import string
import struct
import subprocess
import tempfile
import termios
import time
from contextlib import contextmanager
from ipaddress import IPv4Address, AddressValueError
from enum import Enum
from openpilot.common.esim.base import WEBBING_ICCID_PREFIX
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s.%(msecs)03d %(levelname)-7s modem: %(message)s",
datefmt="%H:%M:%S",
)
AT_PORT = "/dev/modem_at0"
PPP_PORT = "/dev/modem_at1"
STATE_PATH = "/dev/shm/modem"
AT_LOCK = "/dev/shm/modem.lock" # shared with LPA
AT_INIT = [
"ATE0", # disable command echo
"ATV1", # verbose result codes (CONNECT/BUSY/NO CARRIER, not numeric)
"AT+CMEE=1", # numeric +CME ERROR codes on failures (per 3GPP 27.007)
"ATX4", # extended result codes: busy + dial tone detection, line speed in CONNECT
"AT&C1", # DCD pin follows carrier state (V.250 default)
"AT+CREG=2", # registration URCs include location info
"AT+CGREG=2", # GPRS registration URCs include location info
]
CREG = {0: "not_registered", 1: "home", 2: "searching", 3: "denied", 4: "unknown", 5: "roaming"}
# 3GPP TS 27.007 +COPS <AcT> -> network type
NETWORK_TYPE = {0: "gsm", 1: "gsm", 3: "gsm", 8: "gsm",
2: "utran", 4: "utran", 5: "utran", 6: "utran",
7: "lte", 9: "lte", 10: "lte",
11: "nr", 12: "nr", 13: "nr"}
DIAL_CID = 1
PPPD_CMD = [
"sudo", "pppd", PPP_PORT, "460800", "noauth", "nodetach", "noipdefault", "usepeerdns",
"nodefaultroute", "connect",
"/usr/sbin/chat -v ABORT 'NO CARRIER' ABORT 'NO DIALTONE' ABORT 'BUSY' " +
f"ABORT 'NO ANSWER' ABORT 'ERROR' TIMEOUT 5 '' AT OK ATD*99***{DIAL_CID}# CONNECT ''",
"lcp-echo-interval", "30", "lcp-echo-failure", "4", "mtu", "1500", "mru", "1500",
"novj", "novjccomp", "ipcp-accept-local", "ipcp-accept-remote", "nomagic",
"user", '""', "password", '""',
]
INITIAL_STATE: dict[str, object] = {
"seconds_since_boot": 0,
"state": "INITIALIZING",
"connected": False, "ip_address": "",
"iccid": "", "mcc_mnc": "", "imei": "", "modem_version": "",
"signal_strength": 0, "signal_quality": 0,
"network_type": "unknown", "operator": "", "band": "", "channel": 0,
"registration": "unknown", "temperatures": [], "extra": "",
"tx_bytes": 0, "rx_bytes": 0,
}
@contextmanager
def _serial_port(port: str, baudrate: int):
fd = os.open(port, os.O_RDWR | os.O_NOCTTY)
try:
attrs = termios.tcgetattr(fd)
attrs[0] = 0
attrs[1] = 0
attrs[2] = termios.CLOCAL | termios.CREAD | termios.CS8
attrs[3] = 0
attrs[4] = attrs[5] = getattr(termios, f"B{baudrate}")
attrs[6][termios.VMIN] = 0
attrs[6][termios.VTIME] = 0
termios.tcsetattr(fd, termios.TCSANOW, attrs)
yield fd
finally:
os.close(fd)
def _read_line(fd: int, timeout: float) -> bytes:
data = bytearray()
deadline = time.monotonic() + timeout
while True:
readable, _, _ = select.select([fd], [], [], max(0.0, deadline - time.monotonic()))
if not readable:
return bytes(data)
byte = os.read(fd, 1)
if not byte:
return bytes(data)
data.extend(byte)
if byte == b"\n":
return bytes(data)
class State(Enum):
INITIALIZING = "INITIALIZING"
SEARCHING = "SEARCHING"
CONNECTING = "CONNECTING"
CONNECTED = "CONNECTED"
DISCONNECTING = "DISCONNECTING"
STATE_WAIT = 1.0 # seconds to wait after each state handler returns
class PPPSession:
"""Owns pppd lifecycle, fail tracking, and PPP routing."""
MAX_FAILS = 3
def __init__(self):
self._proc: subprocess.Popen | None = None
self._fails = 0
self._peer = ""
def start(self):
self._proc = subprocess.Popen(PPPD_CMD, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
self._peer = ""
logging.info(f"PPP dialing CID {DIAL_CID}")
def kill(self):
subprocess.run(["sudo", "killall", "-9", "pppd"], capture_output=True)
self._peer = ""
@staticmethod
def reset_data_port():
"""Drop DTR on PPP_PORT so the modem terminates any stuck PPP session."""
try:
with _serial_port(PPP_PORT, 460800) as fd:
dtr = struct.pack("I", termios.TIOCM_DTR)
fcntl.ioctl(fd, termios.TIOCMBIC, dtr)
time.sleep(0.2)
fcntl.ioctl(fd, termios.TIOCMBIS, dtr)
except Exception as e:
logging.warning(f"data port reset failed: {e}")
def has_exited(self) -> bool:
return self._proc is not None and self._proc.poll() is not None
def reset_fail_counter(self):
self._fails = 0
def record_fail(self) -> bool:
"""Bump fail counter; return True if at the give-up limit."""
self._fails += 1
return self._fails >= self.MAX_FAILS
@property
def fails(self) -> int:
return self._fails
def maybe_install_routes(self, ip: str, peer: str) -> bool:
"""Install routes if peer changed; kill the session on failure so the state machine reconnects."""
if not peer or peer == self._peer:
return False
try:
IPv4Address(ip)
IPv4Address(peer)
except AddressValueError:
logging.warning(f"refusing route install with non-IPv4 ip={ip!r} peer={peer!r}")
self.kill()
return False
self.cleanup_routes()
cmds = [
["sudo", "ip", "route", "add", "default", "via", peer, "dev", "ppp0", "metric", "1000"],
["sudo", "ip", "route", "add", "default", "via", peer, "dev", "ppp0", "table", "1000"],
["sudo", "ip", "rule", "add", "from", ip, "table", "1000"],
]
for cmd in cmds:
r = subprocess.run(cmd, capture_output=True, text=True)
if r.returncode != 0:
logging.warning(f"route install failed ({' '.join(cmd[1:])}): {r.stderr.strip()}")
self.cleanup_routes()
self.kill()
return False
logging.info(f"route set up for {ip} via {peer}")
self._peer = peer
return True
def maybe_install_dns(self, dns_servers: list[str]) -> bool:
"""Register DNS servers with systemd-resolved; kill the session on failure to force a retry."""
if not dns_servers:
return False
for cmd in (["sudo", "resolvectl", "dns", "ppp0", *dns_servers],
["sudo", "resolvectl", "default-route", "ppp0", "yes"]):
r = subprocess.run(cmd, capture_output=True, text=True)
if r.returncode != 0:
logging.warning(f"resolvectl failed ({' '.join(cmd[1:])}): {r.stderr.strip()}")
self.kill()
return False
logging.info(f"resolvectl: ppp0 DNS = {dns_servers}")
return True
@staticmethod
def cleanup_routes():
subprocess.run(["sudo", "ip", "route", "del", "default", "dev", "ppp0"], capture_output=True)
subprocess.run(["sudo", "ip", "route", "flush", "table", "1000"], capture_output=True)
# rules don't have a flush; delete until none remain
while subprocess.run(["sudo", "ip", "rule", "del", "table", "1000"], capture_output=True).returncode == 0:
pass
subprocess.run(["sudo", "resolvectl", "revert", "ppp0"], capture_output=True)
class Modem:
def __init__(self):
self._ppp = PPPSession()
self._sim_change = False
self._apn = "" # blank = network-provided via PCO
self._roaming_allowed = True
self.running = True
self.S = INITIAL_STATE.copy()
@staticmethod
def _read_param(key):
try:
with open(f"/data/params/d/{key}") as f:
return f.read().strip()
except FileNotFoundError:
return ""
@staticmethod
def _parse_reg(v: str) -> str:
try:
return CREG.get(int(v.split(",")[1].strip('"')), "unknown")
except (ValueError, IndexError):
return "unknown"
@staticmethod
def _has_modem_manager() -> bool:
return os.path.isfile("/lib/systemd/system/ModemManager.service")
def _is_roaming_allowed(self) -> bool:
if self.S["iccid"].startswith(WEBBING_ICCID_PREFIX):
return True
return self._read_param("GsmRoaming") == "1"
def _publish_state(self, **kwargs):
self.S.update(kwargs)
self.S["seconds_since_boot"] = time.monotonic()
with tempfile.NamedTemporaryFile(mode="w", dir="/dev/shm", delete=False) as f:
json.dump(self.S, f, indent=2)
os.chmod(f.name, 0o644)
os.replace(f.name, STATE_PATH)
def _at(self, cmd):
"""Send AT command, return response lines. [] on error or if LPA holds port."""
fd = os.open(AT_LOCK, os.O_CREAT | os.O_RDWR, 0o666)
try:
fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
except OSError:
os.close(fd)
return []
try:
with _serial_port(AT_PORT, 9600) as serial_fd:
termios.tcflush(serial_fd, termios.TCIFLUSH)
command = (cmd + "\r").encode()
while command:
command = command[os.write(serial_fd, command):]
lines = []
while True:
raw = _read_line(serial_fd, 5)
if not raw:
raise TimeoutError("AT timeout")
line = raw.decode(errors="ignore").strip()
if not line:
continue
if line == "OK":
break
if line == "ERROR" or line.startswith("+CME ERROR"):
raise RuntimeError(line)
lines.append(line)
return lines
except (RuntimeError, TimeoutError, OSError) as e:
logging.info(f"AT {cmd} failed: {e}")
return []
finally:
fcntl.flock(fd, fcntl.LOCK_UN)
os.close(fd)
def _atv(self, cmd, pfx):
for line in self._at(cmd):
if pfx in line and ":" in line:
return line.split(":", 1)[1].strip()
return None
def _init_at_channel(self) -> bool:
"""Run AT_INIT and confirm ATE0 took effect. Returns False if echo is still on."""
for c in AT_INIT:
self._at(c)
r = self._at("AT+CGMI")
return bool(r) and not r[0].startswith("AT")
def _configure_modem(self, modem_version: str):
if not modem_version.startswith("EG25"):
return
cmds = [
# clear initial EPS bearer APN (some carriers reject the default)
'AT+CGDCONT=0,"IP",""',
# SIM hot swap
'AT+QSIMDET=1,0',
'AT+QSIMSTAT=1',
# configure modem as data-centric
'AT+QNVW=5280,0,"0102000000000000"',
'AT+QNVFW="/nv/item_files/ims/IMS_enable",00',
'AT+QNVFW="/nv/item_files/modem/mmode/ue_usage_setting",01',
]
for c in cmds:
self._at(c)
def _do_initializing(self):
if not os.path.exists(AT_PORT):
return State.INITIALIZING
logging.info("port found, initializing")
self._ppp.kill()
self._ppp.cleanup_routes()
if not self._init_at_channel():
logging.warning("AT echo still on, retrying")
return State.INITIALIZING
identity = self._read_identity()
if not identity["iccid"] or not identity["imei"]:
logging.warning(f"identity read incomplete: {identity}, retrying")
return State.INITIALIZING
self._configure_modem(identity["modem_version"])
self.S.update(identity)
self._apn = self._read_param("GsmApn")
self._roaming_allowed = self._is_roaming_allowed()
# blank APN lets the carrier supply one via PCO
self._at(f'AT+CGDCONT={DIAL_CID},"IP","{self._apn}"')
logging.info(f"APN '{self._apn or '(network-provided)'}' written to CID {DIAL_CID}, roaming={'on' if self._roaming_allowed else 'off'}")
self._sim_change = False # clear since we just re-read identity with the new SIM
self._publish_state(**identity)
return State.SEARCHING
def _read_identity(self):
def first_line(cmd):
r = self._at(cmd)
return r[0].strip() if r else ""
imei = first_line("AT+CGSN")
if not (imei.isdigit() and 14 <= len(imei) <= 17): # 3GPP TS 23.003
imei = ""
iccid = (self._atv("AT+QCCID", "+QCCID:") or "").rstrip("F")
if not all(c in string.hexdigits for c in iccid):
iccid = ""
imsi = first_line("AT+CIMI")
mcc_mnc = imsi[:6] if imsi.isdigit() and len(imsi) >= 6 else ""
modem_version = first_line("AT+GMR")
logging.info(f"imei={imei} iccid={iccid} mcc_mnc={mcc_mnc} ver={modem_version}")
return {"imei": imei, "iccid": iccid, "mcc_mnc": mcc_mnc, "modem_version": modem_version}
def _do_searching(self):
new_roaming = self._is_roaming_allowed()
if new_roaming != self._roaming_allowed:
logging.info(f"roaming changed: {self._roaming_allowed} -> {new_roaming}")
self._roaming_allowed = new_roaming
v = self._atv("AT+CREG?", "+CREG:")
if not v:
return self._searching_idle()
reg = self._parse_reg(v)
greg = self._parse_reg(self._atv("AT+CGREG?", "+CGREG:") or "")
logging.debug(f"creg={reg} cgreg={greg} roaming_allowed={self._roaming_allowed}")
if reg == "roaming" and not self._roaming_allowed:
self._publish_state(registration=reg)
return State.SEARCHING
if reg in ("home", "roaming") and greg in ("home", "roaming"):
self._publish_state(registration=reg)
return State.CONNECTING
if reg != self.S.get("registration"):
self._publish_state(registration=reg)
return self._searching_idle()
def _searching_idle(self):
if self._sim_change or not os.path.exists(AT_PORT):
logging.info(f"-> reconnecting (sim_change={self._sim_change} port={os.path.exists(AT_PORT)})")
return State.DISCONNECTING
return State.SEARCHING
def _do_connecting(self):
logging.info("starting pppd")
self._ppp.reset_fail_counter()
self._sim_change = False
self._ppp.start()
return State.CONNECTED
def _handle_pppd_exit(self):
if self._sim_change or not os.path.exists(AT_PORT):
return State.DISCONNECTING
give_up = self._ppp.record_fail()
if give_up:
logging.warning(f"PPP fail {self._ppp.fails}/{self._ppp.MAX_FAILS}, reconnecting")
return State.DISCONNECTING
logging.warning(f"PPP fail {self._ppp.fails}/{self._ppp.MAX_FAILS}, retrying")
self._ppp.reset_data_port()
if not os.path.exists(AT_PORT):
return State.DISCONNECTING
self._ppp.start()
return State.CONNECTED
def _params_changed(self) -> bool:
new_apn = self._read_param("GsmApn")
if new_apn != self._apn:
logging.info(f"GsmApn changed: '{self._apn}' -> '{new_apn}'")
return True
new_roaming = self._is_roaming_allowed()
if new_roaming != self._roaming_allowed:
logging.info(f"roaming changed: {self._roaming_allowed} -> {new_roaming}")
return True
return False
def _check_iccid(self, state):
if state in (State.INITIALIZING, State.DISCONNECTING) or not self.S["iccid"]:
return
iccid = (self._atv("AT+QCCID", "+QCCID:") or "").rstrip("F")
if iccid and iccid != self.S["iccid"]:
logging.warning(f"iccid changed: {self.S['iccid']} -> {iccid}")
self._sim_change = True
def _do_connected(self):
if self._ppp.has_exited():
return self._handle_pppd_exit()
if self._sim_change or not os.path.exists(AT_PORT) or self._params_changed():
return State.DISCONNECTING
self._poll()
return State.CONNECTED
def _do_disconnecting(self):
logging.warning("reconnecting")
self._publish_state(**INITIAL_STATE)
self._ppp.kill()
self._ppp.cleanup_routes()
self._ppp.reset_data_port()
self._sim_change = False
return State.INITIALIZING
def _poll_signal(self) -> dict:
v = self._atv("AT+CSQ", "+CSQ:")
if not v:
return {}
try:
rssi = int(v.split(",")[0])
if rssi == 99:
return {}
return {"signal_strength": rssi, "signal_quality": min(100, int(rssi / 31 * 100))}
except (ValueError, IndexError):
return {}
def _poll_operator(self) -> dict:
v = self._atv("AT+COPS?", "+COPS:")
if not v:
return {}
p = v.split(",")
out: dict = {}
try:
if len(p) >= 3:
out["operator"] = p[2].strip('"')
if len(p) >= 4:
out["network_type"] = NETWORK_TYPE.get(int(p[3]), "unknown")
except (ValueError, IndexError):
pass
return out
def _poll_band(self) -> dict:
v = self._atv("AT+QNWINFO", "+QNWINFO:")
if not v:
return {}
info = v.replace('"', '').split(",")
try:
if len(info) >= 4:
return {"band": info[2], "channel": int(info[3])}
except ValueError:
pass
return {}
def _poll_extra(self) -> dict:
v = self._atv('AT+QENG="servingcell"', "+QENG:")
return {"extra": v.replace('"', '')} if v else {}
def _poll_temps(self) -> dict:
v = self._atv("AT+QTEMP", "+QTEMP:")
if not v:
return {}
try:
return {"temperatures": [t for t in (int(x) for x in v.split(",") if x.strip()) if t != 255]}
except (ValueError, IndexError):
return {}
def _poll_iface(self) -> dict:
try:
r = subprocess.run(["ip", "-4", "addr", "show", "ppp0"], capture_output=True, text=True, timeout=2)
ip, peer = "", ""
for line in r.stdout.splitlines():
# `inet 10.x.x.x peer 10.64.64.64/32 ...`
parts = line.strip().split()
if "inet" in parts:
i = parts.index("inet")
ip = parts[i + 1].split("/")[0]
if "peer" in parts:
peer = parts[parts.index("peer") + 1].split("/")[0]
break
if ip:
if self._ppp.maybe_install_routes(ip, peer):
self._ppp.maybe_install_dns(self._read_cellular_dns())
return {"ip_address": ip, "connected": True}
if self.S["connected"]:
return {"connected": False, "ip_address": ""}
except Exception:
pass
return {}
def _read_cellular_dns(self) -> list[str]:
v = self._atv(f"AT+CGCONTRDP={DIAL_CID}", "+CGCONTRDP:")
if not v:
return []
# +CGCONTRDP: <cid>,<bearer_id>,<apn>,<local_addr>,<gw_addr>,<dns_prim>,<dns_sec>,...
fields = [f.strip().strip('"') for f in v.split(",")]
dns_servers = []
for d in fields[5:7]:
try:
dns_servers.append(str(IPv4Address(d)))
except (AddressValueError, ValueError):
pass
if not dns_servers:
dns_servers = [
"8.8.8.8", # Google
"1.1.1.1", # Cloudflare
]
logging.warning(f"no cellular DNS servers reported by modem: {v!r}; using fallback {dns_servers}")
return dns_servers
def _poll_byte_counters(self) -> dict:
try:
with open("/sys/class/net/ppp0/statistics/tx_bytes") as f:
tx = int(f.read().strip())
with open("/sys/class/net/ppp0/statistics/rx_bytes") as f:
rx = int(f.read().strip())
except Exception:
return {}
return {"tx_bytes": tx, "rx_bytes": rx}
def _poll(self):
s: dict = {}
for fn in (self._poll_signal, self._poll_operator, self._poll_band,
self._poll_extra, self._poll_temps, self._poll_iface,
self._poll_byte_counters):
s.update(fn())
if s:
self._publish_state(**s)
def run(self):
logging.info("starting")
self._publish_state(state=State.INITIALIZING.value)
if self._has_modem_manager():
subprocess.run(["sudo", "systemctl", "mask", "--runtime", "ModemManager"], capture_output=True)
subprocess.run(["sudo", "systemctl", "stop", "ModemManager"], capture_output=True)
self._ppp.kill()
state = State.INITIALIZING
handlers = {
State.INITIALIZING: self._do_initializing,
State.SEARCHING: self._do_searching,
State.CONNECTING: self._do_connecting,
State.CONNECTED: self._do_connected,
State.DISCONNECTING: self._do_disconnecting,
}
while self.running:
try:
self._check_iccid(state)
prev = state
state = handlers[state]()
if state != prev:
self._publish_state(state=state.value)
logging.info(f"{prev.value} -> {state.value}")
except Exception:
logging.exception(f"error in {state.value}")
state = State.DISCONNECTING
time.sleep(STATE_WAIT)
def stop(self):
self.running = False
self._ppp.kill()
self._ppp.cleanup_routes()
try:
os.remove(STATE_PATH)
except FileNotFoundError:
pass
if self._has_modem_manager():
subprocess.run(["sudo", "systemctl", "unmask", "--runtime", "ModemManager"], capture_output=True)
subprocess.run(["sudo", "systemctl", "start", "ModemManager"], capture_output=True)
def main():
m = Modem()
def _sig(*_):
m.running = False
signal.signal(signal.SIGINT, _sig)
signal.signal(signal.SIGTERM, _sig)
m.run()
m.stop()
if __name__ == "__main__":
main()
@@ -7,11 +7,10 @@ from collections import deque
from openpilot.common.realtime import Ratekeeper
from openpilot.common.filter_simple import FirstOrderFilter
from openpilot.common.hardware.comma.hardware import hwmon
def read_power():
with open(f"{hwmon('ina231')}/power1_input") as f:
with open("/sys/bus/i2c/devices/0-0040/hwmon/hwmon1/power1_input") as f:
return int(f.read()) / 1e6
def sample_power(seconds=5) -> list[float]:
@@ -26,7 +26,7 @@ class TestAmplifier(OpenpilotTestCase):
def _check_for_i2c_errors(self, expected):
dmesg = subprocess.check_output("dmesg", shell=True, encoding='utf8')
i2c_lines = [l for l in dmesg.strip().splitlines() if 'a88000.i2c' in l]
i2c_lines = [l for l in dmesg.strip().splitlines() if 'i2c_geni a88000.i2c' in l]
i2c_str = '\n'.join(i2c_lines)
if not expected:
+2 -2
View File
@@ -1,3 +1,3 @@
version https://git-lfs.github.com/spec/v1
oid sha256:86d8e83be5e2c7a1e9a443a8bc0ddc706ea6c40a822f86aaf35fc09641082487
size 41289720
oid sha256:f92c0a9b41613e063b6a1cd086729f5555d9df6482249e171ed1e276272cad7d
size 24709520
+13 -1
View File
@@ -33,8 +33,12 @@ namespace Path {
return util::getenv("PARAMS_ROOT", Hardware::PC() ? (Path::comma_home() + "/params") : "/data/params");
}
inline std::string rsa_file() {
return Hardware::PC() ? Path::comma_home() + "/persist/comma/id_rsa" : "/persist/comma/id_rsa";
}
inline std::string swaglog_ipc() {
return "/tmp/logmessage" + Path::openpilot_prefix();
return "ipc:///tmp/logmessage" + Path::openpilot_prefix();
}
inline std::string download_cache_root() {
@@ -44,6 +48,14 @@ namespace Path {
return "/tmp/comma_download_cache" + Path::openpilot_prefix() + "/";
}
inline std::string shm_path() {
#ifdef __APPLE__
return"/tmp";
#else
return "/dev/shm";
#endif
}
inline std::string model_root() {
return Hardware::PC() ? Path::comma_home() + "/media/0/models" : "/data/media/0/models";
}
+1 -1
View File
@@ -33,7 +33,7 @@ class Paths:
@staticmethod
def swaglog_ipc() -> str:
return "/tmp/logmessage" + os.environ.get("OPENPILOT_PREFIX", "")
return "ipc:///tmp/logmessage" + os.environ.get("OPENPILOT_PREFIX", "")
@staticmethod
def download_cache_root() -> str:
-10
View File
@@ -7,7 +7,6 @@ CHESTNUT_ROM_USB_IDS = ((0x174C, 0x2464), (0x174C, 0x2463))
CHESTNUT_USB_PRODUCT = f"custom {CHESTNUT_FW_VERSION}-CLEAN"
USB_DEVICES_PATH = Path("/sys/bus/usb/devices")
TYPEC_CC_ORIENTATION_PATH = Path("/sys/class/power_supply/usb/typec_cc_orientation")
UDC_PATH = Path("/sys/class/udc")
PRIMARY_USB_CONTROLLER = "a600000.ssusb"
@@ -41,15 +40,6 @@ def cable_connected() -> bool:
return read_int(TYPEC_CC_ORIENTATION_PATH) != 0
def usb_host_connected() -> bool:
"""Whether a USB host, e.g. a PC with adb or the UP in CI, is on the USB-C port, also while it has suspended this device.
A chestnut is a USB device, so then it isn't on that port."""
try:
return any(read(p) not in (None, "not attached") for p in UDC_PATH.glob("*/state"))
except OSError:
return False
def usb_devices() -> list[Path]:
try:
devices = (d for d in USB_DEVICES_PATH.glob("*") if (d / "idVendor").exists())
+10
View File
@@ -3,6 +3,7 @@ import os
import sys
import copy
import json
import time
import uuid
import socket
import logging
@@ -12,6 +13,7 @@ from threading import local
from collections import OrderedDict
from contextlib import contextmanager
LOG_TIMESTAMPS = "LOG_TIMESTAMPS" in os.environ
def json_handler(obj):
if isinstance(obj, np.bool_):
@@ -167,6 +169,14 @@ class SwagLogger(logging.Logger):
else:
self.info(evt)
def timestamp(self, event_name):
if LOG_TIMESTAMPS:
t = time.monotonic()
tstp = NiceOrderedDict()
tstp['timestamp'] = NiceOrderedDict()
tstp['timestamp']["event"] = event_name
tstp['timestamp']["time"] = t*1e9
self.debug(tstp)
def findCaller(self, stack_info=False, stacklevel=1):
"""
+18 -7
View File
@@ -9,7 +9,7 @@ inline static std::unordered_map<std::string, ParamKeyAttributes> keys = {
{"AccessToken", {CLEAR_ON_MANAGER_START | DONT_LOG, STRING}},
{"AdbEnabled", {PERSISTENT | BACKUP, BOOL}},
{"AlwaysOnDM", {PERSISTENT | BACKUP, BOOL}},
{"AlwaysOnDMLock", {PERSISTENT, BOOL}},
{"ApiCache_Device", {PERSISTENT, STRING}},
{"ApiCache_FirehoseStats", {PERSISTENT, JSON}},
{"AssistNowToken", {PERSISTENT, STRING}},
{"AthenadPid", {PERSISTENT, INT}},
@@ -25,7 +25,7 @@ inline static std::unordered_map<std::string, ParamKeyAttributes> keys = {
{"CarParamsPersistent", {PERSISTENT, BYTES}},
{"CarParamsPrevRoute", {PERSISTENT, BYTES}},
{"CompletedTrainingVersion", {PERSISTENT, STRING, "0"}},
{"ControlsReady", {CLEAR_ON_MANAGER_START | CLEAR_ON_ONROAD_TRANSITION | CLEAR_ON_OFFROAD_TRANSITION, BOOL}},
{"ControlsReady", {CLEAR_ON_MANAGER_START | CLEAR_ON_ONROAD_TRANSITION, BOOL}},
{"CurrentBootlog", {PERSISTENT, STRING}},
{"CurrentRoute", {CLEAR_ON_MANAGER_START | CLEAR_ON_ONROAD_TRANSITION, STRING}},
{"DisableDriverCameraIR", {CLEAR_ON_MANAGER_START | CLEAR_ON_ONROAD_TRANSITION, BOOL}},
@@ -40,7 +40,7 @@ inline static std::unordered_map<std::string, ParamKeyAttributes> keys = {
{"DriverTooDistracted", {CLEAR_ON_MANAGER_START | CLEAR_ON_IGNITION_ON, BOOL}},
{"DriverLockoutCount", {CLEAR_ON_MANAGER_START | CLEAR_ON_IGNITION_ON, INT, "0"}},
{"AlphaLongitudinalEnabled", {PERSISTENT | DEVELOPMENT_ONLY | BACKUP, BOOL}},
{"FirmwareQueryDone", {CLEAR_ON_MANAGER_START | CLEAR_ON_ONROAD_TRANSITION | CLEAR_ON_OFFROAD_TRANSITION, BOOL}},
{"FirmwareQueryDone", {CLEAR_ON_MANAGER_START | CLEAR_ON_ONROAD_TRANSITION, BOOL}},
{"ForcePowerDown", {PERSISTENT, BOOL}},
{"GitBranch", {PERSISTENT, STRING}},
{"GitCommit", {PERSISTENT, STRING}},
@@ -87,8 +87,8 @@ inline static std::unordered_map<std::string, ParamKeyAttributes> keys = {
{"LongitudinalManeuverMode", {CLEAR_ON_MANAGER_START | CLEAR_ON_OFFROAD_TRANSITION, BOOL}},
{"LongitudinalPersonality", {PERSISTENT | BACKUP, INT, std::to_string(static_cast<int>(cereal::LongitudinalPersonality::STANDARD))}},
{"NetworkMetered", {PERSISTENT | BACKUP, BOOL}},
{"ObdMultiplexingChanged", {CLEAR_ON_MANAGER_START | CLEAR_ON_ONROAD_TRANSITION | CLEAR_ON_OFFROAD_TRANSITION, BOOL}},
{"ObdMultiplexingEnabled", {CLEAR_ON_MANAGER_START | CLEAR_ON_ONROAD_TRANSITION | CLEAR_ON_OFFROAD_TRANSITION, BOOL}},
{"ObdMultiplexingChanged", {CLEAR_ON_MANAGER_START | CLEAR_ON_ONROAD_TRANSITION, BOOL}},
{"ObdMultiplexingEnabled", {CLEAR_ON_MANAGER_START | CLEAR_ON_ONROAD_TRANSITION, BOOL}},
{"Offroad_CarUnrecognized", {CLEAR_ON_MANAGER_START | CLEAR_ON_ONROAD_TRANSITION, JSON}},
{"Offroad_ChestnutBranch", {CLEAR_ON_MANAGER_START, JSON}},
{"Offroad_ChestnutNotDetected", {CLEAR_ON_MANAGER_START | CLEAR_ON_ONROAD_TRANSITION, JSON}},
@@ -100,6 +100,7 @@ inline static std::unordered_map<std::string, ParamKeyAttributes> keys = {
{"Offroad_ConnectivityNeeded", {CLEAR_ON_MANAGER_START, JSON}},
{"Offroad_ConnectivityNeededPrompt", {CLEAR_ON_MANAGER_START, JSON}},
{"Offroad_ExcessiveActuation", {PERSISTENT, JSON}},
{"Offroad_NoFirmware", {CLEAR_ON_MANAGER_START | CLEAR_ON_ONROAD_TRANSITION, JSON}},
{"Offroad_Recalibration", {CLEAR_ON_MANAGER_START | CLEAR_ON_ONROAD_TRANSITION, JSON}},
{"Offroad_TemperatureTooHigh", {CLEAR_ON_MANAGER_START, JSON}},
{"Offroad_UnregisteredHardware", {CLEAR_ON_MANAGER_START, JSON}},
@@ -113,7 +114,6 @@ inline static std::unordered_map<std::string, ParamKeyAttributes> keys = {
{"RecordFront", {PERSISTENT | BACKUP, BOOL}},
{"RecordFrontLock", {PERSISTENT, BOOL}}, // for the internal fleet
{"SecOCKey", {PERSISTENT | DONT_LOG | BACKUP, STRING}},
{"Notifications", {PERSISTENT, JSON}},
{"ShowDebugInfo", {PERSISTENT, BOOL}},
{"RouteCount", {PERSISTENT, INT, "0"}},
{"SnoozeUpdate", {CLEAR_ON_MANAGER_START | CLEAR_ON_OFFROAD_TRANSITION, BOOL}},
@@ -149,12 +149,15 @@ inline static std::unordered_map<std::string, ParamKeyAttributes> keys = {
{"Version", {PERSISTENT, STRING}},
// --- sunnypilot params --- //
{"AccelBoostSP", {PERSISTENT | BACKUP, BOOL, "1"}},
{"ApiCache_DriveStats", {PERSISTENT, JSON}},
{"AutoLaneChangeBsmDelay", {PERSISTENT | BACKUP, BOOL, "0"}},
{"AutoLaneChangeTimer", {PERSISTENT | BACKUP, INT, "0"}},
{"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}},
@@ -168,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"}},
@@ -180,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}},
@@ -190,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"}},
@@ -231,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
@@ -238,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"}},
+7 -3
View File
@@ -4,7 +4,7 @@ import functools
import itertools
import numpy as np
import raylib_nb as rl
import pyray as rl
# (ec codewords per block, block count) for levels L, M, Q, H, versions 1-40
@@ -237,8 +237,12 @@ def make_texture(data: str, inverted: bool = False) -> rl.Texture:
gray = ((modules == inverted) * 255).astype(np.uint8)
img_array = np.dstack((gray, gray, gray, np.full_like(gray, 255)))
rl_image = rl.Image(img_array, img_array.shape[1], img_array.shape[0], 1,
rl.PixelFormat.PIXELFORMAT_UNCOMPRESSED_R8G8B8A8)
rl_image = rl.Image()
rl_image.data = rl.ffi.cast("void *", img_array.ctypes.data)
rl_image.width = img_array.shape[1]
rl_image.height = img_array.shape[0]
rl_image.mipmaps = 1
rl_image.format = rl.PixelFormat.PIXELFORMAT_UNCOMPRESSED_R8G8B8A8
return rl.load_texture_from_image(rl_image)
+3 -4
View File
@@ -17,7 +17,7 @@ class Spinner:
return self
def update(self, spinner_text: str):
if self.spinner_proc is not None and self.spinner_proc.stdin is not None:
if self.spinner_proc is not None:
self.spinner_proc.stdin.write(spinner_text.encode('utf8') + b"\n")
try:
self.spinner_proc.stdin.flush()
@@ -29,12 +29,11 @@ class Spinner:
def close(self):
if self.spinner_proc is not None:
self.spinner_proc.terminate() # lets it restore the display
self.spinner_proc.kill()
try:
self.spinner_proc.communicate(timeout=2.)
except subprocess.TimeoutExpired:
self.spinner_proc.kill()
print("WARNING: failed to stop spinner")
print("WARNING: failed to kill spinner")
self.spinner_proc = None
def __del__(self):
+58 -16
View File
@@ -5,13 +5,12 @@
#include "common/swaglog.h"
#include <cassert>
#include <limits>
#include <mutex>
#include <string>
#include <zmq.h>
#include <stdarg.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <unistd.h>
#include "json11/json11.hpp"
#include "common/version.h"
#include "common/hardware/hw.h"
@@ -21,11 +20,13 @@
class SwaglogState {
public:
SwaglogState() {
sock = socket(AF_UNIX, SOCK_DGRAM, 0);
int sndbuf = SWAGLOG_MAX_SIZE;
setsockopt(sock, SOL_SOCKET, SO_SNDBUF, &sndbuf, sizeof(sndbuf));
addr.sun_family = AF_UNIX;
strncpy(addr.sun_path, Path::swaglog_ipc().c_str(), sizeof(addr.sun_path) - 1);
zctx = zmq_ctx_new();
sock = zmq_socket(zctx, ZMQ_PUSH);
// Timeout on shutdown for messages to be received by the logging process
int timeout = 100;
zmq_setsockopt(sock, ZMQ_LINGER, &timeout, sizeof(timeout));
zmq_connect(sock, Path::swaglog_ipc().c_str());
// workaround for https://github.com/dropbox/json11/issues/38
setlocale(LC_NUMERIC, "C");
@@ -63,7 +64,8 @@ public:
}
~SwaglogState() {
close(sock);
zmq_close(sock);
zmq_ctx_destroy(zctx);
}
void log(int levelnum, const char* filename, int lineno, const char* func, const char* msg, const std::string& log_s) {
@@ -71,18 +73,21 @@ public:
if (levelnum >= print_level) {
printf("%s: %s\n", filename, msg);
}
// drop if logmessaged is busy, not running, or the message is too big
sendto(sock, log_s.data(), log_s.length(), MSG_DONTWAIT, (struct sockaddr*)&addr, sizeof(addr));
zmq_send(sock, log_s.data(), log_s.length(), ZMQ_NOBLOCK);
}
std::mutex lock;
int sock = -1;
struct sockaddr_un addr = {};
void* zctx = nullptr;
void* sock = nullptr;
int print_level;
json11::Json::object ctx_j;
};
static void cloudlog_common(int levelnum, const char* filename, int lineno, const char* func, char* msg_buf) {
bool LOG_TIMESTAMPS = getenv("LOG_TIMESTAMPS");
uint32_t NO_FRAME_ID = std::numeric_limits<uint32_t>::max();
static void cloudlog_common(int levelnum, const char* filename, int lineno, const char* func,
char* msg_buf, const json11::Json::object &msg_j={}) {
static SwaglogState s;
json11::Json::object log_j = json11::Json::object {
@@ -91,9 +96,13 @@ static void cloudlog_common(int levelnum, const char* filename, int lineno, cons
{"filename", filename},
{"lineno", lineno},
{"funcname", func},
{"created", seconds_since_epoch()},
{"msg", msg_buf},
{"created", seconds_since_epoch()}
};
if (msg_j.empty()) {
log_j["msg"] = msg_buf;
} else {
log_j["msg"] = msg_j;
}
std::string log_s;
log_s += (char)levelnum;
@@ -113,3 +122,36 @@ void cloudlog_e(int levelnum, const char* filename, int lineno, const char* func
if (ret <= 0 || !msg_buf) return;
cloudlog_common(levelnum, filename, lineno, func, msg_buf);
}
void cloudlog_t_common(int levelnum, const char* filename, int lineno, const char* func,
uint32_t frame_id, const char* fmt, va_list args) {
if (!LOG_TIMESTAMPS) return;
char* msg_buf = nullptr;
int ret = vasprintf(&msg_buf, fmt, args);
if (ret <= 0 || !msg_buf) return;
json11::Json::object tspt_j = json11::Json::object{
{"event", msg_buf},
{"time", std::to_string(nanos_since_boot())}
};
if (frame_id < NO_FRAME_ID) {
tspt_j["frame_id"] = std::to_string(frame_id);
}
tspt_j = json11::Json::object{{"timestamp", tspt_j}};
cloudlog_common(levelnum, filename, lineno, func, msg_buf, tspt_j);
}
void cloudlog_te(int levelnum, const char* filename, int lineno, const char* func,
const char* fmt, ...) {
va_list args;
va_start(args, fmt);
cloudlog_t_common(levelnum, filename, lineno, func, NO_FRAME_ID, fmt, args);
va_end(args);
}
void cloudlog_te(int levelnum, const char* filename, int lineno, const char* func,
uint32_t frame_id, const char* fmt, ...) {
va_list args;
va_start(args, fmt);
cloudlog_t_common(levelnum, filename, lineno, func, frame_id, fmt, args);
va_end(args);
}
+12 -1
View File
@@ -8,7 +8,6 @@
#define CLOUDLOG_ERROR 40
#define CLOUDLOG_CRITICAL 50
#define SWAGLOG_MAX_SIZE (4*1024*1024)
#ifdef __GNUC__
#define SWAG_LOG_CHECK_FMT(a, b) __attribute__ ((format (printf, a, b)))
@@ -19,12 +18,20 @@
void cloudlog_e(int levelnum, const char* filename, int lineno, const char* func,
const char* fmt, ...) SWAG_LOG_CHECK_FMT(5, 6);
void cloudlog_te(int levelnum, const char* filename, int lineno, const char* func,
const char* fmt, ...) SWAG_LOG_CHECK_FMT(5, 6);
void cloudlog_te(int levelnum, const char* filename, int lineno, const char* func,
uint32_t frame_id, const char* fmt, ...) SWAG_LOG_CHECK_FMT(6, 7);
#define cloudlog(lvl, fmt, ...) cloudlog_e(lvl, __FILE__, __LINE__, \
__func__, \
fmt, ## __VA_ARGS__)
#define cloudlog_t(lvl, ...) cloudlog_te(lvl, __FILE__, __LINE__, \
__func__, \
__VA_ARGS__)
#define cloudlog_rl(burst, millis, lvl, fmt, ...) \
@@ -57,9 +64,13 @@ void cloudlog_e(int levelnum, const char* filename, int lineno, const char* func
}
#define LOGT(...) cloudlog_t(CLOUDLOG_DEBUG, __VA_ARGS__)
#define LOGD(fmt, ...) cloudlog(CLOUDLOG_DEBUG, fmt, ## __VA_ARGS__)
#define LOG(fmt, ...) cloudlog(CLOUDLOG_INFO, fmt, ## __VA_ARGS__)
#define LOGW(fmt, ...) cloudlog(CLOUDLOG_WARNING, fmt, ## __VA_ARGS__)
#define LOGE(fmt, ...) cloudlog(CLOUDLOG_ERROR, fmt, ## __VA_ARGS__)
#define LOGD_100(fmt, ...) cloudlog_rl(2, 100, CLOUDLOG_DEBUG, fmt, ## __VA_ARGS__)
#define LOG_100(fmt, ...) cloudlog_rl(2, 100, CLOUDLOG_INFO, fmt, ## __VA_ARGS__)
#define LOGW_100(fmt, ...) cloudlog_rl(2, 100, CLOUDLOG_WARNING, fmt, ## __VA_ARGS__)
#define LOGE_100(fmt, ...) cloudlog_rl(2, 100, CLOUDLOG_ERROR, fmt, ## __VA_ARGS__)
+19 -13
View File
@@ -1,16 +1,16 @@
import logging
import os
import socket
import time
import warnings
from pathlib import Path
from logging.handlers import BaseRotatingHandler
import zmq
from openpilot.common.logging_extra import SwagLogger, SwagFormatter, SwagLogFileFormatter
from openpilot.common.hardware.hw import Paths
SWAGLOG_MAX_SIZE = 4*1024*1024
def get_file_handler():
Path(Paths.swaglog_root()).mkdir(parents=True, exist_ok=True)
base_filename = os.path.join(Paths.swaglog_root(), "swaglog")
@@ -49,7 +49,7 @@ class SwaglogRotatingFileHandler(BaseRotatingHandler):
return sorted(log_files, reverse=True)
def shouldRollover(self, record):
size_exceeded = self.max_bytes > 0 and self.stream is not None and self.stream.tell() >= self.max_bytes
size_exceeded = self.max_bytes > 0 and self.stream.tell() >= self.max_bytes
time_exceeded = self.interval > 0 and self.last_rollover + self.interval <= time.monotonic()
return size_exceeded or time_exceeded
@@ -69,6 +69,8 @@ class UnixDomainSocketHandler(logging.Handler):
logging.Handler.__init__(self)
self.setFormatter(formatter)
self.pid = None
self.zctx = None
self.sock = None
def __del__(self):
@@ -77,25 +79,29 @@ class UnixDomainSocketHandler(logging.Handler):
def close(self):
if self.sock is not None:
self.sock.close()
self.sock = None
if self.zctx is not None:
self.zctx.term()
def connect(self):
self.close()
self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)
self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, SWAGLOG_MAX_SIZE)
self.sock.setblocking(False)
self.zctx = zmq.Context()
self.sock = self.zctx.socket(zmq.PUSH)
self.sock.setsockopt(zmq.LINGER, 10)
self.sock.connect(Paths.swaglog_ipc())
self.pid = os.getpid()
def emit(self, record):
if os.getpid() != self.pid:
# TODO suppresses warning about forking proc with zmq socket, fix root cause
warnings.filterwarnings("ignore", category=ResourceWarning, message="unclosed.*<zmq.*>")
self.connect()
msg = self.format(record).rstrip('\n')
assert self.sock is not None
# print("SEND".format(repr(msg)))
try:
self.sock.sendto((chr(record.levelno)+msg).encode('utf8'), Paths.swaglog_ipc())
except OSError:
# logmessaged is busy, not running, or the message is too big. drop :/
s = chr(record.levelno)+msg
self.sock.send(s.encode('utf8'), zmq.NOBLOCK)
except zmq.error.Again:
# drop :/
pass
-2
View File
@@ -4,7 +4,6 @@ import inspect
import os
import subprocess
import unittest
from collections.abc import Callable
from unittest import mock
from openpilot.common.hardware import HARDWARE, COMMA_HARDWARE
@@ -27,7 +26,6 @@ class OpenpilotTestCase(unittest.TestCase):
COMMA_HARDWARE_TEST = False
SHARED_DOWNLOAD_CACHE = False
openpilot_setup_method: Callable[[], None] # a subclass's setup_method, moved here by __init_subclass__
def __init_subclass__(cls, **kwargs):
super().__init_subclass__(**kwargs)
+64 -18
View File
@@ -1,11 +1,7 @@
#include <cstdlib>
#include <cstring>
#include <string>
#include <sys/socket.h>
#include <sys/time.h>
#include <sys/un.h>
#include <unistd.h>
#include <zmq.h>
#include "common/hardware/hw.h"
#include "common/swaglog.h"
@@ -14,25 +10,27 @@
#include "sunnypilot/common/version.h"
std::string daemon_name = "testy";
std::string dongle_id = "test_dongle_id";
int LINE_NO = 0;
void test_swaglog() {
setenv("MANAGER_DAEMON", "swaglog_test", 1);
setenv("DONGLE_ID", "test_dongle_id", 1);
setenv("CLEAN", "1", 1);
const std::string path = Path::swaglog_ipc();
unlink(path.c_str());
int sock = socket(AF_UNIX, SOCK_DGRAM, 0);
CHECK(sock >= 0);
struct timeval timeout = {.tv_sec = 5, .tv_usec = 0};
CHECK(setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(timeout)) == 0);
struct sockaddr_un addr = {.sun_family = AF_UNIX};
strncpy(addr.sun_path, path.c_str(), sizeof(addr.sun_path) - 1);
CHECK(bind(sock, (struct sockaddr*)&addr, sizeof(addr)) == 0);
void *context = zmq_ctx_new();
CHECK(context != nullptr);
void *socket = zmq_socket(context, ZMQ_PULL);
CHECK(socket != nullptr);
int timeout = 5000;
CHECK(zmq_setsockopt(socket, ZMQ_RCVTIMEO, &timeout, sizeof(timeout)) == 0);
CHECK(zmq_bind(socket, Path::swaglog_ipc().c_str()) == 0);
LOGD("native-cpp-log");
char buffer[4096] = {};
const int size = recv(sock, buffer, sizeof(buffer), 0);
const int size = zmq_recv(socket, buffer, sizeof(buffer), 0);
CHECK(size > 1);
CHECK(buffer[0] == CLOUDLOG_DEBUG);
std::string error;
@@ -45,10 +43,58 @@ void test_swaglog() {
CHECK(message["ctx"]["daemon"].string_value() == "swaglog_test");
CHECK(message["ctx"]["dongle_id"].string_value() == "test_dongle_id");
CHECK(message["ctx"]["dirty"].bool_value() == false);
CHECK(message["ctx"]["version"].string_value() == SUNNYPILOT_VERSION);
CHECK(close(sock) == 0);
CHECK(unlink(path.c_str()) == 0);
CHECK(zmq_close(socket) == 0);
CHECK(zmq_ctx_destroy(context) == 0);
}
void recv_log(int thread_cnt, int thread_msg_cnt) {
void *zctx = zmq_ctx_new();
void *sock = zmq_socket(zctx, ZMQ_PULL);
zmq_bind(sock, Path::swaglog_ipc().c_str());
std::vector<int> thread_msgs(thread_cnt);
int total_count = 0;
for (auto start = std::chrono::steady_clock::now(), now = start;
now < start + std::chrono::seconds{1} && total_count < (thread_cnt * thread_msg_cnt);
now = std::chrono::steady_clock::now()) {
char buf[4096] = {};
if (zmq_recv(sock, buf, sizeof(buf), ZMQ_DONTWAIT) <= 0) {
if (errno == EAGAIN || errno == EINTR || errno == EFSM) continue;
break;
}
CHECK(buf[0] == CLOUDLOG_DEBUG);
std::string err;
auto msg = json11::Json::parse(buf + 1, err);
CHECK(!msg.is_null());
CHECK(msg["levelnum"].int_value() == CLOUDLOG_DEBUG);
CHECK(msg["filename"].string_value().find("test_swaglog.cc") != std::string::npos);
CHECK(msg["funcname"].string_value() == "log_thread");
CHECK(msg["lineno"].int_value() == LINE_NO);
auto ctx = msg["ctx"];
CHECK(ctx["daemon"].string_value() == daemon_name);
CHECK(ctx["dongle_id"].string_value() == dongle_id);
CHECK(ctx["dirty"].bool_value() == true);
CHECK(ctx["version"].string_value() == SUNNYPILOT_VERSION);
std::string device = Hardware::get_name();
CHECK(ctx["device"].string_value() == device);
int thread_id = atoi(msg["msg"].string_value().c_str());
CHECK((thread_id >= 0 && thread_id < thread_cnt));
thread_msgs[thread_id]++;
total_count++;
}
for (int i = 0; i < thread_cnt; ++i) {
CHECK(thread_msgs[i] == thread_msg_cnt);
}
zmq_close(sock);
zmq_ctx_destroy(zctx);
}
int main() {
+13
View File
@@ -36,3 +36,16 @@ static inline double seconds_since_epoch() {
clock_gettime(CLOCK_REALTIME, &t);
return (double)t.tv_sec + t.tv_nsec * 1e-9;
}
// you probably should use nanos_since_boot instead
static inline uint64_t nanos_monotonic() {
struct timespec t;
clock_gettime(CLOCK_MONOTONIC, &t);
return t.tv_sec * 1000000000ULL + t.tv_nsec;
}
static inline uint64_t nanos_monotonic_raw() {
struct timespec t;
clock_gettime(CLOCK_MONOTONIC_RAW, &t);
return t.tv_sec * 1000000000ULL + t.tv_nsec;
}
+6
View File
@@ -235,6 +235,12 @@ std::string hexdump(const uint8_t* in, const size_t size) {
return ss.str();
}
int random_int(int min, int max) {
std::random_device dev;
std::mt19937 rng(dev());
std::uniform_int_distribution<std::mt19937::result_type> dist(min, max);
return dist(rng);
}
std::string random_string(std::string::size_type length) {
const std::string chrs = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
+1
View File
@@ -78,6 +78,7 @@ bool ends_with(const std::string &s, const std::string &suffix);
std::string strip(const std::string &str);
// ***** random helpers *****
int random_int(int min, int max);
std::string random_string(std::string::size_type length);
// **** file helpers *****
+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"
-51
View File
@@ -1,51 +0,0 @@
#!/usr/bin/env python3
# Builds emoji.npz from Noto Color Emoji's 72px PNGs and region flags: uv run --with pillow build_emoji.py
import subprocess
import tempfile
import zipfile
from pathlib import Path
import numpy as np
from PIL import Image
NOTO_EMOJI = "https://github.com/googlefonts/noto-emoji.git"
COMMIT = "99701e07d3d1fe1bdbcdb14964547f0fd592966f"
OUT = Path(__file__).parent / "emoji.npz"
def main():
with tempfile.TemporaryDirectory() as tmp:
src = Path(tmp)
git = ["git", "-C", tmp]
subprocess.run(["git", "init", "-q", tmp], check=True)
subprocess.run([*git, "sparse-checkout", "set", "2D/png/72", "third_party/region-flags/png"], check=True)
subprocess.run([*git, "fetch", "-q", "--depth", "1", "--filter=blob:none", NOTO_EMOJI, COMMIT], check=True)
subprocess.run([*git, "checkout", "-q", "FETCH_HEAD"], check=True)
arrays: dict[str, np.ndarray] = {}
for f in sorted((src / "2D/png/72").glob("emoji_u*.png")):
key = f.stem.removeprefix("emoji_u")
codepoints = [int(c, 16) for c in key.split("_")]
# digits, # and * are always text, and only the default skin tone ships
if len(codepoints) == 1 and codepoints[0] < 0x2000 and codepoints[0] not in (0xA9, 0xAE):
continue
if any(0x1F3FB <= c <= 0x1F3FF for c in codepoints):
continue
arrays[key] = np.asarray(Image.open(f).convert("RGBA"))
# flags are pairs of regional indicators, one per letter of the country code
for f in sorted((src / "third_party/region-flags/png").glob("??.png")):
img = Image.open(f).convert("RGBA")
img = img.resize((72, max(1, round(72 * img.height / img.width))), Image.Resampling.LANCZOS)
arrays["_".join(f"{0x1F1E6 + ord(c) - ord('A'):x}" for c in f.stem)] = np.asarray(img)
# same layout as np.savez_compressed, which np.load reads one array at a time
with zipfile.ZipFile(OUT, "w", zipfile.ZIP_DEFLATED) as z:
for key, array in arrays.items():
with z.open(f"{key}.npy", "w") as f:
np.lib.format.write_array(f, array)
print(f"{len(arrays)} emoji, {OUT.stat().st_size / 1e6:.1f} MB")
if __name__ == "__main__":
main()
-3
View File
@@ -1,3 +0,0 @@
version https://git-lfs.github.com/spec/v1
oid sha256:af9b3abfec97714f2a79e066703a841c63d975596e21253f325db15da0ec4963
size 4325737
@@ -0,0 +1,3 @@
version https://git-lfs.github.com/spec/v1
oid sha256:254b7f753b70c964847b686f0f71af751f2f49beea6ede4aeb333fe06062a257
size 2289
@@ -0,0 +1,3 @@
version https://git-lfs.github.com/spec/v1
oid sha256:57c7ba72642b0350ee764c924586fa66ff94915be4aba1813797e67eb4b74376
size 33215
@@ -1,3 +1,3 @@
version https://git-lfs.github.com/spec/v1
oid sha256:11cb414145582a5738c038b09c61b6bbd60a7b3255c96664f4f69adda41b8252
size 312
oid sha256:71dc069bd3dc5b11ba8e1b52eb3a1025ee0ad8c82834f94b4b2269ec0d401920
size 237
@@ -0,0 +1,3 @@
version https://git-lfs.github.com/spec/v1
oid sha256:73a6fe02cf19105c0051a6664a424c1bf2ede364c6cf3791f235c86ffa203f39
size 10348
@@ -1,3 +1,3 @@
version https://git-lfs.github.com/spec/v1
oid sha256:fb3c2ea747e4aa7a1ad23df2776589886b1f89acb12dcd701469176607f9f82c
size 338
oid sha256:4f500f118dca3eedbd86fc6cc943ad8be67fe5d4f7b474d5b452cd757ad805c3
size 282
@@ -0,0 +1,3 @@
version https://git-lfs.github.com/spec/v1
oid sha256:8a49996f0ce069a048abe94ba9424de655dcff53745676ab35e045204af88a3c
size 12103
@@ -1,3 +1,3 @@
version https://git-lfs.github.com/spec/v1
oid sha256:aa4ccc0d4d7f52a55772675f42bd53071a750d5dcefef2f9d4c8266b4959f2c5
size 371
oid sha256:8542374779f1908dc52c8a126bc041efea4c4d605afdd34e3bf8e520a7e78bf2
size 320
@@ -0,0 +1,3 @@
version https://git-lfs.github.com/spec/v1
oid sha256:21e656b387c1a7e8de54d3e1b1c246f442cffe3c5e0924273d6d6d897c00b568
size 13868
@@ -1,3 +0,0 @@
version https://git-lfs.github.com/spec/v1
oid sha256:53b616fcfaaa05d6d5ac405b3a5da70525ddf65fc70ed01cdcf8e13420936bd2
size 2460
@@ -0,0 +1,3 @@
version https://git-lfs.github.com/spec/v1
oid sha256:aeee7f049879caff52320fab5f286cf3fd6a52c820cd8e150ff242e53a14176f
size 14774
@@ -0,0 +1,3 @@
version https://git-lfs.github.com/spec/v1
oid sha256:0b59ddada9c9e0e7972ead27396ebe6c10fd2352687b18ff6b476f61f74d80bf
size 46106
@@ -0,0 +1,3 @@
version https://git-lfs.github.com/spec/v1
oid sha256:46d08a8a08b42d466ff45d8ad6d2578e345dcbb1c06c126ad361873d9d35eaec
size 12877
@@ -0,0 +1,3 @@
version https://git-lfs.github.com/spec/v1
oid sha256:42ea275e5fe0a8a0e2fddb5a4a8487806fb22850115ea3646ee8f213d5fd6bb6
size 37202
@@ -0,0 +1,3 @@
version https://git-lfs.github.com/spec/v1
oid sha256:cfbf38672a893fd1d8fadf942354d2511e2436814a9af0e5c188cbb427fc6c70
size 12281
@@ -0,0 +1,3 @@
version https://git-lfs.github.com/spec/v1
oid sha256:a7102850bcfb075a285041cecb546559374a905403ab3b9814fa6097d2d822dd
size 34680
@@ -0,0 +1,3 @@
version https://git-lfs.github.com/spec/v1
oid sha256:001cb8227eaaff5367055395d9b3ccd5822f9a47276091832d8ad28b074d77c9
size 914
@@ -0,0 +1,3 @@
version https://git-lfs.github.com/spec/v1
oid sha256:4c3d9082b295f9e5ddef93f8d4e9cb961ea2374c7affd26394bbccb26e7137b2
size 11023
@@ -0,0 +1,19 @@
import numpy as np
from scipy.io import wavfile
sr = 48000
max_int16 = 2**15 - 1
def harmonic_beep(freq, duration_seconds):
n_total = int(sr * duration_seconds)
signal = np.sin(2 * np.pi * freq * np.arange(n_total) / sr)
x = np.arange(n_total)
exp_scale = np.exp(-x/5.5e3)
return max_int16 * signal * exp_scale
engage_beep = harmonic_beep(1661.219, 0.5)
wavfile.write("engage.wav", sr, engage_beep.astype(np.int16))
disengage_beep = harmonic_beep(1318.51, 0.5)
wavfile.write("disengage.wav", sr, disengage_beep.astype(np.int16))
@@ -1,3 +0,0 @@
version https://git-lfs.github.com/spec/v1
oid sha256:02b6789e9c05eff8b02bd74a48cf2175d73720c85e91f4caf87d62fe8334acc8
size 1963310
@@ -1,3 +0,0 @@
version https://git-lfs.github.com/spec/v1
oid sha256:a13b28f8b94e06d28f7d0f9177f50057f8b053714a11814896eef0864c5b3f0a
size 1592395
@@ -1,3 +0,0 @@
version https://git-lfs.github.com/spec/v1
oid sha256:35a9280706245e5c1cf875cba1a10b5b550d3c119197e2e9ec98a165ecca6b25
size 587

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