From ef0d54ca6f445df2fbb27e4cb05a13b6b0804dc3 Mon Sep 17 00:00:00 2001 From: firestar5683 <168790843+firestar5683@users.noreply.github.com> Date: Fri, 25 Sep 2026 14:53:19 -0500 Subject: [PATCH] Ford Provide curvature and optional BluePilot angle controllers for supported Ford configurations, with per-Panda transport and native safety hooks. --- .../opendbc/bluepilot_lateral/CREDITS.md | 35 + .../opendbc/bluepilot_lateral/LICENSE | 7 + .../opendbc/bluepilot_lateral/LICENSE.md | 21 + .../bluepilot_lateral/ORIGIN_HISTORY.tsv | 38 + .../opendbc/bluepilot_lateral/README.md | 81 ++ .../opendbc/bluepilot_lateral/__init__.py | 34 + .../opendbc/bluepilot_lateral/can/__init__.py | 0 .../opendbc/bluepilot_lateral/can/ford.py | 37 + .../bluepilot_lateral/core/__init__.py | 0 .../opendbc/bluepilot_lateral/core/angle.py | 198 +++++ .../opendbc/bluepilot_lateral/core/trim.py | 104 +++ .../bluepilot_lateral/hosts/__init__.py | 0 .../bluepilot_lateral/hosts/starpilot.py | 101 +++ .../bluepilot_lateral/params/__init__.py | 0 .../bluepilot_lateral/params/generate.py | 41 + .../opendbc/bluepilot_lateral/params/limits.h | 20 + .../bluepilot_lateral/params/limits.py | 19 + .../bluepilot_lateral/params/manifest.json | 109 +++ .../bluepilot_lateral/params/protocol.h | 10 + .../bluepilot_lateral/params/protocol.json | 11 + .../bluepilot_lateral/params/protocol.py | 10 + .../opendbc/bluepilot_lateral/params/trim.py | 45 ++ .../bluepilot_lateral/safety/ford_bp.h | 236 ++++++ .../bluepilot_lateral/tests/__init__.py | 0 .../bluepilot_lateral/tests/reference.py | 101 +++ .../tests/reference/angle.py.txt | 577 +++++++++++++ .../tests/reference/bpdev_trim.py.txt | 203 +++++ .../tests/reference/builders.py.txt | 377 +++++++++ .../tests/reference/fordcan.py.txt | 342 ++++++++ .../tests/reference/human.py.txt | 71 ++ .../tests/reference/manifest.json | 37 + .../starpilot_curvature_controller.py.txt | 329 ++++++++ .../tests/reference/values.py.txt | 125 +++ .../tests/test_angle_core.py | 213 +++++ .../tests/test_angle_native.py | 307 +++++++ .../bluepilot_lateral/upstream-root-LICENSE | 7 + .../upstream-root-LICENSE.md | 21 + opendbc_repo/opendbc/car/ford/aol.py | 53 ++ .../opendbc/car/ford/carcontroller.py | 206 ++++- opendbc_repo/opendbc/car/ford/carstate.py | 97 ++- .../opendbc/car/ford/classic_lateral.py | 52 ++ .../opendbc/car/ford/curvature_preview.py | 14 + .../opendbc/car/ford/explorer_lateral.py | 92 +++ .../opendbc/car/ford/extended_classic_can.py | 25 + opendbc_repo/opendbc/car/ford/fingerprints.py | 57 ++ opendbc_repo/opendbc/car/ford/fordcan.py | 25 +- .../opendbc/car/ford/generic_canfd_can.py | 9 + .../opendbc/car/ford/generic_canfd_lateral.py | 47 ++ opendbc_repo/opendbc/car/ford/interface.py | 62 +- .../opendbc/car/ford/lateral_strategy.py | 757 ++++++++++++++++++ opendbc_repo/opendbc/car/ford/mache_can.py | 50 ++ .../opendbc/car/ford/mache_lateral.py | 147 ++++ opendbc_repo/opendbc/car/ford/manual_turn.py | 101 +++ .../opendbc/car/ford/new_port_curvature.py | 69 ++ .../opendbc/car/ford/radar_interface.py | 59 +- opendbc_repo/opendbc/car/ford/stock_cruise.py | 57 ++ .../tests/test_added_firmware_identity.py | 148 ++++ .../car/ford/tests/test_creep_compensation.py | 72 ++ .../car/ford/tests/test_curvature_preview.py | 69 ++ .../ford/tests/test_flag_source_identity.py | 54 ++ .../opendbc/car/ford/tests/test_ford.py | 3 +- .../car/ford/tests/test_mach_e_profile.py | 52 ++ .../car/ford/tests/test_manual_turn.py | 144 ++++ .../ford/tests/test_required_source_health.py | 96 +++ .../car/ford/tests/test_stock_cruise.py | 103 +++ .../car/ford/tests/test_three_ports.py | 195 +++++ opendbc_repo/opendbc/car/ford/values.py | 43 +- opendbc_repo/opendbc/car/fw_versions.py | 4 + opendbc_repo/opendbc/safety/modes/ford.h | 440 +++++++++- opendbc_repo/opendbc/safety/modes/ford_aol.h | 192 +++++ .../opendbc/safety/tests/test_ford_aol.py | 262 ++++++ .../tests/test_ford_explorer_extended.py | 102 +++ .../tests/test_ford_generic_canfd_extended.py | 89 ++ .../safety/tests/test_ford_mach_e_extended.py | 195 +++++ .../safety/tests/test_ford_stock_switch.py | 91 +++ .../opendbc/safety/tests/test_ford_three.py | 159 ++++ openpilot/starpilot/car/ford/aol.py | 74 ++ .../starpilot/car/ford/lateral_preferences.py | 19 + .../starpilot/ui/ford_lateral_feature.py | 61 ++ 79 files changed, 8448 insertions(+), 65 deletions(-) create mode 100644 opendbc_repo/opendbc/bluepilot_lateral/CREDITS.md create mode 100644 opendbc_repo/opendbc/bluepilot_lateral/LICENSE create mode 100644 opendbc_repo/opendbc/bluepilot_lateral/LICENSE.md create mode 100644 opendbc_repo/opendbc/bluepilot_lateral/ORIGIN_HISTORY.tsv create mode 100644 opendbc_repo/opendbc/bluepilot_lateral/README.md create mode 100644 opendbc_repo/opendbc/bluepilot_lateral/__init__.py create mode 100644 opendbc_repo/opendbc/bluepilot_lateral/can/__init__.py create mode 100644 opendbc_repo/opendbc/bluepilot_lateral/can/ford.py create mode 100644 opendbc_repo/opendbc/bluepilot_lateral/core/__init__.py create mode 100644 opendbc_repo/opendbc/bluepilot_lateral/core/angle.py create mode 100644 opendbc_repo/opendbc/bluepilot_lateral/core/trim.py create mode 100644 opendbc_repo/opendbc/bluepilot_lateral/hosts/__init__.py create mode 100644 opendbc_repo/opendbc/bluepilot_lateral/hosts/starpilot.py create mode 100644 opendbc_repo/opendbc/bluepilot_lateral/params/__init__.py create mode 100644 opendbc_repo/opendbc/bluepilot_lateral/params/generate.py create mode 100644 opendbc_repo/opendbc/bluepilot_lateral/params/limits.h create mode 100644 opendbc_repo/opendbc/bluepilot_lateral/params/limits.py create mode 100644 opendbc_repo/opendbc/bluepilot_lateral/params/manifest.json create mode 100644 opendbc_repo/opendbc/bluepilot_lateral/params/protocol.h create mode 100644 opendbc_repo/opendbc/bluepilot_lateral/params/protocol.json create mode 100644 opendbc_repo/opendbc/bluepilot_lateral/params/protocol.py create mode 100644 opendbc_repo/opendbc/bluepilot_lateral/params/trim.py create mode 100644 opendbc_repo/opendbc/bluepilot_lateral/safety/ford_bp.h create mode 100644 opendbc_repo/opendbc/bluepilot_lateral/tests/__init__.py create mode 100644 opendbc_repo/opendbc/bluepilot_lateral/tests/reference.py create mode 100644 opendbc_repo/opendbc/bluepilot_lateral/tests/reference/angle.py.txt create mode 100644 opendbc_repo/opendbc/bluepilot_lateral/tests/reference/bpdev_trim.py.txt create mode 100644 opendbc_repo/opendbc/bluepilot_lateral/tests/reference/builders.py.txt create mode 100644 opendbc_repo/opendbc/bluepilot_lateral/tests/reference/fordcan.py.txt create mode 100644 opendbc_repo/opendbc/bluepilot_lateral/tests/reference/human.py.txt create mode 100644 opendbc_repo/opendbc/bluepilot_lateral/tests/reference/manifest.json create mode 100644 opendbc_repo/opendbc/bluepilot_lateral/tests/reference/starpilot_curvature_controller.py.txt create mode 100644 opendbc_repo/opendbc/bluepilot_lateral/tests/reference/values.py.txt create mode 100644 opendbc_repo/opendbc/bluepilot_lateral/tests/test_angle_core.py create mode 100644 opendbc_repo/opendbc/bluepilot_lateral/tests/test_angle_native.py create mode 100644 opendbc_repo/opendbc/bluepilot_lateral/upstream-root-LICENSE create mode 100644 opendbc_repo/opendbc/bluepilot_lateral/upstream-root-LICENSE.md create mode 100644 opendbc_repo/opendbc/car/ford/aol.py create mode 100644 opendbc_repo/opendbc/car/ford/classic_lateral.py create mode 100644 opendbc_repo/opendbc/car/ford/curvature_preview.py create mode 100644 opendbc_repo/opendbc/car/ford/explorer_lateral.py create mode 100644 opendbc_repo/opendbc/car/ford/extended_classic_can.py create mode 100644 opendbc_repo/opendbc/car/ford/generic_canfd_can.py create mode 100644 opendbc_repo/opendbc/car/ford/generic_canfd_lateral.py create mode 100644 opendbc_repo/opendbc/car/ford/lateral_strategy.py create mode 100644 opendbc_repo/opendbc/car/ford/mache_can.py create mode 100644 opendbc_repo/opendbc/car/ford/mache_lateral.py create mode 100644 opendbc_repo/opendbc/car/ford/manual_turn.py create mode 100644 opendbc_repo/opendbc/car/ford/new_port_curvature.py create mode 100644 opendbc_repo/opendbc/car/ford/stock_cruise.py create mode 100644 opendbc_repo/opendbc/car/ford/tests/test_added_firmware_identity.py create mode 100644 opendbc_repo/opendbc/car/ford/tests/test_creep_compensation.py create mode 100644 opendbc_repo/opendbc/car/ford/tests/test_curvature_preview.py create mode 100644 opendbc_repo/opendbc/car/ford/tests/test_flag_source_identity.py create mode 100644 opendbc_repo/opendbc/car/ford/tests/test_mach_e_profile.py create mode 100644 opendbc_repo/opendbc/car/ford/tests/test_manual_turn.py create mode 100644 opendbc_repo/opendbc/car/ford/tests/test_required_source_health.py create mode 100644 opendbc_repo/opendbc/car/ford/tests/test_stock_cruise.py create mode 100644 opendbc_repo/opendbc/car/ford/tests/test_three_ports.py create mode 100644 opendbc_repo/opendbc/safety/modes/ford_aol.h create mode 100644 opendbc_repo/opendbc/safety/tests/test_ford_aol.py create mode 100644 opendbc_repo/opendbc/safety/tests/test_ford_explorer_extended.py create mode 100644 opendbc_repo/opendbc/safety/tests/test_ford_generic_canfd_extended.py create mode 100644 opendbc_repo/opendbc/safety/tests/test_ford_mach_e_extended.py create mode 100644 opendbc_repo/opendbc/safety/tests/test_ford_stock_switch.py create mode 100644 opendbc_repo/opendbc/safety/tests/test_ford_three.py create mode 100644 openpilot/starpilot/car/ford/aol.py create mode 100644 openpilot/starpilot/car/ford/lateral_preferences.py create mode 100644 openpilot/starpilot/ui/ford_lateral_feature.py diff --git a/opendbc_repo/opendbc/bluepilot_lateral/CREDITS.md b/opendbc_repo/opendbc/bluepilot_lateral/CREDITS.md new file mode 100644 index 0000000000..347892a413 --- /dev/null +++ b/opendbc_repo/opendbc/bluepilot_lateral/CREDITS.md @@ -0,0 +1,35 @@ +# BluePilot angle source + +Adapted from BluePilotDev/bluepilot bp-7.0 at +[e1d051d7ba270261b4455068bd68f1a58db15a4a](https://github.com/BluePilotDev/bluepilot/commit/e1d051d7ba270261b4455068bd68f1a58db15a4a), +principally Alan Polk, with John Christman, Jacob Neulight, Nathan Ingraham, +Praeuner, tonesto7, Haibin Wen and other BluePilot, sunnypilot and comma contributors. +Source paths: opendbc/sunnypilot/car/ford/lateral_angle_ext.py, +fordcan_ext.py, human_turn.py and opendbc/safety/modes/ford.h. +The simultaneous upstream LICENSE and LICENSE.md notices are retained. +This software is licensed under a custom license requiring permission for use. +This project uses software from Haibin Wen and SUNNYPILOT LLC and is licensed under a custom license requiring permission for use. + +This is a StarPilot adapter to the September 2026 proposed library shape. +It is not a released BluePilot library, tag, or claim of BluePilot validation. +The existing curvature controller remains StarPilot-owned. Pinion curvature, +curvature-primary settings and the unsafe native reset bypass are not imported. + +The exact upstream root notices are additionally retained as upstream-root-LICENSE +and upstream-root-LICENSE.md; LICENSE/ LICENSE.md retain the opendbc notices. +ORIGIN_HISTORY.tsv records the inspected path history with commit IDs/authors/dates. +The private compact upstream root clone preserves its reachable root history. +Pre-conversion opendbc submodule objects are not included in that root history. + +Angle lane-centering trim is separately adapted from BluePilot bp-dev +[e22afa6be9b881fa784c92ebb316db47728a3d81](https://github.com/BluePilotDev/bluepilot/commit/e22afa6be9b881fa784c92ebb316db47728a3d81), +`opendbc/sunnypilot/car/ford/lane_center_trim.py` (blob +`5eedebd79e99493624f9d6af0750d1dd5713306c`). Alan Polk authored the initial +trim, model-position fallback, correction slew and default-strength changes; +ghbarker contributed reference/NaN guards and tests. The source explicitly credits +StarPilot/u/jc01rho for curvature-domain placement/geometry. The core adaptation +adds immutable host projection and conservative stale/driver-pressure suppression. +The pinned bp-7.0 controller baseline and default-disabled policy are unchanged. +Both simultaneous root/opendbc MIT and Custom MIT notices also exist unchanged at +this trim revision; all retained notices and permission acknowledgments apply +without assigning an exclusive license or claiming a new permission grant. diff --git a/opendbc_repo/opendbc/bluepilot_lateral/LICENSE b/opendbc_repo/opendbc/bluepilot_lateral/LICENSE new file mode 100644 index 0000000000..f1fd199c63 --- /dev/null +++ b/opendbc_repo/opendbc/bluepilot_lateral/LICENSE @@ -0,0 +1,7 @@ +Copyright (c) 2020, Comma.ai, Inc. + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/opendbc_repo/opendbc/bluepilot_lateral/LICENSE.md b/opendbc_repo/opendbc/bluepilot_lateral/LICENSE.md new file mode 100644 index 0000000000..650b6f55b3 --- /dev/null +++ b/opendbc_repo/opendbc/bluepilot_lateral/LICENSE.md @@ -0,0 +1,21 @@ +# Custom MIT License + +Copyright (c) 2024, Haibin Wen, SUNNYPILOT LLC + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to view and modify the Software, subject to the following conditions: + +1. **Permission Required**: Permission Required for Commercial, For-Profit, or Closed Source Use: Use of the Software, in whole or in part, for any commercial purposes, for-profit projects, or in closed source projects requires explicit written permission from the original author(s). + +2. **Redistribution**: Any redistribution of the Software, modified or unmodified, must retain this license notice and the following acknowledgment: + "This software is licensed under a custom license requiring permission for use." + +3. **Visibility**: Any project that uses the Software must visibly mention the following acknowledgment: + "This project uses software from Haibin Wen and SUNNYPILOT LLC and is licensed under a custom license requiring permission for use." + +4. **No Warranty**: THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +Contact sunnypilot Support for permission requests. + +--- + +Haibin Wen, SUNNYPILOT LLC diff --git a/opendbc_repo/opendbc/bluepilot_lateral/ORIGIN_HISTORY.tsv b/opendbc_repo/opendbc/bluepilot_lateral/ORIGIN_HISTORY.tsv new file mode 100644 index 0000000000..55105a47d7 --- /dev/null +++ b/opendbc_repo/opendbc/bluepilot_lateral/ORIGIN_HISTORY.tsv @@ -0,0 +1,38 @@ +9d190417bf74563abfa6f36996f1e673e9ee0a1b Praeuner 2026-08-13T22:26:15-05:00 Update dampening factor to .25 +a881646ea5edc21c0db4c4e74076e0dc14671a4e alan-polk 2026-08-10T09:04:52-05:00 Merge pull request #176 from BluePilotDev/bp-no-stall +9012f76666a5c90764fcaec40832b9a607488c27 John Christman 2026-08-05T17:49:59-04:00 anti-stall +3610e3f18a0ad37d793d7ada61dbc739ab1077a3 Nathan Ingraham 2026-07-23T22:26:29-05:00 self.path_angle_gain_lowC_highV remains the platform-specific base gain. The toggle now controls separate self.user_dampening_factor. l ow_gain_calc uses: self.path_angle_gain_lowC_highV * self.user_dampening_factor UI placement, description, default, and 0.75–1.25 range remain unchanged. +1db52bc79e607ddb00214254dd4d732615e27fe4 Nathan Ingraham 2026-07-23T00:00:51-05:00 -Added “High Speed Dampening” directly below “High Speed Adjustment Factor”, range 0.75–1.25, step 0.01, and default 1.0. +5d994c24edf63f3b9004b2963f18ef4199e5d368 Jacob Neulight 2026-07-18T20:17:04-06:00 Ford safety: optional pinion-sourced angle_meas behind STEER_ANGLE_CURVATURE SP flag +699c17d9fde62c690eed9d68eed7d731744d5137 Jacob Neulight 2026-07-18T19:53:46-06:00 Ford: publish angle-mode shadow curvature from measured curvature during overrides +b7428fee4b116d4832f91c850d54cac2730de2ef alan-polk 2026-07-18T08:52:24-05:00 restore curvature safety checks to bp-6.0 logic. +97867c1eb57b7472f6fc3de62f0fef576e5a5497 alan-polk 2026-07-16T19:18:05-05:00 Human Turn Reset for Angle (#118) +7efee67e3e643d52b973895d6c6765c5cc12e314 alan-polk 2026-07-16T08:19:43-05:00 angle mode: rescale exit-detection threshold for 20Hz cadence +1958a3501ead10ae1f496f0d11e1e8cda6e2dbcc alan-polk 2026-07-14T15:22:38-05:00 Bp 7.0 variable cleanup (#111) +8f8d6d15f0a590f42b78de964ffb0d0af7f5d63d alan-polk 2026-07-14T08:53:28-05:00 Bp 7.0 panda2 (#109) +11ac3b760671b489ca449d522f1edf240a232884 alan-polk 2026-07-09T07:53:21-05:00 angle mode: fix ROC values tuned for 100Hz cadence running at actual 20Hz +dbdcea747e65f574d326a55c9bf1a9d6c9485e22 alan-polk 2026-07-08T09:21:32-05:00 Revert "ford: add current-curvature deviation check to angle mode (panda-side)" +69a9714563622729ba304ac75354ba3fd37b0b39 alan-polk 2026-07-08T09:17:09-05:00 ford: add current-curvature deviation check to angle mode (panda-side) +be7f86a5d0dc1ea3b3f0052d4b54ff0b8a70f843 John Christman 2026-07-06T21:53:55-04:00 cast on debug +5c1fbb07dd4d7d950a01cb2cd1faddd90d41e632 alan-polk 2026-07-06T14:20:49-05:00 controllerStateBP: add angleRateLimited + curvatureRateLimited diagnostics +06d654e5f48ea8fcffce6e98e48e3a30450b5097 alan-polk 2026-06-25T23:28:51-05:00 Revert "temp blend ratio change" — restore predicted-curvature blend to 0.50 +540e69fcf4861a2ce5d7ca41467effc231638e27 alan-polk 2026-06-22T08:35:44-05:00 temp blend ratio change +e3819c7e630d85cfb44858840124fe7f72f1762d alan-polk 2026-06-13T20:47:09-05:00 ford.h: don't block angle mode on the inactive curvature signal +5d343738e30267688d0ffa6eebe2ec3ca57b10ee alan-polk 2026-06-13T18:28:30-05:00 ford.h: widen path_angle ROC to 2% looser than lateral_angle_ext _soft_roc +d0aac605f99d37e9da205e419f7989c1e9eaa386 alan-polk 2026-06-13T11:15:50-05:00 BluePilot: add angle-primary lateral control mode +51d5de8991508c862e7c51333e5055425b2b8d23 alan-polk 2026-04-11T12:00:10-05:00 fixing missing punctation in ford.h +8194ceb7e0bbc112c73d393a8f0add3261f6592d alan-polk 2026-04-11T11:51:49-05:00 make safety limits symetrical but control limits asymetrical. Add 1.5s duration to detect human turn +db2bdff05df103d71df62f45c2a3cb5211aba6e6 alan-polk 2026-04-09T23:47:30-05:00 move all external logic to lateral_curv_ext.py. Apply some order of operations fixes to try and eleminate panda blocking messages. +1a8ac23b5bd5d7952c15eb913c2b1e39f14ad92e Blue Genie 2026-04-08T15:10:24-05:00 Adjust panda limits +892be076daf898d806983f847c72357accff7312 Blue Genie 2026-04-08T11:45:28-05:00 Add logging functionality +ce7d27230657159332f64a253a0faea6cf8dcc95 alan-polk 2026-04-08T11:40:02-05:00 fix rate of change limits +021b5146e80ac58fe2e81dbd848bc7cd409ef08e alan-polk 2026-04-07T16:24:38-05:00 align ford.h limits with dbc and carcontroller +7f9212f7f8dc22c4a0a22443158554f4d3652a3c tonesto7 2026-04-05T21:28:37-04:00 Merge bp-6.1 upstream changes into bp-6.0-dev (#124) +dd1a9d3fd8f60462d3d8ac6de3e7860e70e1f667 alan-polk 2025-12-12T12:22:31-06:00 convert opendbc from a submodule to a subfolder +10101012d8a4cc37951a557023824cdd995443a6 alan-polk 2026-08-10T17:23:04Z BluePilot: angle-mode lane centering trim (advanced lane positioning) +560e80e9d593badca08aa60e8ddb692e58033425 alan-polk 2026-08-11T12:50:00Z BluePilot: angle-mode lane centering falls back to model position, not zero +94bf8144d4a683e9f3408f3babf892878f3b81f4 ghbarker 2026-08-12T01:31:33Z ford ALP: restore StarPilot guards (narrow lane, laneline std, NaN params) and cap applied correction at 0.0015 +80825b81568ad684fe4ec37a797d3cbaa004fdcf ghbarker 2026-08-13T01:04:02Z split applied-correction ceiling into its own PR per review +e5b92cc48b34ea43ac756a96a96687c9851a188d ghbarker 2026-08-13T01:05:07Z add tests for the restored guards +af4bc410c9ef417ba723212ceaa2a77758dd8ecb alan-polk 2026-08-14T03:24:28Z BluePilot: rate-limit the lane centering correction, not just filter it +8eea9eb68e0c4126ee1c52f251e274d5865b6743 alan-polk 2026-08-19T13:33:00Z BluePilot: lower angle-mode lane centering default strength to 0.25 diff --git a/opendbc_repo/opendbc/bluepilot_lateral/README.md b/opendbc_repo/opendbc/bluepilot_lateral/README.md new file mode 100644 index 0000000000..69a561b84a --- /dev/null +++ b/opendbc_repo/opendbc/bluepilot_lateral/README.md @@ -0,0 +1,81 @@ +# BluePilot Ford angle control + +StarPilot adaptation of BluePilotDev/bluepilot `bp-7.0`, pinned to +[e1d051d7ba270261b4455068bd68f1a58db15a4a](https://github.com/BluePilotDev/bluepilot/commit/e1d051d7ba270261b4455068bd68f1a58db15a4a). +The layout follows Alan Polk's September 2026 library proposal. This is an +adaptation, not an upstream library release. + +Existing curvature control remains the default. Explicit `FordLateralMode=1` +selects angle control next drive; the saved choice persists when unavailable. +Only this selector is exposed. Fixed defaults and bounds live in +`params/manifest.json`; pinion-yaw correction and curvature-primary tuning are +outside this library. Angle lane-centering trim is available as a default-disabled +core capability, separately sourced from BluePilot bp-dev +`e22afa6be9b881fa784c92ebb316db47728a3d81`; it adds no public settings. + +`core/` accepts scalar/model inputs without openpilot, Params or messaging +imports. `can/` owns encoding, `safety/ford_bp.h` owns native enforcement, and +`hosts/starpilot.py` connects the host. `params/protocol.json` generates the wire +constants. The folder is vendored without submodules, LFS or an external runtime. + +## Admission + +Classic: Bronco Sport Mk1, Escape Mk4, Focus Mk4, Maverick Mk1, Explorer Mk6. +CAN FD: Escape Mk4.5, Expedition Mk4, F150 Mk14, F150 Lightning Mk1, Ranger Mk2, +Mustang Mach-E Mk1. + +Exact classic safety parameters 32/33 map to angle 128/129; CAN FD 18/19 and +66/67 map to 130/131. Parameter 131 requires DEBUG; RELEASE retains stock 130. +Longitudinal, radar, fingerprint and parser policy remain host-owned. Admission +uses the final CarParams contract, not brand or steering-control enum alone. + +AOL, alternative experiences, Transit, Edge, Mondeo, SecOC, passive, dashcam, +notCar and unsupported static flags are excluded. Auxiliary noOutput requires +parameter zero; production deployments with two Pandas remain unqualified until +actual startup, bus routing and public acknowledgments are verified. + +## Safety design + +The extension uses small Ford hooks without changing shared safety headers or +existing curvature namespaces. Active steering requires ordinary controls +permission, healthy physical RX and a fresh matching public Panda acknowledgment +of safety parameter, alternative experience, controls, RX validity, heartbeat and +faults. Cruise, gas/brake, checksum, counter, quality and freshness checks apply. +Neutral mode cannot grant permission. + +The BluePilot reset-bypass latch is omitted. Rejected frames preserve accepted +actuator history and withdraw the shadow lease; accepted neutral commands or +permission withdrawal reset history. Lost counters recover through neutral +resynchronization. Version or checksum failure cannot fall through to curvature +control. + +Active frames carry neutral curvature, offset and curvature rate, with checked +mode, ramp, precision, path angle, counter, checksum and cadence. Native enforcement +checks the shadow against the actual path across gains 0.95–1.3, bounds both by +`min(0.02, 2.4114/v²)`, and bounds the full actual-curvature interval against +measured curvature above 10 m/s. Actual path also obeys the 3.5886 m/s³ equivalent +jerk limit and rolling message-rate limit. Core quantization and timing margins +keep packed commands inside these bounds; an impossible intersection is neutral. + +The versioned 0x3CA announcement preserves StarPilot's existing byte 4 bit 1 +curvature flag and requires it clear in angle mode. It carries a counter, signed +shadow curvature, protocol version and checksum; its lease expires after 60 ms. +The shadow derives from the final path after rate limiting and saturation. + +Control computes at 20 Hz, announces through 33 Hz LKA, then sends the latest +announced result at 20 Hz, adding at most one steering tick. Permission withdrawal +sends neutral immediately. Human-turn recovery uses bounded neutral blips without +a native bypass. The retained Dom factory steering delay is 0.22 s; pinned +BluePilot uses 0.20 s. + +These stricter native limits and versioned metadata intentionally differ from +BluePilot 7.0. Identical bytes or safety decisions are not claimed for affected +commands. Runtime and physical ECU qualification remain pending. + +## Attribution and notices + +See `CREDITS.md`, `ORIGIN_HISTORY.tsv` and the project `THIRD_PARTY_NOTICES.md`. +Both upstream MIT and Custom MIT notices are retained verbatim in `LICENSE`, +`LICENSE.md`, `upstream-root-LICENSE` and `upstream-root-LICENSE.md`. The maintainer +reports author permission to use this adaptation under MIT. Both published notices +remain intact. diff --git a/opendbc_repo/opendbc/bluepilot_lateral/__init__.py b/opendbc_repo/opendbc/bluepilot_lateral/__init__.py new file mode 100644 index 0000000000..6ae503535a --- /dev/null +++ b/opendbc_repo/opendbc/bluepilot_lateral/__init__.py @@ -0,0 +1,34 @@ +"""Adapter to the proposed BluePilot library; angle only, exact source pinned.""" +from opendbc.bluepilot_lateral.can.ford import lateral, lka +from opendbc.bluepilot_lateral.core.angle import Command +from opendbc.bluepilot_lateral.hosts.starpilot import Host, qualified + + +class BluePilotLateral: + def __init__(self, CP, *, host=None): + if not qualified(CP): + raise ValueError("Angle mode is not configured") + self.host = host or Host(CP) + self.canfd = bool(CP.flags & 1) + self.pending = Command() + self.announced = Command() + self.announced_ns = 0 + self.lka_counter = 0 + self.apply_curvature_last = 0.0 + + def step_lateral(self, CC, CS, packer, CAN, frame, now_ns): + self.pending = self.host.update(CC, CS) + command = self.announced + # A pending permission withdrawal is immediate; an increase waits until + # the 33Hz side channel has announced the matching final actuator. + if not self.pending.active or not 0 < self.announced_ns <= now_ns <= self.announced_ns + 60_000_000: + command = Command() + self.announced = command + return [lateral(packer, CAN.main, command, canfd=self.canfd, counter=frame // 5)] + + def step_lka(self, packer, CAN, now_ns): + self.announced = self.pending + self.announced_ns = now_ns + message = lka(packer, CAN.main, self.announced.shadow_curvature, self.lka_counter) + self.lka_counter = (self.lka_counter + 1) % 8 + return [message] diff --git a/opendbc_repo/opendbc/bluepilot_lateral/can/__init__.py b/opendbc_repo/opendbc/bluepilot_lateral/can/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/opendbc_repo/opendbc/bluepilot_lateral/can/ford.py b/opendbc_repo/opendbc/bluepilot_lateral/can/ford.py new file mode 100644 index 0000000000..e12aa99c9d --- /dev/null +++ b/opendbc_repo/opendbc/bluepilot_lateral/can/ford.py @@ -0,0 +1,37 @@ +"""Ford angle codecs, adapted from BluePilot fordcan_ext.py at e1d051d7. + +Core commands use planner signs; path and shadow are negated on the wire. +The v1 side channel retains byte4 bit1 for StarPilot's curvature announcement. +""" +from opendbc.bluepilot_lateral.params import protocol as p + + +def checksum4(dat): + return (15 - (sum(dat[:7]) & 15)) & 15 + + +def lka(packer, bus, shadow, counter): + addr, original, _ = packer.make_can_msg("Lane_Assist_Data1", bus, {"LaRefAng_No_Req": 0., "LaCurvature_No_Calc": 0.}) + dat = bytearray(original) + raw = max(-20000, min(20000, round(-shadow / p.SHADOW_SCALE))) & 0xFFFF + dat[4] |= p.ANGLE_MASK | ((counter % p.COUNTER_MODULUS) << p.COUNTER_SHIFT) + dat[5], dat[6] = raw >> 8, raw & 255 + dat[7] = p.VERSION | (checksum4(dat) << p.CHECKSUM_SHIFT) + return addr, bytes(dat), bus + + +def lateral(packer, bus, command, *, canfd, counter): + values = {"HandsOffCnfm_B_Rq": 0, "LatCtlRampType_D_Rq": 2 if command.active else 0, + "LatCtlPrecision_D_Rq": command.precision, "LatCtlPathOffst_L_Actl": 0.0, + "LatCtlPath_An_Actl": -command.path_angle, "LatCtlCurv_No_Actl": 0.0} + if canfd: + values.update({"LatCtl_D2_Rq": int(command.active), "LatCtlCrv_NoRate2_Actl": 0.0, + "LatCtlPath_No_Cnt": counter % 16, "LatCtlPath_No_Cs": 0}) + dat = packer.make_can_msg("LateralMotionControl2", bus, values)[1] + fields = ((dat[2] << 3) | (dat[3] >> 5), (dat[6] << 3) | (dat[7] >> 5), + ((dat[3] & 31) << 6) | (dat[4] >> 2), ((dat[4] & 3) << 8) | dat[5]) + total = int(command.active) + counter % 16 + sum(v + (v >> 8) for v in fields) + values["LatCtlPath_No_Cs"] = 255 - (total & 255) + return packer.make_can_msg("LateralMotionControl2", bus, values) + values.update({"LatCtl_D_Rq": int(command.active), "LatCtlRng_L_Max": 0, "LatCtlCurv_NoRate_Actl": 0.0}) + return packer.make_can_msg("LateralMotionControl", bus, values) diff --git a/opendbc_repo/opendbc/bluepilot_lateral/core/__init__.py b/opendbc_repo/opendbc/bluepilot_lateral/core/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/opendbc_repo/opendbc/bluepilot_lateral/core/angle.py b/opendbc_repo/opendbc/bluepilot_lateral/core/angle.py new file mode 100644 index 0000000000..8d789921a9 --- /dev/null +++ b/opendbc_repo/opendbc/bluepilot_lateral/core/angle.py @@ -0,0 +1,198 @@ +"""Angle-primary Ford steering adapted from Alan Polk's BluePilot bp-7.0. + +Source e1d051d7ba270261b4455068bd68f1a58db15a4a lateral_angle_ext.py. +See ../LICENSE, ../LICENSE.md and ../CREDITS.md. This core has no vehicle, +openpilot, Params, messaging or model-constant imports. +""" +from dataclasses import dataclass +import math +from ..params import limits as bounds +from .trim import LaneCenterTrim, LaneGeometry, TrimConfig + + +def clip(value, low, high): + return max(low, min(high, value)) + + +def interp(value, xs, ys): + if value <= xs[0]: + return ys[0] + for i in range(1, len(xs)): + if value < xs[i]: + return ys[i - 1] + (ys[i] - ys[i - 1]) * (value - xs[i - 1]) / (xs[i] - xs[i - 1]) + return ys[-1] + + +@dataclass(frozen=True) +class Inputs: + active: bool + speed: float + measured_curvature: float + desired_curvature: float + steering_pressed: bool = False + steering_angle: float = 0.0 + yaw_predictions: tuple = () + time_indices: tuple = () + lateral_delay: float = 0.15 + lane_change: bool = False + lane_direction: int = 0 + limit_status: int = 0 + geometry: LaneGeometry | None = None + + +@dataclass(frozen=True) +class Command: + active: bool = False + path_angle: float = 0.0 + shadow_curvature: float = 0.0 + precision: int = 1 + + +class AngleController: + def __init__(self, *, low_gain=1.0, high_gain=1.15, trim_config=None): + self.trim_config = TrimConfig() if trim_config is None else trim_config + self.trim = LaneCenterTrim() + self.low_gain = low_gain + self.high_gain = high_gain + self.path_last = 0.0 + self.speed_last = 0.1 + self.desired_last = 0.0 + self.human_timer = 0.0 + self.press_last = False + self.preturned = False + self.press_timer = 0.0 + self.blip_frames = 0 + self.blip_cooldown = 0.0 + self.blip_hold = 0.0 + self.blip_count = 0 + + def reset(self): + self.trim.reset() + self.path_last = 0.0 + self.speed_last = 0.1 + self.desired_last = 0.0 + self.human_timer = 0.0 + self.press_last = False + self.preturned = False + self.press_timer = 0.0 + self.blip_frames = 0 + self.blip_cooldown = 0.0 + self.blip_hold = 0.0 + self.blip_count = 0 + + def step(self, i: Inputs) -> Command: + values = (i.speed, i.measured_curvature, i.desired_curvature, i.steering_angle, i.lateral_delay) + if not i.active or not all(math.isfinite(v) for v in values) or i.speed < 0.0: + self.reset() + return Command() + if i.steering_pressed and not self.press_last: + self.preturned = abs(i.steering_angle) > 45.0 + self.press_last = i.steering_pressed + self.human_timer = self.human_timer + 0.05 if i.steering_pressed and abs(i.steering_angle) > 45.0 else 0.0 + if self.human_timer + 1e-9 >= (3.0 if self.preturned else 1.5): + self.trim.reset() + self.path_last = 0.0 + self.desired_last = i.desired_curvature + self.blip_frames = self.blip_count = 0 + self.blip_hold = self.blip_cooldown = self.press_timer = 0.0 + return Command() + if i.steering_pressed: + self.press_timer += 0.05 + else: + if self.press_timer >= 0.5 and self.blip_cooldown <= 0.0 and self.blip_frames <= 0 and abs(self.path_last) < 0.1: + self.blip_frames = 6 + self.press_timer = 0.0 + if self.blip_frames > 0: + self.blip_frames -= 1 + self.trim.reset() + self.path_last = 0.0 + self.desired_last = i.desired_curvature + if self.blip_frames == 0: + self.blip_cooldown = 2.0 + return Command() + + base = clip(i.lateral_delay, 0.1, 0.15) + 0.05 + predictions_valid = (len(i.yaw_predictions) == len(i.time_indices) and len(i.time_indices) >= 17 and + all(math.isfinite(v) for v in (*i.yaw_predictions, *i.time_indices)) and + all(b > a for a, b in zip(i.time_indices, i.time_indices[1:], strict=False))) + curves = tuple(y / max(0.01, i.speed) for y in i.yaw_predictions) if predictions_valid else () + entering = bool(curves) and abs(interp(base, i.time_indices, curves)) > abs(i.desired_curvature) + factor = 1.0 if entering else interp(abs(i.desired_curvature), (0.005, 0.020), (1.0, 0.0)) + lookup = base + bounds.VLT_EXTRA * interp(i.speed, (11.176, 24.5872), (1.0, 0.0)) * factor + predicted = interp(lookup, i.time_indices, curves) if curves else i.desired_curvature + saturated = i.limit_status >= 2 or self.path_last >= 0.5235 * 0.9 or self.path_last <= -0.5 * 0.9 + falling = abs(i.desired_curvature) < abs(self.desired_last) - 0.010 + blend = bounds.BLEND * 0.25 if not entering and (i.limit_status >= 1 or saturated or falling) else bounds.BLEND + requested = predicted * blend + i.desired_curvature * (1.0 - blend) + self.desired_last = i.desired_curvature + precision = 0 if i.lane_change and ((i.lane_direction == 1 and requested < 0) or + (i.lane_direction == 2 and requested > 0)) else 1 + # BluePilot's default lane-change factors are both 1.0. + # Trim requested curvature before every existing actuator/safety limiter. + requested = self.trim.update(requested, i.speed, i.geometry, self.trim_config, + active=i.active, lane_change=i.lane_change, steering_pressed=i.steering_pressed) + kappa = clip(requested, i.measured_curvature - 0.002, i.measured_curvature + 0.002) if i.speed > 9.0 else requested + low = interp(i.speed, (13.5, 26.82), (1.0, self.low_gain)) + high = interp(i.speed, (13.5, 26.82), (1.3, self.high_gain)) + gain = interp(abs(kappa), (0.0007, 0.001), (low, high)) + path = kappa * i.speed * gain + if saturated: + last_mag, magnitude = abs(self.path_last), abs(path) + if magnitude > last_mag: + path = self.path_last + elif last_mag - magnitude > 0.02: + path = math.copysign(last_mag - 0.02, self.path_last) + elif i.limit_status >= 1: + path = clip(path, -abs(self.path_last), abs(self.path_last)) + roc = interp(i.speed, (10.0, 15.0, 25.0), (0.055, 0.0425, 0.009)) + path = clip(clip(path, -0.5235, 0.5), self.path_last - roc, self.path_last + roc) + + # Tightening relative to bp-7.0: the shadow describes the final actuator, + # including ROC/saturation. A truthful derived curvature must fit both the + # measured-curvature interval and the modern ISO envelope. If those bands + # cannot meet the previous actuator ROC, send a neutral mode-0 frame. + effective_speed = max(i.speed, 0.1) + cap = min(bounds.CURVATURE_MAX, bounds.LATERAL_ACCEL / max(i.speed, 1.0) ** 2) + low_kappa, high_kappa = -cap, cap + if i.speed > 9.0: + low_kappa = max(low_kappa, i.measured_curvature - 0.0018) + high_kappa = min(high_kappa, i.measured_curvature + 0.0018) + # Native cannot trust a host-selected feel gain. Intersect every admitted + # gain (0.95..1.3), so the worst equivalent curvature remains bounded. + lower_gain = bounds.GAIN_MAX if low_kappa >= 0.0 else bounds.GAIN_MIN + upper_gain = bounds.GAIN_MIN if high_kappa >= 0.0 else bounds.GAIN_MAX + lower = max(-bounds.PATH_MAX, low_kappa * effective_speed * lower_gain, self.path_last - roc) + upper = min(-bounds.PATH_MIN, high_kappa * effective_speed * upper_gain, self.path_last + roc) + # Bound the actual-angle equivalent derivative at the worst admitted gain. + # 45ms core margin remains inside the native elapsed-time/50ms cap. + jerk_delta = bounds.LATERAL_JERK / max(i.speed - 1.0, 1.0) ** 2 * bounds.CORE_STEER_PERIOD_S * bounds.GAIN_MIN * effective_speed + jerk_center = self.path_last / self.speed_last * effective_speed + lower = max(lower, jerk_center - jerk_delta) + upper = min(upper, jerk_center + jerk_delta) + lower += bounds.PATH_ROUNDING_MARGIN + upper -= bounds.PATH_ROUNDING_MARGIN + if lower > upper: + self.trim.reset() + self.path_last = 0.0 + return Command() + path = clip(path, lower, upper) + self.path_last = path + self.speed_last = effective_speed + shadow = path / (effective_speed * gain) + + self.blip_cooldown = max(0.0, self.blip_cooldown - 0.05) + gap = i.desired_curvature - i.measured_curvature + stalled = (not i.steering_pressed and not i.lane_change and i.speed > 9.0 and abs(gap) > 0.004 and + abs(i.desired_curvature) > abs(i.measured_curvature)) + if stalled: + if abs(kappa - requested) > 1e-9 and self.blip_cooldown <= 0.0: + self.blip_hold += 0.05 + if self.blip_hold >= 0.5 and self.blip_count < 3 and abs(path) < 0.1: + self.blip_frames = 6 + self.blip_hold = 0.0 + self.blip_count += 1 + else: + self.blip_hold = 0.0 + if i.steering_pressed or abs(gap) < 0.002: + self.blip_count = 0 + return Command(True, path, shadow, precision) diff --git a/opendbc_repo/opendbc/bluepilot_lateral/core/trim.py b/opendbc_repo/opendbc/bluepilot_lateral/core/trim.py new file mode 100644 index 0000000000..3d971982e6 --- /dev/null +++ b/opendbc_repo/opendbc/bluepilot_lateral/core/trim.py @@ -0,0 +1,104 @@ +"""Pure angle lane-centering trim adapted from BluePilot bp-dev e22afa6b. + +Alan Polk and ghbarker; the source also credits StarPilot/u/jc01rho. +See ../CREDITS.md, ../LICENSE and ../LICENSE.md. Geometry/confidence/fallback, +filter and slew follow lane_center_trim.py; this module receives immutable arrays +instead of a host model. Stale geometry and driver pressure additionally suppress +trim, and nonfinite confidence cannot create correction. +""" +from dataclasses import dataclass +import math +from ..params.trim import DEFAULTS, BOUNDS + + +def clip(value, low, high): + return max(low, min(high, value)) + + +def interp(value, xs, ys): + if value <= xs[0]: + return ys[0] + for index in range(1, len(xs)): + if value < xs[index]: + return ys[index - 1] + (ys[index] - ys[index - 1]) * (value - xs[index - 1]) / (xs[index] - xs[index - 1]) + return ys[-1] + + +@dataclass(frozen=True) +class TrimConfig: + enabled: bool = DEFAULTS["enabled"] + offset_m: float = DEFAULTS["offset_m"] + gain: float = DEFAULTS["gain"] + + +@dataclass(frozen=True) +class LaneGeometry: + position_x: tuple = () + position_y: tuple = () + left_x: tuple = () + left_y: tuple = () + right_x: tuple = () + right_y: tuple = () + probabilities: tuple = () + standard_deviations: tuple = () + fresh: bool = False + + +def sample(xs, ys, distance): + if (not isinstance(xs, tuple) or not isinstance(ys, tuple) or len(xs) < 2 or len(xs) != len(ys) or + not all(math.isfinite(v) for v in (*xs, *ys)) or not all(b > a for a, b in zip(xs, xs[1:], strict=False))): + return None + return interp(distance, xs, ys) + + +class LaneCenterTrim: + def __init__(self): + self.correction = 0.0 + + def reset(self): + self.correction = 0.0 + + def update(self, requested, speed, geometry, config, *, active, lane_change, steering_pressed=False): + try: + valid = (isinstance(config, TrimConfig) and config.enabled is True and active and not lane_change and + not steering_pressed and isinstance(geometry, LaneGeometry) and geometry.fresh is True and + math.isfinite(requested) and math.isfinite(speed) and speed >= 0.0 and + math.isfinite(config.offset_m) and BOUNDS["offset_m"][0] <= config.offset_m <= BOUNDS["offset_m"][1] and + math.isfinite(config.gain) and BOUNDS["gain"][0] <= config.gain <= BOUNDS["gain"][1]) + authority = interp(speed, BOUNDS["speed_mps"], BOUNDS["speed_authority"]) if valid else 0.0 + if not valid or authority <= 0.0: + self.reset() + return requested + distance = clip(speed, *BOUNDS["lookahead_m"]) + model_y = sample(geometry.position_x, geometry.position_y, distance) + if model_y is None: + self.reset() + return requested + # Bad lane-only geometry retains the source's model-position/offset fallback. + scale, center = self.lane_blend(geometry, distance) + error = scale * (center - model_y) + config.offset_m + raw = 2.0 * error / distance ** 2 + target = clip(raw, -BOUNDS["raw_correction"], BOUNDS["raw_correction"]) * config.gain * authority + alpha = 1.0 - math.exp(-BOUNDS["period_s"] / BOUNDS["tau_s"]) + filtered = alpha * target + (1.0 - alpha) * self.correction + self.correction = clip(filtered, self.correction - BOUNDS["correction_delta"], self.correction + BOUNDS["correction_delta"]) + return requested + self.correction + except (AttributeError, IndexError, TypeError, ValueError, OverflowError): + self.reset() + return requested + + def lane_blend(self, geometry, distance): + try: + left = sample(geometry.left_x, geometry.left_y, distance) + right = sample(geometry.right_x, geometry.right_y, distance) + probs, stds = geometry.probabilities, geometry.standard_deviations + if (left is None or right is None or not isinstance(probs, tuple) or not isinstance(stds, tuple) or + len(probs) != 2 or len(stds) != 2 or not all(math.isfinite(p) and 0.0 <= p <= 1.0 for p in probs) or + not all(math.isfinite(s) and s >= 0.0 for s in stds)): + return 0.0, 0.0 + confidence = min(*probs, interp(right - left, BOUNDS["width_m"], BOUNDS["width_tolerance"]), + interp(max(stds), BOUNDS["std"], BOUNDS["std_tolerance"])) + scale = clip(interp(confidence, BOUNDS["confidence"], (0.0, 1.0)), 0.0, 1.0) + return scale, 0.5 * (left + right) + except (AttributeError, IndexError, TypeError, ValueError, OverflowError): + return 0.0, 0.0 diff --git a/opendbc_repo/opendbc/bluepilot_lateral/hosts/__init__.py b/opendbc_repo/opendbc/bluepilot_lateral/hosts/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/opendbc_repo/opendbc/bluepilot_lateral/hosts/starpilot.py b/opendbc_repo/opendbc/bluepilot_lateral/hosts/starpilot.py new file mode 100644 index 0000000000..d32ed1e309 --- /dev/null +++ b/opendbc_repo/opendbc/bluepilot_lateral/hosts/starpilot.py @@ -0,0 +1,101 @@ +"""StarPilot's CP adapter; model transport and saved Params stay in the host. + +Only exact final CP words derived from the existing five classic/six CANFD +extended profiles can select angle. AOL and Transit keep their current owner. +""" +from opendbc.car import structs +from opendbc.car.ford.values import CAR, FordFlags +from opendbc.bluepilot_lateral.core.angle import AngleController, Inputs +from opendbc.bluepilot_lateral.core.trim import LaneGeometry +from opendbc.bluepilot_lateral.params import limits as bounds + +ANGLE_FLAG = 128 +CLASSIC = frozenset({CAR.FORD_BRONCO_SPORT_MK1, CAR.FORD_ESCAPE_MK4, CAR.FORD_FOCUS_MK4, + CAR.FORD_MAVERICK_MK1, CAR.FORD_EXPLORER_MK6}) +CANFD = frozenset({CAR.FORD_ESCAPE_MK4_5, CAR.FORD_EXPEDITION_MK4, CAR.FORD_F_150_MK14, + CAR.FORD_F_150_LIGHTNING_MK1, CAR.FORD_RANGER_MK2, CAR.FORD_MUSTANG_MACH_E_MK1}) +TRUCKS = CANFD - {CAR.FORD_ESCAPE_MK4_5, CAR.FORD_MUSTANG_MACH_E_MK1} + + +def mode_word(cp, *, selected): + if (cp.brand != "ford" or cp.passive or cp.dashcamOnly or cp.notCar or cp.alternativeExperience != 0 or + cp.steerControlType != structs.CarParams.SteerControlType.angle or + not cp.pcmCruise or len(cp.safetyConfigs) not in (1, 2)): + return None + if len(cp.safetyConfigs) == 2 and (cp.safetyConfigs[0].safetyModel != structs.CarParams.SafetyModel.noOutput or + cp.safetyConfigs[0].safetyParam != 0): + return None + fd = cp.carFingerprint in CANFD + if ((fd and (not cp.flags & FordFlags.CANFD or cp.flags & ~int(FordFlags.CANFD | FordFlags.HAS_BSM))) or + (not fd and (cp.carFingerprint not in CLASSIC or cp.flags & ~int(FordFlags.HAS_BSM)))): + return None + safety = cp.safetyConfigs[-1] + long = int(cp.openpilotLongitudinalControl) + original = (18 if cp.carFingerprint == CAR.FORD_MUSTANG_MACH_E_MK1 else 66) + long if fd else 32 + long + expected = ANGLE_FLAG + (2 if fd else 0) + long if selected else original + return expected if safety.safetyModel == structs.CarParams.SafetyModel.ford and safety.safetyParam == expected else None + + +def supported(cp): + return mode_word(cp, selected=False) is not None or mode_word(cp, selected=True) is not None + + +def qualified(cp): + return mode_word(cp, selected=True) is not None + + +def select(cp, raw): + # Absence/invalid bytes stay at current curvature. Never rewrite saved bytes. + chosen = (type(raw) is int and raw == 1) or (type(raw) in (bytes, str) and raw in (b"1", "1")) + if not chosen or mode_word(cp, selected=False) is None: + return False + cp.safetyConfigs[-1].safetyParam = ANGLE_FLAG + (2 if cp.flags & FordFlags.CANFD else 0) + int(cp.openpilotLongitudinalControl) + cp.steerActuatorDelay = 0.22 + return True + + +def model_geometry(model, *, fresh=False): + """Project a caller-qualified snapshot to immutable core arrays; no model imports.""" + if model is None or fresh is not True: + return None + try: + position_x, position_y = tuple(model.position.x), tuple(model.position.y) + except (AttributeError, TypeError, ValueError): + return None + try: + return LaneGeometry(position_x=position_x, position_y=position_y, fresh=True, left_x=tuple(model.laneLines[1].x), left_y=tuple(model.laneLines[1].y), + right_x=tuple(model.laneLines[2].x), right_y=tuple(model.laneLines[2].y), + probabilities=(model.laneLineProbs[1], model.laneLineProbs[2]), + standard_deviations=(model.laneLineStds[1], model.laneLineStds[2])) + except (AttributeError, IndexError, TypeError, ValueError): + return LaneGeometry(position_x=position_x, position_y=position_y, fresh=True) + + +class Host: + def __init__(self, cp): + if not qualified(cp): + raise ValueError("BluePilot angle requires an exact admitted Ford safety word") + low, high = (0.95, 0.95) if cp.carFingerprint in TRUCKS else ((1.0, 1.05) if cp.carFingerprint in CANFD else (1.0, 1.15)) + self.cp = cp + self.controller = AngleController(low_gain=low, high_gain=high) + self.inputs = None + + def update(self, CC, CS): + if self.inputs is not None: + self.inputs.update() + snapshot = self.inputs.lateral_snapshot(CS.out.vEgoRaw) if self.inputs is not None else None + model, times, delay, _ = snapshot if snapshot is not None else (None, (), 0.15, True) + ready = (self.inputs is not None and self.inputs.native_permission(self.cp, max_age_ns=bounds.PANDA_AGE_NS) and + CC.enabled and CC.latActive and CS.out.cruiseState.enabled and CS.out.canValid and + not CS.out.canTimeout and not CS.out.gasPressed and not CS.out.brakePressed and + not CS.out.steerFaultTemporary and not CS.out.steerFaultPermanent and not CS.out.vehicleSensorsInvalid) + meta = model.meta if model is not None else None + return self.controller.step(Inputs( + active=ready, speed=CS.out.vEgoRaw, measured_curvature=-CS.out.yawRate / max(CS.out.vEgoRaw, 0.1), + desired_curvature=CC.actuators.curvature, steering_pressed=CS.out.steeringPressed, + steering_angle=CS.out.steeringAngleDeg, yaw_predictions=tuple(model.orientationRate.z) if model is not None else (), + time_indices=tuple(times), lateral_delay=delay, + lane_change=int(getattr(meta.laneChangeState, "raw", meta.laneChangeState)) in (1, 2, 3) if meta else False, + lane_direction=int(getattr(meta.laneChangeDirection, "raw", meta.laneChangeDirection)) if meta else 0, + limit_status=getattr(CS, "lat_ctl_lim_stat", 0), + geometry=model_geometry(model, fresh=snapshot is not None))) diff --git a/opendbc_repo/opendbc/bluepilot_lateral/params/__init__.py b/opendbc_repo/opendbc/bluepilot_lateral/params/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/opendbc_repo/opendbc/bluepilot_lateral/params/generate.py b/opendbc_repo/opendbc/bluepilot_lateral/params/generate.py new file mode 100644 index 0000000000..50c6ed881e --- /dev/null +++ b/opendbc_repo/opendbc/bluepilot_lateral/params/generate.py @@ -0,0 +1,41 @@ +"""Generate protocol constants without loading a host or vehicle module.""" +import json +from pathlib import Path + +root = Path(__file__).parent +spec = json.loads((root / "protocol.json").read_text()) +(root / "protocol.py").write_text('"""Generated from protocol.json; layout preserves the existing curvature flag."""\n' + + "".join(f"{key.upper()} = {value!r}\n" for key, value in spec.items())) +(root / "protocol.h").write_text("#pragma once\n// Generated from protocol.json; do not allocate bit 1 to angle metadata.\n" + + "".join(f"#define FORD_BP_{key.upper()} {int(value)}U\n" for key, value in spec.items() if key != "shadow_scale")) + +manifest = json.loads((root / "manifest.json").read_text()) +defaults, bounds = manifest["defaults"], manifest["bounds"] +limits = {"BLEND": defaults["blend"], "VLT_EXTRA": defaults["vlt_extra_max"], + "PATH_MIN": bounds["path_angle_wire"][0], "PATH_MAX": bounds["path_angle_wire"][1], + "GAIN_MIN": bounds["gain"][0], "GAIN_MAX": bounds["gain"][1], + "CURVATURE_MAX": bounds["curvature"], "CURVATURE_ERROR": bounds["curvature_error"], + "LATERAL_ACCEL": bounds["lateral_accel"], "RX_AGE_US": bounds["rx_age_us"], + "SHADOW_AGE_US": bounds["shadow_age_us"], "PATH_ROUNDING_MARGIN": bounds["path_rounding_margin"], + "SHADOW_ROUNDING_MARGIN": bounds["shadow_rounding_margin"], "LATERAL_JERK": bounds["lateral_jerk"], + "RT_INTERVAL_US": bounds["rt_interval_us"], "STEER_PERIOD_US": bounds["steer_period_us"], + "CORE_STEER_PERIOD_S": bounds["core_steer_period_s"], "PANDA_AGE_NS": bounds["panda_age_ns"]} +(root / "limits.py").write_text('"""Generated from manifest.json; host and core use this manifest contract."""\n' + + "".join(f"{key} = {value!r}\n" for key, value in limits.items())) +(root / "limits.h").write_text("#pragma once\n// Generated from manifest.json; native and Python bounds share a source.\n" + + "".join(f"#define FORD_BP_{key} {str(value) + 'F' if isinstance(value, float) else str(value) + 'U'}\n" + for key, value in limits.items())) + +# Optional angle trim settings are Python-only; native safety limits stay unchanged. +trim = manifest["angle_lane_trim"] +types = {"enabled": "bool", "offset_m": "float", "gain": "float"} +defaults_fields = "".join(f" {key}: {types[key]}\n" for key in trim["defaults"]) +bounds_fields = "".join(f" {key}: {'list[float]' if isinstance(value, list) else 'float'}\n" for key, value in trim["bounds"].items()) +(root / "trim.py").write_text('"""Generated Python-only angle trim defaults; no native bound or registry changes."""\n' + + "from typing import TypedDict\n\n\n" + + "class TrimDefaults(TypedDict):\n" + defaults_fields + "\n\n" + + "class TrimBounds(TypedDict):\n" + bounds_fields + "\n\n" + + f"SOURCE_REVISION = {trim['source_revision']!r}\n" + + f"DEFAULTS: TrimDefaults = {trim['defaults']!r}\n" + + "BOUNDS: TrimBounds = {\n" + + "".join(f" {key!r}: {value!r},\n" for key, value in trim["bounds"].items()) + "}\n") diff --git a/opendbc_repo/opendbc/bluepilot_lateral/params/limits.h b/opendbc_repo/opendbc/bluepilot_lateral/params/limits.h new file mode 100644 index 0000000000..5442ec8264 --- /dev/null +++ b/opendbc_repo/opendbc/bluepilot_lateral/params/limits.h @@ -0,0 +1,20 @@ +#pragma once +// Generated from manifest.json; native and Python bounds share a source. +#define FORD_BP_BLEND 0.5F +#define FORD_BP_VLT_EXTRA 0.1F +#define FORD_BP_PATH_MIN -0.5F +#define FORD_BP_PATH_MAX 0.5235F +#define FORD_BP_GAIN_MIN 0.95F +#define FORD_BP_GAIN_MAX 1.3F +#define FORD_BP_CURVATURE_MAX 0.02F +#define FORD_BP_CURVATURE_ERROR 0.002F +#define FORD_BP_LATERAL_ACCEL 2.4114F +#define FORD_BP_RX_AGE_US 100000U +#define FORD_BP_SHADOW_AGE_US 60000U +#define FORD_BP_PATH_ROUNDING_MARGIN 0.0005F +#define FORD_BP_SHADOW_ROUNDING_MARGIN 1e-06F +#define FORD_BP_LATERAL_JERK 3.5886F +#define FORD_BP_RT_INTERVAL_US 250000U +#define FORD_BP_STEER_PERIOD_US 50000U +#define FORD_BP_CORE_STEER_PERIOD_S 0.045F +#define FORD_BP_PANDA_AGE_NS 300000000U diff --git a/opendbc_repo/opendbc/bluepilot_lateral/params/limits.py b/opendbc_repo/opendbc/bluepilot_lateral/params/limits.py new file mode 100644 index 0000000000..a17e792ead --- /dev/null +++ b/opendbc_repo/opendbc/bluepilot_lateral/params/limits.py @@ -0,0 +1,19 @@ +"""Generated from manifest.json; host and core use this manifest contract.""" +BLEND = 0.5 +VLT_EXTRA = 0.1 +PATH_MIN = -0.5 +PATH_MAX = 0.5235 +GAIN_MIN = 0.95 +GAIN_MAX = 1.3 +CURVATURE_MAX = 0.02 +CURVATURE_ERROR = 0.002 +LATERAL_ACCEL = 2.4114 +RX_AGE_US = 100000 +SHADOW_AGE_US = 60000 +PATH_ROUNDING_MARGIN = 0.0005 +SHADOW_ROUNDING_MARGIN = 1e-06 +LATERAL_JERK = 3.5886 +RT_INTERVAL_US = 250000 +STEER_PERIOD_US = 50000 +CORE_STEER_PERIOD_S = 0.045 +PANDA_AGE_NS = 300000000 diff --git a/opendbc_repo/opendbc/bluepilot_lateral/params/manifest.json b/opendbc_repo/opendbc/bluepilot_lateral/params/manifest.json new file mode 100644 index 0000000000..60b482f432 --- /dev/null +++ b/opendbc_repo/opendbc/bluepilot_lateral/params/manifest.json @@ -0,0 +1,109 @@ +{ + "source_revision": "e1d051d7ba270261b4455068bd68f1a58db15a4a", + "settings": [ + { + "key": "FordLateralMode", + "type": "enum", + "default": 0, + "values": { + "0": "Current curvature", + "1": "BluePilot angle" + }, + "label": "Ford steering controller", + "description": "Select the steering controller for supported Ford profiles. Takes effect on the next drive.", + "modes": [ + "angle" + ] + } + ], + "defaults": { + "blend": 0.5, + "vlt_extra_max": 0.1, + "low_speed_factor": 1.0, + "high_speed_factor": 1.0, + "dampening": 1.0, + "lane_change_factor": 1.0 + }, + "bounds": { + "path_angle_wire": [ + -0.5, + 0.5235 + ], + "gain": [ + 0.95, + 1.3 + ], + "curvature_error": 0.002, + "lateral_accel": 2.4114, + "rx_age_us": 100000, + "shadow_age_us": 60000, + "steer_period_us": 50000, + "curvature": 0.02, + "path_rounding_margin": 0.0005, + "shadow_rounding_margin": 1e-06, + "lateral_jerk": 3.5886, + "rt_interval_us": 250000, + "core_steer_period_s": 0.045, + "panda_age_ns": 300000000 + }, + "angle_lane_trim": { + "source_revision": "e22afa6be9b881fa784c92ebb316db47728a3d81", + "defaults": { + "enabled": false, + "offset_m": 0.0, + "gain": 0.25 + }, + "bounds": { + "offset_m": [ + -0.5, + 0.5 + ], + "gain": [ + 0.0, + 1.0 + ], + "width_m": [ + 2.4, + 2.8, + 3.75, + 4.25 + ], + "width_tolerance": [ + 0.0, + 0.81, + 0.81, + 0.59 + ], + "std": [ + 0.3, + 0.5 + ], + "std_tolerance": [ + 0.81, + 0.0 + ], + "confidence": [ + 0.6, + 0.8 + ], + "speed_mps": [ + 0.0, + 9.0, + 15.0 + ], + "speed_authority": [ + 0.0, + 0.0, + 1.0 + ], + "lookahead_m": [ + 8.0, + 35.0 + ], + "raw_correction": 0.004, + "tau_s": 0.4, + "period_s": 0.05, + "correction_delta": 0.00015 + } + } +} diff --git a/opendbc_repo/opendbc/bluepilot_lateral/params/protocol.h b/opendbc_repo/opendbc/bluepilot_lateral/params/protocol.h new file mode 100644 index 0000000000..a7179eb9cf --- /dev/null +++ b/opendbc_repo/opendbc/bluepilot_lateral/params/protocol.h @@ -0,0 +1,10 @@ +#pragma once +// Generated from protocol.json; do not allocate bit 1 to angle metadata. +#define FORD_BP_VERSION 1U +#define FORD_BP_ANGLE_MASK 1U +#define FORD_BP_EXTENDED_CURVATURE_MASK 2U +#define FORD_BP_COUNTER_SHIFT 2U +#define FORD_BP_COUNTER_MASK 28U +#define FORD_BP_COUNTER_MODULUS 8U +#define FORD_BP_VERSION_MASK 15U +#define FORD_BP_CHECKSUM_SHIFT 4U diff --git a/opendbc_repo/opendbc/bluepilot_lateral/params/protocol.json b/opendbc_repo/opendbc/bluepilot_lateral/params/protocol.json new file mode 100644 index 0000000000..dc846eb0d6 --- /dev/null +++ b/opendbc_repo/opendbc/bluepilot_lateral/params/protocol.json @@ -0,0 +1,11 @@ +{ + "version": 1, + "angle_mask": 1, + "extended_curvature_mask": 2, + "counter_shift": 2, + "counter_mask": 28, + "counter_modulus": 8, + "shadow_scale": 1e-06, + "version_mask": 15, + "checksum_shift": 4 +} diff --git a/opendbc_repo/opendbc/bluepilot_lateral/params/protocol.py b/opendbc_repo/opendbc/bluepilot_lateral/params/protocol.py new file mode 100644 index 0000000000..c13f2344c7 --- /dev/null +++ b/opendbc_repo/opendbc/bluepilot_lateral/params/protocol.py @@ -0,0 +1,10 @@ +"""Generated from protocol.json; layout preserves the existing curvature flag.""" +VERSION = 1 +ANGLE_MASK = 1 +EXTENDED_CURVATURE_MASK = 2 +COUNTER_SHIFT = 2 +COUNTER_MASK = 28 +COUNTER_MODULUS = 8 +SHADOW_SCALE = 1e-06 +VERSION_MASK = 15 +CHECKSUM_SHIFT = 4 diff --git a/opendbc_repo/opendbc/bluepilot_lateral/params/trim.py b/opendbc_repo/opendbc/bluepilot_lateral/params/trim.py new file mode 100644 index 0000000000..51a13ca6fa --- /dev/null +++ b/opendbc_repo/opendbc/bluepilot_lateral/params/trim.py @@ -0,0 +1,45 @@ +"""Generated Python-only angle trim defaults; no native bound or registry changes.""" +from typing import TypedDict + + +class TrimDefaults(TypedDict): + enabled: bool + offset_m: float + gain: float + + +class TrimBounds(TypedDict): + offset_m: list[float] + gain: list[float] + width_m: list[float] + width_tolerance: list[float] + std: list[float] + std_tolerance: list[float] + confidence: list[float] + speed_mps: list[float] + speed_authority: list[float] + lookahead_m: list[float] + raw_correction: float + tau_s: float + period_s: float + correction_delta: float + + +SOURCE_REVISION = 'e22afa6be9b881fa784c92ebb316db47728a3d81' +DEFAULTS: TrimDefaults = {'enabled': False, 'offset_m': 0.0, 'gain': 0.25} +BOUNDS: TrimBounds = { + 'offset_m': [-0.5, 0.5], + 'gain': [0.0, 1.0], + 'width_m': [2.4, 2.8, 3.75, 4.25], + 'width_tolerance': [0.0, 0.81, 0.81, 0.59], + 'std': [0.3, 0.5], + 'std_tolerance': [0.81, 0.0], + 'confidence': [0.6, 0.8], + 'speed_mps': [0.0, 9.0, 15.0], + 'speed_authority': [0.0, 0.0, 1.0], + 'lookahead_m': [8.0, 35.0], + 'raw_correction': 0.004, + 'tau_s': 0.4, + 'period_s': 0.05, + 'correction_delta': 0.00015, +} diff --git a/opendbc_repo/opendbc/bluepilot_lateral/safety/ford_bp.h b/opendbc_repo/opendbc/bluepilot_lateral/safety/ford_bp.h new file mode 100644 index 0000000000..100ab9ffe5 --- /dev/null +++ b/opendbc_repo/opendbc/bluepilot_lateral/safety/ford_bp.h @@ -0,0 +1,236 @@ +#pragma once +// Angle-primary Ford extension adapted from Alan Polk's bp-7.0 e1d051d7. +// See ../CREDITS.md, ../LICENSE and ../LICENSE.md. No reset bypass. +#include "opendbc/bluepilot_lateral/params/protocol.h" +#include "opendbc/bluepilot_lateral/params/limits.h" + +// Shared Ford stock-switch state is declared before the angle hooks below. +static bool ford_stock_switch = false; +static bool ford_bp_enabled = false; +static bool ford_bp_canfd = false; +static bool ford_bp_shadow_seen = false; +static bool ford_bp_lka_counter_seen = false; +static uint8_t ford_bp_lka_counter = 0U; +static int ford_bp_shadow_raw = 0; +static uint32_t ford_bp_shadow_us = 0U; +static int ford_bp_path_last = 0; +static bool ford_bp_control_counter_seen = false; +static uint8_t ford_bp_control_counter = 0U; +static bool ford_bp_control_seen = false; +static uint32_t ford_bp_control_us = 0U; +static float ford_bp_equivalent_last = 0.0F; +static unsigned int ford_bp_rt_msgs = 0U; +static unsigned int ford_bp_rt_msgs_prev = 0U; +static uint32_t ford_bp_rt_us = 0U; +static bool ford_bp_rx_seen[7]; +static uint32_t ford_bp_rx_us[7]; + +static void ford_bp_invalidate_shadow(void) { + ford_bp_shadow_seen = false; + ford_bp_shadow_raw = 0; +} + +static void ford_bp_withdraw(void) { + ford_bp_invalidate_shadow(); + ford_bp_path_last = 0; + ford_bp_equivalent_last = 0.0F; +} + +static bool ford_bp_configure(uint16_t param) { + ford_bp_enabled = ((param == 128U) || (param == 129U) || (param == 130U)) && (alternative_experience == 0); +#ifdef ALLOW_DEBUG + ford_bp_enabled |= (param == 131U) && (alternative_experience == 0); +#endif + ford_bp_canfd = (param & 2U) != 0U; + ford_bp_lka_counter_seen = false; + ford_bp_control_counter_seen = false; + ford_bp_control_seen = false; + ford_bp_lka_counter = 0U; + ford_bp_control_counter = 0U; + ford_bp_shadow_us = 0U; + ford_bp_control_us = 0U; + ford_bp_rt_msgs = 0U; + ford_bp_rt_msgs_prev = 0U; + ford_bp_rt_us = microsecond_timer_get(); + ford_bp_withdraw(); + for (unsigned int i = 0U; i < 7U; i++) { + ford_bp_rx_seen[i] = false; + ford_bp_rx_us[i] = 0U; + } + return ((param & 128U) == 0U) || ford_bp_enabled; +} + +static bool ford_bp_health(uint32_t now); + +static void ford_bp_rx(const CANPacket_t *msg) { + if (ford_bp_enabled && (msg->bus == 0U) && (GET_LEN(msg) == 8U)) { + const unsigned int ids[7] = {0x415U, 0x202U, 0x91U, 0x165U, 0x204U, 0x213U, 0x83U}; + for (unsigned int i = 0U; i < 7U; i++) { + if (msg->addr == ids[i]) { + ford_bp_rx_seen[i] = true; + ford_bp_rx_us[i] = microsecond_timer_get(); + } + } + // Angle-specific source freshness is stricter than the generic1s RX tick. + // Expose that withdrawal through the ordinary public controls acknowledgment. + if (controls_allowed && !ford_bp_health(microsecond_timer_get())) { + controls_allowed = false; + } + // Permission losses remove the old actuator history before any later arm. + if (!controls_allowed || brake_pressed || gas_pressed) { + ford_bp_withdraw(); + } + } +} + +static bool ford_bp_health(uint32_t now) { + bool valid = !safety_rx_checks_invalid && !relay_malfunction; + for (int i = 0; i < current_safety_config.rx_checks_len; i++) { + const RxStatus *status = ¤t_safety_config.rx_checks[i].status; + valid &= status->msg_seen && !status->lagging && status->valid_checksum && + status->valid_quality_flag && (status->wrong_counters < MAX_WRONG_COUNTERS); + } + const unsigned int count = ford_stock_switch ? 7U : 6U; + for (unsigned int i = 0U; i < count; i++) { + const uint32_t age = ((i == 3U) || (i == 6U)) ? (2U * FORD_BP_RX_AGE_US) : FORD_BP_RX_AGE_US; + valid &= ford_bp_rx_seen[i] && (safety_get_ts_elapsed(now, ford_bp_rx_us[i]) <= age); + } + return valid; +} + +static bool ford_bp_lka(const CANPacket_t *msg) { + const uint32_t now = microsecond_timer_get(); + const unsigned int counter = (msg->data[4] & FORD_BP_COUNTER_MASK) >> FORD_BP_COUNTER_SHIFT; + unsigned int sum = 0U; + for (unsigned int i = 0U; i < 7U; i++) { sum += msg->data[i]; } + const unsigned int checksum = (15U - (sum & 15U)) & 15U; + // Preserve every DBC-owned bit of the packer's neutral LKA body. + const unsigned int angle = ((msg->data[2] & 0xFU) << 8) | msg->data[3]; + const unsigned int curvature = (msg->data[1] << 4) | (msg->data[2] >> 4); + bool valid = !relay_malfunction && (msg->bus == 0U) && (GET_LEN(msg) == 8U) && (msg->data[0] == 0U) && + (angle == 2048U) && (curvature == 2048U) && + ((msg->data[4] & 0xE3U) == FORD_BP_ANGLE_MASK) && + ((msg->data[7] & FORD_BP_VERSION_MASK) == FORD_BP_VERSION) && + ((msg->data[7] >> FORD_BP_CHECKSUM_SHIFT) == checksum); + const int shadow = to_signed((msg->data[5] << 8) | msg->data[6], 16); + const bool resync = (shadow == 0) && !controls_allowed; + if (ford_bp_lka_counter_seen && !resync) { + valid &= counter == ((ford_bp_lka_counter + 1U) % FORD_BP_COUNTER_MODULUS); + valid &= safety_get_ts_elapsed(now, ford_bp_shadow_us) >= 20000U; + } + valid &= SAFETY_ABS(shadow) <= 20000; + if (valid) { + ford_bp_lka_counter = (uint8_t)counter; + ford_bp_lka_counter_seen = true; + ford_bp_shadow_raw = shadow; + ford_bp_shadow_seen = !resync; + ford_bp_shadow_us = now; + } else { + ford_bp_invalidate_shadow(); + } + return valid; +} + +static bool ford_bp_lateral(const CANPacket_t *msg) { + const bool fd = msg->addr == 0x3D6U; + const unsigned int mode = fd ? ((msg->data[0] >> 4) & 7U) : ((msg->data[4] >> 2) & 7U); + const unsigned int curvature = fd ? ((msg->data[2] << 3) | (msg->data[3] >> 5)) : + ((msg->data[0] << 3) | (msg->data[1] >> 5)); + const unsigned int rate = fd ? (((unsigned int)msg->data[6] << 3) | (msg->data[7] >> 5)) : + (((msg->data[1] & 31U) << 8) | msg->data[2]); + const unsigned int path_raw = fd ? (((msg->data[3] & 31U) << 6) | (msg->data[4] >> 2)) : + (((unsigned int)msg->data[3] << 3) | (msg->data[4] >> 5)); + const unsigned int offset = fd ? (((msg->data[4] & 3U) << 8) | msg->data[5]) : + (((unsigned int)msg->data[5] << 2) | (msg->data[6] >> 6)); + const unsigned int precision = fd ? ((msg->data[0] >> 2) & 3U) : (msg->data[4] & 3U); + const unsigned int ramp = fd ? (msg->data[0] & 3U) : ((msg->data[6] >> 4) & 3U); + const bool active = mode == 1U; + const int path = (int)path_raw - 1000; + const uint32_t now = microsecond_timer_get(); + bool valid = !relay_malfunction && (msg->bus == 0U) && (GET_LEN(msg) == 8U) && (fd == ford_bp_canfd) && (mode <= 1U) && + (curvature == 1000U) && (rate == (fd ? 1024U : 4096U)) && (offset == 512U) && + (precision <= 1U) && (ramp == (active ? 2U : 0U)); + const unsigned int counter = (msg->data[7] >> 1) & 15U; + if (fd) { + unsigned int checksum = mode + counter; + const unsigned int fields[4] = {curvature, rate, path_raw, offset}; + for (unsigned int i = 0U; i < 4U; i++) { checksum += fields[i] + (fields[i] >> 8); } + valid &= msg->data[1] == (0xFFU - (checksum & 0xFFU)); + valid &= ((msg->data[0] & 0x80U) == 0U) && ((msg->data[7] & 1U) == 0U); + if (ford_bp_control_counter_seen && active) { valid &= counter == ((ford_bp_control_counter + 1U) % 16U); } + } else { + valid &= ((msg->data[6] & 0xFU) == 0U) && (msg->data[7] == 0U); + } + const float speed_for_equivalent = SAFETY_MAX(vehicle_speed.min / VEHICLE_SPEED_FACTOR, 0.1F); + const float equivalent = (float)path / (2000.0F * speed_for_equivalent); + // Time-window expiration is independent of packet acceptance: denied floods + // cannot latch the old count forever or erase accepted actuator history. + const uint32_t rt_elapsed = safety_get_ts_elapsed(now, ford_bp_rt_us); + if (rt_elapsed >= FORD_BP_RT_INTERVAL_US) { + ford_bp_rt_msgs = 0U; + ford_bp_rt_msgs_prev = 0U; + ford_bp_rt_us = now; + } else if (rt_elapsed >= (FORD_BP_RT_INTERVAL_US / 2U)) { + ford_bp_rt_msgs_prev = ford_bp_rt_msgs; + ford_bp_rt_msgs = 0U; + ford_bp_rt_us = now; + } else { + // Keep the current history while neither expiration boundary has elapsed. + } + const unsigned int rt_count = ford_bp_rt_msgs + ford_bp_rt_msgs_prev; + valid &= rt_count <= 7U; // Current20Hz curvature RT allowance; accepted frames own this count. + if (active) { + static const struct lookup_t roc = {{10.0F, 15.0F, 25.0F}, {0.0561F, 0.04335F, 0.00918F}}; + const float speed_min = SAFETY_MAX(vehicle_speed.min / VEHICLE_SPEED_FACTOR, 0.1F); + const float speed_max = SAFETY_MAX(vehicle_speed.max / VEHICLE_SPEED_FACTOR, 0.1F); + const float delta_float = safety_interpolate(roc, speed_min - 1.0F) * 2000.0F; + const int delta = (int)delta_float + 1; + const float shadow = (float)ford_bp_shadow_raw * 0.000001F; + const float shadow_can = shadow * 50000.0F; + const float path_abs = SAFETY_ABS(path) / 2000.0F; + const float path_curvature_low = path_abs / (speed_max * FORD_BP_GAIN_MAX); + const float path_curvature_high = path_abs / (speed_min * FORD_BP_GAIN_MIN); + const float physical_cap = SAFETY_MIN(FORD_BP_CURVATURE_MAX, FORD_BP_LATERAL_ACCEL / (SAFETY_MAX(speed_max, 1.0F) * SAFETY_MAX(speed_max, 1.0F))); + const float relation_low = SAFETY_ABS(shadow) * speed_min * FORD_BP_GAIN_MIN * 2000.0F; + const float relation_high = SAFETY_ABS(shadow) * speed_max * FORD_BP_GAIN_MAX * 2000.0F; + valid &= lateral_controls_allowed() && controls_allowed && ford_bp_health(now) && ford_bp_shadow_seen && + (safety_get_ts_elapsed(now, ford_bp_shadow_us) <= FORD_BP_SHADOW_AGE_US) && + (path >= -1000) && (path <= 1047) && (SAFETY_ABS(path - ford_bp_path_last) <= delta) && + ((path == 0) || ((ford_bp_shadow_raw != 0) && ((path > 0) == (ford_bp_shadow_raw > 0)))) && + (SAFETY_ABS(path) >= (relation_low - 2.0F)) && (SAFETY_ABS(path) <= (relation_high + 2.0F)) && + (SAFETY_ABS(shadow) <= (physical_cap + FORD_BP_SHADOW_ROUNDING_MARGIN)) && (path_curvature_high <= (physical_cap + FORD_BP_SHADOW_ROUNDING_MARGIN)); + if (speed_max > 10.0F) { + const int measured_min = curvature_state.meas.min - 100; + const int measured_max = curvature_state.meas.max + 100; + const float measured_min_float = (float)measured_min; + const float measured_max_float = (float)measured_max; + valid &= (shadow_can >= measured_min_float) && (shadow_can <= measured_max_float); + // Independent actual-actuator check; an invented shadow cannot launder path angle. + const float signed_low = (path < 0) ? (-path_curvature_high) : path_curvature_low; + const float signed_high = (path < 0) ? (-path_curvature_low) : path_curvature_high; + valid &= ((signed_low * 50000.0F) >= measured_min_float) && + ((signed_high * 50000.0F) <= measured_max_float); + } + const uint32_t elapsed = ford_bp_control_seen ? safety_get_ts_elapsed(now, ford_bp_control_us) : FORD_BP_STEER_PERIOD_US; + const float jerk_speed = SAFETY_MAX(speed_min - 1.0F, 1.0F); + const float jerk_delta = FORD_BP_LATERAL_JERK / (jerk_speed * jerk_speed) * + (SAFETY_MIN(elapsed, FORD_BP_STEER_PERIOD_US) * 0.000001F) * FORD_BP_GAIN_MIN; + valid &= SAFETY_ABS(equivalent - ford_bp_equivalent_last) <= (jerk_delta + FORD_BP_SHADOW_ROUNDING_MARGIN); + if (ford_bp_control_seen) { valid &= elapsed >= 40000U; } + } else { + valid &= path == 0; + } + if (valid) { + ford_bp_rt_msgs += 1U; + ford_bp_equivalent_last = active ? equivalent : 0.0F; + ford_bp_path_last = active ? path : 0; + ford_bp_control_counter = (uint8_t)counter; + ford_bp_control_counter_seen = true; + ford_bp_control_seen = true; + ford_bp_control_us = now; + if (!active) { ford_bp_shadow_seen = false; } + } else { + ford_bp_invalidate_shadow(); + } + return valid; +} diff --git a/opendbc_repo/opendbc/bluepilot_lateral/tests/__init__.py b/opendbc_repo/opendbc/bluepilot_lateral/tests/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/opendbc_repo/opendbc/bluepilot_lateral/tests/reference.py b/opendbc_repo/opendbc/bluepilot_lateral/tests/reference.py new file mode 100644 index 0000000000..1637576c87 --- /dev/null +++ b/opendbc_repo/opendbc/bluepilot_lateral/tests/reference.py @@ -0,0 +1,101 @@ +"""Hash-bound upstream angle execution and current-curvature controller oracle. + +Only imports are removed from the upstream angle/human module AST; every other +statement and function remains exact. Glue supplies current ABI types, source +fixed defaults and the source's no-op lazy-init/yaw-default adapter. No BluePilot +curvature strategy is loaded. Its diagnostic limiter cannot affect angle output. +""" +import ast +from collections import namedtuple +import hashlib +import json +from pathlib import Path +from types import SimpleNamespace + +import numpy as np +from opendbc.car import structs, DT_CTRL +from opendbc.car.ford.values import CAR, CarControllerParams +from opendbc.car.ford.fordcan import CanBus +from opendbc.car.lateral import AngleSteeringLimits, apply_std_steer_angle_limits +from openpilot.selfdrive.modeld.constants import ModelConstants + +ROOT = Path(__file__).with_name("reference") +MANIFEST = json.loads((ROOT / "manifest.json").read_text()) + + +def source(name): + raw = (ROOT / (name + ".py.txt")).read_bytes() + if hashlib.sha256(raw).hexdigest() != MANIFEST[name]["sha256"]: + raise AssertionError("Reference source differs from its pinned manifest: " + name) + return ast.parse(raw.decode(), filename=MANIFEST[name]["origin"]) + + +def execute(tree, namespace, *, names=None): + body = [] + for node in tree.body: + if isinstance(node, (ast.Import, ast.ImportFrom)): + continue + if names is not None: + assigned = [target.id for target in node.targets if isinstance(target, ast.Name)] if isinstance(node, ast.Assign) else [] + if getattr(node, "name", None) not in names and not any(name in names for name in assigned): + continue + body.append(node) + exec(compile(ast.Module(body=body, type_ignores=[]), "", "exec"), namespace) + + +def angle(): + LateralResult = namedtuple("LateralResult", "apply_curvature curvature_rate path_offset path_angle ramp_type precision_type lateralUncertainty") + namespace = {"np": np, "clip": np.clip, "interp": np.interp, "DT_CTRL": DT_CTRL, + "CAR": CAR, "CarControllerParams": CarControllerParams, "ModelConstants": ModelConstants, + "LateralResult": LateralResult, "AngleSteeringLimits": AngleSteeringLimits, + "apply_std_steer_angle_limits": apply_std_steer_angle_limits} + execute(source("human"), namespace) + execute(source("values"), namespace, names={"_BP_ANGLE_RATE_UP", "_BP_ANGLE_RATE_DOWN", "BP_ANGLE_LIMITS"}) + execute(source("angle"), namespace) + return namespace["LateralAngleExt"] + + +def builders(): + namespace = {"CanBus": CanBus, "structs": structs} + execute(source("fordcan"), namespace, names={"calculate_lat_ctl2_checksum"}) + execute(source("builders"), namespace, names={"create_lka_msg", "create_lat_ctl_msg", "create_lat_ctl2_msg", "_BP_LKA_SHADOW_CURVATURE_SCALE"}) + return namespace + + +def curvature_controller(): + # Full exact pre-angle production controller, with unchanged current imports. + namespace = {"__name__": "ford_curvature_pre_angle_reference"} + exec(compile(source("starpilot_curvature_controller"), "", "exec"), namespace) + return namespace["CarController"] + + +class Angle: + def __init__(self, identity): + self.controller = angle()() + self.controller.CP = SimpleNamespace(carFingerprint=identity) + self.controller._ensure_lateral_curv_initialized = lambda _cp: None # Exact source guard is a no-op. + self.controller.get_current_curvature = lambda cs: -cs.out.yawRate / max(cs.out.vEgoRaw, .1) + self.controller.path_angle_last = 0. + self.controller.lp = None # Read but unused by the source angle strategy. + self.controller.lane_change_factor_bp = [0., 50.] + self.controller.lane_change_factor_low = 1. + self.controller.model = None + self.controller.update_angle_params(None) + + def step(self, inputs): + c = self.controller + c.sm = {"liveDelay": SimpleNamespace(lateralDelay=inputs.lateral_delay)} + c.model = SimpleNamespace(orientationRate=SimpleNamespace(z=list(inputs.yaw_predictions)), + meta=SimpleNamespace(laneChangeState=1 if inputs.lane_change else 0, + laneChangeDirection=inputs.lane_direction)) if inputs.yaw_predictions else None + cc = SimpleNamespace(latActive=inputs.active) + cs = SimpleNamespace(out=SimpleNamespace(vEgoRaw=inputs.speed, yawRate=-inputs.measured_curvature * inputs.speed, + steeringPressed=inputs.steering_pressed, steeringAngleDeg=inputs.steering_angle), + lat_ctl_lim_stat=inputs.limit_status) + return c.update_angle_strategy(cc, cs, SimpleNamespace(curvature=inputs.desired_curvature), c.CP) + + +def trim(): + namespace = {"np": np, "interp": np.interp} + execute(source("bpdev_trim"), namespace) + return namespace["LaneCenterTrim"] diff --git a/opendbc_repo/opendbc/bluepilot_lateral/tests/reference/angle.py.txt b/opendbc_repo/opendbc/bluepilot_lateral/tests/reference/angle.py.txt new file mode 100644 index 0000000000..886ffca8a2 --- /dev/null +++ b/opendbc_repo/opendbc/bluepilot_lateral/tests/reference/angle.py.txt @@ -0,0 +1,577 @@ +""" +BluePilot: Ford CAN-FD path-angle–primary lateral control (developer). + +Steering intent is c1 from κ → θ. Converts planner/model curvature into ``path_angle`` using +PSCM short lookahead d_ref and y ≈ ½κ x² ⇒ path_angle = ½ κ d_ref (see +``bluepilot/agent_info/20_FORD_PSCM_KNOWLEDGE_PACK.md``). Predicted curvature (modelV2) is +blended with ``actuators.curvature`` per ``FordPathAngleBlendRatio`` (0 = planner only, +1 = model only). + +**c0 (path_offset) is always zero on the wire, unconditionally.** Angle mode has no centering +trim -- an earlier port attempt piped a small additive trim onto path_angle through the +curv-mode ``LC_PID_controller``, but it never actually tracked lane center correctly in this +mode and was removed; only the DBC-required zero c0 remains. + +**Human-turn override**: while the driver manually turns (same sustained-press + angle criteria +as ``lateral_curv_ext``, via the shared ``HumanTurnDetector``), lateral is forced inactive (mode +0, all-zero signals) instead of winding path_angle into a stale command the PSCM has to reconcile +on release -- on the Mach-E's PSCM that reconciliation cost 2-3 s of dead time before control +resumed. Mode 0 is panda-clean by construction: every ford.h check has a legitimate +!steer_control_enabled branch, so no reset-bypass latch involvement. On release, path_angle ramps +back in from zero through the soft ROC below (no jump seed) -- generous at human-turn speeds, and +admitted by ford.h's path_angle ROC check (2% looser) without any bypass. +""" +import numpy as np +from numpy import clip, interp + +from opendbc.car import DT_CTRL +from opendbc.car.lateral import apply_std_steer_angle_limits +from opendbc.car.ford.values import CAR, CarControllerParams +from opendbc.sunnypilot.car.ford.lateral_curv_ext import LateralResult +from opendbc.sunnypilot.car.ford.human_turn import HumanTurnDetector +from opendbc.sunnypilot.car.ford.values_ext import BP_ANGLE_LIMITS +from selfdrive.modeld.constants import ModelConstants + +# Hard-coded per-platform gain defaults. +# CAN vehicles (Escape MK4, Bronco Sport, Explorer, Maverick, Edge) +_GAIN_CAN = (1.00, 1.15) +# CAN-FD body-on-frame trucks (F-150, Lightning, Expedition, Ranger) +_GAIN_CANFD_BOF = (0.95, 0.95) +# CAN-FD unibody SUVs (Mustang Mach-E, Escape MK4.5) +_GAIN_CANFD_SUV = (1.00, 1.05) + +_CANFD_BOF_CARS = frozenset({ + CAR.FORD_F_150_MK14, + CAR.FORD_F_150_LIGHTNING_MK1, + CAR.FORD_EXPEDITION_MK4, + CAR.FORD_RANGER_MK2, +}) +_CANFD_SUV_CARS = frozenset({ + CAR.FORD_MUSTANG_MACH_E_MK1, + CAR.FORD_ESCAPE_MK4_5, +}) + + +# DBC ``LatCtlPath_An_Actl`` (rad) — panda safety uses the same in ``ford.h``; PSCM enforces in firmware. +FORD_DBC_PATH_ANGLE_MIN = -0.5 +FORD_DBC_PATH_ANGLE_MAX = 0.5235 + + +# PSCM d_ref (m) vs speed (m/s) — 6 points; above ~55.6 m/s use plateau + optional cap to 5 m. +_PSCM_DREF_SPEEDS_MS = (0.0, 4.17, 27.78, 41.67, 50.0, 55.56) +_PSCM_DREF_M = (0.5, 0.95, 1.4, 2.075, 2.75, 3.875) + +# Default blend ratio validated on F-150 fleet data (0.5s lookup time). +_FORD_PATH_ANGLE_BLEND_RATIO_DEFAULT = 0.50 + +# Variable lookup time (VLT): curvature_lookup_time adapts to speed and curvature magnitude. +# t_lookup = t_base + t_extra_max × speed_factor(v) × kappa_factor(|κ|) +# t_base = liveDelay.lateralDelay + DT_MDL — always matches the planner's pre-compensation floor. +# Extra lookahead collapses toward zero at high speed (PSCM responds faster) +# and at large curvature (prevents blend importing a "start unwinding" signal too early). +_DT_MDL = 0.05 # model loop period (matches common/realtime.py) +_VLT_T_EXTRA_MAX = 0.10 # max extra lookahead above t_base +_VLT_V_LOW_MS = 25.0 * 0.44704 # 25 mph — full extra lookahead at or below this speed +_VLT_V_HIGH_MS = 55.0 * 0.44704 # 55 mph — no extra lookahead at or above this speed +_VLT_KAPPA_FULL = 0.005 # 1/m — full extra lookahead below this curvature (200m+ radius) +_VLT_KAPPA_TAPER = 0.020 # 1/m — no extra lookahead above this curvature (50m radius) + +# Rate cap on path_angle magnitude DECREASE during PSCM LimitReached (rad/call = 0.40 rad/s). +# Both model and planner naturally drop path_angle ~0.36 rad/s at a sharp 90° apex, while the PSCM is +# physically pinned and cannot execute the rapidly falling desired angle. The resulting actual-vs-desired +# gap (up to 47° observed) causes a snap correction the moment the PSCM is released. This cap limits +# the desired-angle drop rate to what the PSCM can reasonably track, at the cost of holding the car +# slightly more in the curve during saturation. +# BluePilot: this strategy runs once per STEER_STEP (CarControllerParams.STEER_STEP=5), i.e. once +# every 5th 100Hz control tick = 20Hz, not every tick. The original 0.004 rad/call value (and its +# "50Hz" comment, corrected above) was authored 2026-05-11 on bp-sid-simple, which had already +# switched STEER_STEP 5->1 (true 100Hz) on 2026-04-22 -- so it was tuned at 100Hz real cadence +# even though its own comment mistakenly said 50Hz. Scaled x5 here to restore the same real-world +# 0.40 rad/s (23 deg/s) unwind rate on this branch's actual 20Hz cadence. +_PSCM_SAT_UNWIND_RATE = 0.02 # rad/call (0.02 * 20Hz = 0.40 rad/s) + +# Post-override stall blip. Road test 2026-07-14 (route 886240741b067740/000000bd--feb980680f) +# showed that after driver-touch episodes the Mach-E PSCM keeps reporting InProgress but honors +# path_angle at only ~0.56x (healthy hands-free delivery on the same route: ~0.95 median). The +# current-curvature deviation clip below then pins kappa_cmd at measured + CURVATURE_ERROR, so the +# command can never lead the car enough to overcome the attenuation -- a stall equilibrium the +# driver reads as "not engaging" (wire path_angle flat at ~4 deg for 4.5 s while desired kappa +# climbed to 3x measured, EPS motor current ~0 A). A short mode-0 pulse -- the identical +# panda-clean wire pattern the human-turn override sends, no ford.h involvement -- resets the +# PSCM's authority, after which path_angle ramps back in from zero through the soft ROC. +_STEER_DT = CarControllerParams.STEER_STEP * DT_CTRL # 20 Hz lateral tick (matches human_turn.py) +_STALL_GAP_MIN = 2.0 * CarControllerParams.CURVATURE_ERROR # desired must lead measured by 2x the clip tolerance +_STALL_HOLD_S = 0.5 # accumulated clip-binding time before a pulse fires +_STALL_BLIP_FRAMES = 6 # mode-0 pulse length (6 frames @ 20 Hz = 300 ms; PSCM acked mode 0 in ~150 ms on-road) +_STALL_COOLDOWN_S = 2.0 # re-arm delay after a pulse (release ramp + PSCM response time) +_STALL_MAX_BLIPS = 3 # give up on a stuck episode; devLim telemetry keeps recording the stall +# Proactive hand-off blip: any sustained driver press attenuates the PSCM (route 000000be seg 4: +# 3 s of sub-45-deg circle-exit steering left it at ~0x delivery, and the reactive detector's +# fire-after-the-stall-develops timing meant 2.4 s of dead-straight running into the next curve +# before the pulse landed). Firing the same pulse on the falling edge of a sustained press resets +# the PSCM while the car is straight and the command is small -- a 300 ms lateral gap right at +# hand-off, imperceptible, instead of a missed curve. The reactive detector above stays as backstop. +_PRESS_BLIP_MIN_S = 0.5 # press must last this long before its release earns a pulse +# The pulse releases steering for 300 ms; never fire it in a curve. +_BLIP_MAX_PATH_ANGLE = 0.10 # rad + + +def pscm_d_ref_m(v_ego_ms: float) -> float: + v = max(float(v_ego_ms), 0.0) + d = float(np.interp(v, _PSCM_DREF_SPEEDS_MS, _PSCM_DREF_M)) + if v > _PSCM_DREF_SPEEDS_MS[-1]: + # Doc: d_ref table ends at 3.875 m; contribution saturates for high speed — cap at 5 m. + d = min(5.0, d) + return d + + +class LateralAngleExt: + def __init__(self, CP=None, CP_SP=None): + # Predicted-curvature blend for path_angle: pred * b + desired * (1-b); b from ``FordPathAngleBlendRatio`` + self.path_angle_blend_ratio = _FORD_PATH_ANGLE_BLEND_RATIO_DEFAULT + # Max extra VLT above t_base; from ``FordVLTExtraMax`` param + self.vlt_extra_max = _VLT_T_EXTRA_MAX + # Telemetry: final path_angle (rad) after limits (see bp_card_publisher) + self.bp_path_angle_final = 0.0 + # High-speed gain factors: set per-platform via carFingerprint in update_angle_params. + self.path_angle_gain_lowC_highV = 1.0 # dampening at high speed, low curvature + self.path_angle_gain_highC_highV = 1.0 # gain at high speed, high curvature + self.bp_path_angle_gain_lowC_highV = 1.0 + self.bp_path_angle_gain_highC_highV = 1.0 + # User-tunable "feel" multipliers: read from the angle-tuning Params below. + self.low_speed_curv_factor = 1.0 + self.high_speed_curv_factor = 1.0 + self.user_dampening_factor = 1.0 + self.bp_low_speed_curv_factor = 1.0 + self.bp_high_speed_curv_factor = 1.0 + # BluePilot: angle mode's own lane-change scaling factor, independent of curvature mode's + # lane_change_factor_high_curv -- angle needs a boost (>1) where curvature needs a cut (<1). + self.lane_change_factor_high_ang = 1.0 + # Telemetry: variable curvature lookup time used this frame (s) + self.bp_curvature_lookup_time = _VLT_T_EXTRA_MAX + 0.3725 # warm start at ~0.5s + # BluePilot: error-clipped kappa path_angle was derived from -- carcontroller.py reads this as + # shadow_curvature for ford.h's angle-mode deviation check. Actively consumed, not telemetry. + self.bp_kappa_cmd = 0.0 + # BluePilot: rate-limit diagnostics (controllerStateBP) + self.bp_angle_rate_limited = False # path_angle soft-ROC clip actually bit this frame + self.bp_curvature_rate_limited = False # equivalent curvature would be rate-limited by curv-mode logic (sim) + self.bp_curvature_deviation_limited = False # current_curvature error-clip constrained kappa_cmd this frame + self.sim_curvature_last = 0.0 # shadow curvature-mode last for the curvatureRateLimited sim + # Exit detection: track previous desired curvature to sense when planner is actively reducing + self._desired_curvature_last = 0.0 + # Human-turn override: while the driver manually turns, lateral is forced inactive (mode 0, + # all-zero signals) instead of winding path_angle into a stale command the PSCM can't cleanly + # reconcile on release (2-3 s re-engage dead time observed on Mach-E). See module docstring. + # Note: in CarController this attribute is shared with LateralCurvExt (same mixin instance) -- + # only one lateral strategy runs per frame, so a single detector serves both. + self.human_turn_detector = HumanTurnDetector() + self.angle_human_turn_active = False # read by carcontroller to force mode 0 + # Post-override stall blip state (see module constants). angle_stall_blip_active is read by + # carcontroller to force mode 0, exactly like angle_human_turn_active. + self.stall_blip_hold_s = 0.0 # accumulated deviation-clip-binding time toward a pulse + self.stall_blip_frames_left = 0 # remaining pulse frames; > 0 -> mode 0 on the wire + self.stall_blip_cooldown_s = 0.0 # re-arm delay after a pulse + self.stall_blip_count = 0 # pulses fired this stall episode + self.angle_stall_blip_active = False + self.press_timer_s = 0.0 # continuous steeringPressed time, for the hand-off blip + + def update_angle_params(self, params): + """Sets per-platform gain defaults and reads user angle-tuning params.""" + self._ensure_lateral_curv_initialized(self.CP) + fp = getattr(self.CP, 'carFingerprint', '') + if fp in _CANFD_BOF_CARS: + low, high = _GAIN_CANFD_BOF + elif fp in _CANFD_SUV_CARS: + low, high = _GAIN_CANFD_SUV + else: + low, high = _GAIN_CAN + self.path_angle_gain_lowC_highV = low + self.path_angle_gain_highC_highV = high + if params is not None and hasattr(params, "get"): + for attr, key, min_value, max_value in ( + ("low_speed_curv_factor", "FordLowSpeedFactor_ang", 0.5, 1.5), + ("high_speed_curv_factor", "FordHighSpeedFactor_ang", 0.5, 1.5), + ("user_dampening_factor", "FordHighSpeedDampening_ang", 0.25, 1.25), + ): + try: + raw = params.get(key, return_default=True) + if raw is not None and raw != b"": + setattr(self, attr, float(clip( + float(raw.decode("utf-8", errors="replace") if isinstance(raw, bytes) else raw), min_value, max_value))) + except Exception: + pass + try: + raw = params.get("lane_change_factor_high_ang", return_default=True) + if raw is not None and raw != b"": + self.lane_change_factor_high_ang = float(clip( + float(raw.decode("utf-8", errors="replace") if isinstance(raw, bytes) else raw), 0.85, 1.50)) + except Exception: + pass + + def update_angle_strategy(self, CC, CS, actuators, CP): + """ + Curvature from planner (+ optional predicted blend) → path_angle via ½·κ·d_ref. + c0 (path_offset) is always zero on the wire -- no centering trim in angle mode. c2 and c3 are zero. + Blended κ is not passed through Ford c2 rate / DBC limits (those target the curvature actuator). + """ + self._ensure_lateral_curv_initialized(CP) + + v_ego = float(CS.out.vEgoRaw) + d_ref = pscm_d_ref_m(v_ego) + + curvature_rate = 0.0 + path_offset = 0.0 + path_angle = 0.0 + ramp_type = 0 + lateral_uncertainty = 0.0 + precision = 1 + + if not CC.latActive: + self.path_angle_last = 0.0 + self.bp_path_angle_final = 0.0 + self.apply_curvature_last = 0.0 + self.bp_angle_rate_limited = False + self.bp_curvature_rate_limited = False + self.bp_curvature_deviation_limited = False + self.sim_curvature_last = 0.0 + # Publish the shadow curvature from the measured curvature while inactive. LKA keeps + # carrying angle_mode_engaged whenever angle mode is configured (independent of + # latActive), and ford.h latches the shadow from every LKA frame -- so the latched + # value must track reality here, not sit at a stale zero. Otherwise the first enabled + # LMC frame after (re-)engage races LKA's 33Hz latch against LMC's 20Hz enable bit and + # ford.h's deviation check compares a zero shadow against real measured curvature. + # (ford.h skips the check while steer_control_enabled is 0, so the value is free to + # follow the measurement during the inactive period itself.) + self.bp_kappa_cmd = self.get_current_curvature(CS) + self.human_turn_detector.reset() + self.angle_human_turn_active = False + self.stall_blip_hold_s = 0.0 + self.stall_blip_frames_left = 0 + self.stall_blip_cooldown_s = 0.0 + self.stall_blip_count = 0 + self.angle_stall_blip_active = False + self.press_timer_s = 0.0 + self.precision_type = 1 + return LateralResult( + apply_curvature=0.0, + curvature_rate=0.0, + path_offset=0.0, + path_angle=0.0, + ramp_type=0, + precision_type=1, + lateralUncertainty=0.0, + ) + + # Human-turn override: sustained driver press + large wheel angle → force lateral inactive + # (carcontroller drops mode to 0; all signals are zero on the wire) so path_angle can't wind + # into a stale command while the driver turns. Always on in angle mode (no param gate) -- the + # curv-suffixed human-turn toggle belongs to curvature mode's reset strategy, and the Mach-E + # PSCM re-engage stall this prevents is not something a user should be able to opt out of. + # On release, no jump seed: path_angle_last is 0, so the normal flow below ramps the command + # back in through the soft ROC -- generous at human-turn speeds, no panda bypass involved. + self.angle_human_turn_active = self.human_turn_detector.update( + True, CS.out.steeringPressed, CS.out.steeringAngleDeg) + if self.angle_human_turn_active: + self.path_angle_last = 0.0 + self.bp_path_angle_final = 0.0 + self.apply_curvature_last = 0.0 + self.bp_angle_rate_limited = False + self.bp_curvature_rate_limited = False + self.bp_curvature_deviation_limited = False + self.sim_curvature_last = 0.0 + # Truthful shadow during the override (mirrors the inactive path -- see the comment + # there): the driver is steering, so the honest command is the car's actual curvature, + # and the panda-latched shadow stays current for the re-engage frame. + self.bp_kappa_cmd = self.get_current_curvature(CS) + # Keep exit detection current so resume doesn't compare against a stale pre-turn value. + self._desired_curvature_last = float(actuators.curvature) + # A human turn ends any stall episode -- its own mode 0 does the PSCM reset job. That also + # covers the press so far: only press time accumulated AFTER the latch releases should earn + # a hand-off pulse. + self.stall_blip_hold_s = 0.0 + self.stall_blip_frames_left = 0 + self.stall_blip_cooldown_s = 0.0 + self.stall_blip_count = 0 + self.angle_stall_blip_active = False + self.press_timer_s = 0.0 + self.precision_type = 1 + return LateralResult( + apply_curvature=0.0, + curvature_rate=0.0, + path_offset=0.0, + path_angle=0.0, + ramp_type=0, + precision_type=1, + lateralUncertainty=0.0, + ) + + # Proactive hand-off blip: the falling edge of a sustained press earns an immediate mode-0 + # pulse (see _PRESS_BLIP_MIN_S) -- resets the PSCM's press-induced attenuation right at + # hand-off, while the car is straight and the command small, instead of waiting for the + # reactive stall detector below to watch the car miss the next curve first. + if CS.out.steeringPressed: + self.press_timer_s += _STEER_DT + else: + if (self.press_timer_s >= _PRESS_BLIP_MIN_S and self.stall_blip_cooldown_s <= 0.0 + and self.stall_blip_frames_left <= 0 + and abs(self.path_angle_last) < _BLIP_MAX_PATH_ANGLE): + self.stall_blip_frames_left = _STALL_BLIP_FRAMES + self.press_timer_s = 0.0 + + # Stall-blip pulse in progress: hold lateral inactive (mode 0, all-zero signals -- the same + # wire pattern as the human-turn override, no ford.h involvement) for _STALL_BLIP_FRAMES so the + # PSCM drops its post-override attenuation, then release; path_angle ramps back in from zero + # through the soft ROC exactly like a human-turn release. Detection lives at the end of the + # normal flow below. + if self.stall_blip_frames_left > 0: + self.stall_blip_frames_left -= 1 + self.angle_stall_blip_active = True + self.path_angle_last = 0.0 + self.bp_path_angle_final = 0.0 + self.apply_curvature_last = 0.0 + self.bp_angle_rate_limited = False + self.bp_curvature_rate_limited = False + self.bp_curvature_deviation_limited = False + self.sim_curvature_last = 0.0 + # Truthful shadow during the blip (see the inactive-path comment). + self.bp_kappa_cmd = self.get_current_curvature(CS) + self._desired_curvature_last = float(actuators.curvature) + self.precision_type = 1 + if self.stall_blip_frames_left <= 0: + self.stall_blip_cooldown_s = _STALL_COOLDOWN_S + return LateralResult( + apply_curvature=0.0, + curvature_rate=0.0, + path_offset=0.0, + path_angle=0.0, + ramp_type=0, + precision_type=1, + lateralUncertainty=0.0, + ) + self.angle_stall_blip_active = False + + self.precision_type = 1 + precision = 1 + LP = self.lp + desired_curvature = float(actuators.curvature) + + # Variable lookup time: t_base tracks planner pre-compensation; extra tapers on high speed and large curves. + # Cap liveDelay at 0.15s for VLT purposes. liveDelay can calibrate up to ~420ms on some runs, which inflates + # VLT to 0.6s and pushes the model lookahead 5m into the curve. At that depth the model sees full peak + # curvature, kappa_entering stays True, and the exit-biased blend is permanently disabled — causing the car + # to command max path_angle through the entire apex. 0.15s gives t_base ≤ 0.20s and VLT ≤ 0.33s, restoring + # the 2.8m lookahead that kept kappa_entering False at the apex in successful earlier runs. + _t_base = float(clip(self.sm['liveDelay'].lateralDelay, 0.1, 0.15)) + _DT_MDL + _speed_factor = float(interp(v_ego, [_VLT_V_LOW_MS, _VLT_V_HIGH_MS], [1.0, 0.0])) + # Direction-aware kappa factor: on curve ENTRY (model shows more curvature at t_base than planner now), + # keep full lookahead so pre-steering begins early. On exit/apex, taper by magnitude to prevent unwind. + _kappa_at_t_base = 0.0 + if self.model is not None and len(self.model.orientationRate.z) >= 17: + _curvatures_ref = np.array(self.model.orientationRate.z) / max(0.01, v_ego) + _kappa_at_t_base = abs(float(interp(_t_base, ModelConstants.T_IDXS, _curvatures_ref))) + _kappa_entering = _kappa_at_t_base > abs(desired_curvature) + if _kappa_entering: + _kappa_factor = 1.0 # curve deepening ahead: full extra lookahead for gradual entry + else: + _kappa_factor = float(interp(abs(desired_curvature), [_VLT_KAPPA_FULL, _VLT_KAPPA_TAPER], [1.0, 0.0])) + curvature_lookup_time = _t_base + self.vlt_extra_max * _speed_factor * _kappa_factor + self.bp_curvature_lookup_time = curvature_lookup_time + + predicted_curvature = 0.0 + if self.model is not None and len(self.model.orientationRate.z) >= 17: + curvatures = np.array(self.model.orientationRate.z) / max(0.01, v_ego) + predicted_curvature = float( + interp(curvature_lookup_time, ModelConstants.T_IDXS, curvatures) + ) + + b = float(self.path_angle_blend_ratio) + b = float(clip(b, 0.0, 1.0)) + + # Exit-biased blend: near the PSCM authority limit or while the planner is actively + # reducing curvature (exit detected), drop model prediction weight from 60% → ~15%. + # This lets the planner's natural unwind dominate instead of being diluted by a model + # prediction that still sees the curve (→ seg-14 slow unwind) or that snaps when its + # lookahead window crosses the curve exit (→ seg-17 snap + reverse PSCM hit). + # Normal gentle curves are unaffected: no PSCM limit, no falling desired → full b=0.60. + _pscm_lim = getattr(CS, 'lat_ctl_lim_stat', 0) + # In angle mode, LatCtlLim_D_Stat (→ lat_ctl_lim_stat) does not fire. + # Previously used angleState.saturated (CtrSat) as a proxy, but CtrSat fires whenever the car + # lags the commanded path_angle by > 2.5° — which happens during any normal curve entry. + # That caused a positive-feedback flat-line: under-steer → CtrSat → path_angle frozen → more under-steer. + # Use DBC-limit proximity instead: only block when path_angle is already near the ±0.5 rad CAN limits, + # which is the only condition where the anti-snap unwind rate cap makes physical sense. + _dbc_sat = (self.path_angle_last >= FORD_DBC_PATH_ANGLE_MAX * 0.90 or + self.path_angle_last <= FORD_DBC_PATH_ANGLE_MIN * 0.90) + _in_hard_sat = _pscm_lim >= 2 or _dbc_sat + # BluePilot: per-call delta threshold. The original 0.002 was authored 2026-05-07 on + # bp-sid-simple (9c3d000fd), which ran STEER_STEP=1 (true 100Hz, switched 2026-04-22) -- so it + # was tuned to trigger on planner unwind faster than 0.2 (1/m)/s. Scaled x5 here to restore + # that same real-world trigger rate on this branch's actual 20Hz cadence; unscaled it fired at + # 0.04 (1/m)/s, collapsing the model blend on mild straightening instead of genuine exits. + # Same bug class and fix as _PSCM_SAT_UNWIND_RATE and _soft_roc above. + _desired_falling = abs(desired_curvature) < abs(self._desired_curvature_last) - 0.010 + _on_exit_near_limit = not _kappa_entering and (_pscm_lim >= 1 or _in_hard_sat or _desired_falling) + b_blend = float(clip(b * 0.25, 0.0, 1.0)) if _on_exit_near_limit else b + requested_curvature = predicted_curvature * b_blend + desired_curvature * (1.0 - b_blend) + self._desired_curvature_last = desired_curvature + + if self.model is not None: + self.lane_change = self.model.meta.laneChangeState in (1, 2, 3) + else: + self.lane_change = False + + lane_change_factor = interp( + v_ego, self.lane_change_factor_bp, [self.lane_change_factor_low, self.lane_change_factor_high_ang] + ) + if self.lane_change and self.model is not None: + if self.model.meta.laneChangeDirection == 1 and requested_curvature < 0: + requested_curvature *= lane_change_factor + precision = 0 + elif self.model.meta.laneChangeDirection == 2 and requested_curvature > 0: + requested_curvature *= lane_change_factor + precision = 0 + self.precision_type = precision + + # Use planner / predicted κ directly for the κ → path_angle map; we are not sending κ on CAN. + kappa_cmd = float(requested_curvature) + + # BluePilot: clip kappa_cmd to current_curvature (measured, from yaw rate) +- CURVATURE_ERROR, + # mirroring lateral_curv_ext.py's apply_ford_curvature_limits_ext exactly (same formula, same + # v_ego > 9 gate, same CarControllerParams.CURVATURE_ERROR tolerance). Without this, kappa_cmd + # (and therefore path_angle, and the shadow_curvature sent to ford.h) can legitimately lead the + # measured curvature by more than ford.h's angle-error tolerance during normal curve entry/exit + # -- the shadow-curvature deviation check (ford_shadow_curvature_error_check) would then block + # routinely, not just on genuine pothole/override divergence. Curvature mode has always clipped + # here; this brings angle mode's actual steering intent in line with that proven behavior rather + # than only clipping the value reported to panda (which would make the check a no-op). + current_curvature = self.get_current_curvature(CS) + self.bp_curvature_deviation_limited = False + if v_ego > 9: + _kappa_cmd_pre_error_clip = kappa_cmd + kappa_cmd = float(clip(kappa_cmd, current_curvature - CarControllerParams.CURVATURE_ERROR, + current_curvature + CarControllerParams.CURVATURE_ERROR)) + # BluePilot: did this clip actually constrain kappa_cmd this frame (deviation from measured, + # not rate-of-change -- see carcontroller.py)? + self.bp_curvature_deviation_limited = bool(abs(kappa_cmd - _kappa_cmd_pre_error_clip) > 1e-9) + + lateral_uncertainty = 0.0 # no curvature-limit ladder until angle-mode torque display is defined + + + + # Speed-interpolated gain: at low speed both curves use 1.0; at high speed the params take effect. + self.low_gain_calc = interp( + v_ego, [13.5, 26.82], [1.0, (self.path_angle_gain_lowC_highV * self.user_dampening_factor)] + ) + self.high_gain_calc = interp(v_ego, [13.5, 26.82], [(1.30 * self.low_speed_curv_factor), (self.path_angle_gain_highC_highV * self.high_speed_curv_factor)]) + + # As the curve gets bigger, we will need a little boost to the signal to to not understeer + self.curvature_factor = interp(abs(kappa_cmd), [0.0007, 0.001], [self.low_gain_calc, self.high_gain_calc]) + + path_angle_calc = kappa_cmd * v_ego * self.curvature_factor + path_angle = path_angle_calc + + + # PSCM authority limit clamp. + # On CANFD Fords in angle mode, LatCtlLim_D_Stat does not fire, so _pscm_lim stays 0. + # _in_hard_sat (computed above) combines _pscm_lim >= 2 with _dbc_sat (path_angle near ±0.5 rad limit). + # LimitClose (_pscm_lim >= 1 only): block magnitude increases — exit-biased blend provides unwind. + # Hard saturation (_in_hard_sat): block increases AND rate-limit decreases to _PSCM_SAT_UNWIND_RATE. + # Without the decrease cap, model+planner drop path_angle at ~0.36 rad/s at a sharp apex, + # driving desired steering 30°+ ahead of actual while the PSCM is pinned, causing a snap when released. + if _in_hard_sat: + _last = self.path_angle_last + _last_mag = abs(_last) + _curr_mag = abs(path_angle) + if _curr_mag > _last_mag: # magnitude growing — block + path_angle = _last + elif _last_mag - _curr_mag > _PSCM_SAT_UNWIND_RATE: # decreasing too fast — rate-limit + _limited_mag = _last_mag - _PSCM_SAT_UNWIND_RATE + path_angle = float(_limited_mag if _last >= 0 else -_limited_mag) + elif _pscm_lim >= 1: # LimitClose (F150/non-angle-mode only): block increases only + path_angle = float(clip(path_angle, -abs(self.path_angle_last), abs(self.path_angle_last))) + + path_angle = min(FORD_DBC_PATH_ANGLE_MAX, max(FORD_DBC_PATH_ANGLE_MIN, path_angle)) + + # Soft ROC limit — unconditional, slightly tighter than ford.h, applied before the + # hardware bypass in ford.h is re-enabled. Lets us observe whether the limit would + # suppress control and tune it, while the PSCM still receives the clipped value. + # BluePilot: this strategy runs once per STEER_STEP (CarControllerParams.STEER_STEP=5), i.e. + # once every 5th 100Hz control tick = 20Hz, not every tick -- ported "verbatim from bp-sid-simple" + # (2026-06-13), which runs STEER_STEP=1 (true 100Hz, switched 2026-04-22). The y-values below are + # scaled x5 from the original [0.011, 0.011, 0.0085, 0.0018] to restore the same real-world rate + # (63/63/49/10 deg/s at v=9-10/15/25) on this branch's actual 20Hz cadence. See ford.h's + # FORD_PATH_ANGLE_LIMITS, which must mirror this scaling (x1.02 looser) to stay a true backstop. + _soft_roc = float(interp(v_ego, [9., 10., 15., 25.], [0.055, 0.055, 0.0425, 0.009])) + _path_angle_pre_roc = path_angle + path_angle = float(clip(path_angle, + self.path_angle_last - _soft_roc, + self.path_angle_last + _soft_roc)) + # BluePilot: did the soft ROC clip actually limit the path_angle we wanted to send this frame? + self.bp_angle_rate_limited = bool(abs(path_angle - _path_angle_pre_roc) > 1e-9) + + + # c0 always zero -- no centering trim in angle mode. + path_offset = 0.0 + + # Telemetry / state + self.bp_path_angle_gain_lowC_highV = self.path_angle_gain_lowC_highV + self.bp_path_angle_gain_highC_highV = self.path_angle_gain_highC_highV + self.bp_low_speed_curv_factor = self.low_speed_curv_factor + self.bp_high_speed_curv_factor = self.high_speed_curv_factor + self.path_angle_last = path_angle + self.bp_path_angle_final = path_angle + self.apply_curvature_last = 0.0 + # BluePilot: the error-clipped kappa path_angle was derived from -- carcontroller.py reads this + # as shadow_curvature for ford.h's angle-mode deviation check (see fordcan_ext.create_lka_msg). + # Not just telemetry: an actively-consumed value, unlike the removed *_kappa_cmd_raw stubs. + # While the driver is pressing (before the human-turn override latches), the clipped planner + # kappa can't follow the wheel: the driver moves the measured curvature faster than the + # deviation clip tracks it, so the shadow can exit ford.h's error band mid-curve -- the one + # in-drive lateral safety block observed across ~3h of replayed road-test routes was exactly + # this (driver fighting a sustained curve with the mode still enabled). The honest command + # during a press is the driver's actual curvature. + self.bp_kappa_cmd = self.get_current_curvature(CS) if CS.out.steeringPressed else kappa_cmd + + # BluePilot: would the equivalent curvature (kappa_cmd) have been rate-limited by curvature-mode's + # ROC (apply_std_steer_angle_limits)? kappa_cmd is already error-clipped above (same clip + # curvature mode applies), so only the rate-of-change portion remains to simulate here. + _equiv_curv_rl = apply_std_steer_angle_limits(kappa_cmd, self.sim_curvature_last, v_ego, + CS.out.steeringAngleDeg, CC.latActive, BP_ANGLE_LIMITS) + self.bp_curvature_rate_limited = bool(abs(_equiv_curv_rl - kappa_cmd) > 1e-9) + self.sim_curvature_last = float(_equiv_curv_rl) + + # Post-override stall detection (mechanism in the module constants' comment). Fires the mode-0 + # blip when, hands-free, desired curvature has led measured by more than 2x the deviation + # clip's tolerance while the clip was actually binding for _STALL_HOLD_S accumulated seconds. + # devLim flickers mid-stall (~63% duty on the diagnosis route), so off frames hold the + # accumulator rather than resetting it; a closed gap or driver press ends the episode. + self.stall_blip_cooldown_s = max(0.0, self.stall_blip_cooldown_s - _STEER_DT) + _stall_gap = desired_curvature - current_curvature + _stalled = (not CS.out.steeringPressed and not self.lane_change and v_ego > 9.0 + and abs(_stall_gap) > _STALL_GAP_MIN + and abs(desired_curvature) > abs(current_curvature)) + if _stalled: + if self.bp_curvature_deviation_limited and self.stall_blip_cooldown_s <= 0.0: + self.stall_blip_hold_s += _STEER_DT + if (self.stall_blip_hold_s >= _STALL_HOLD_S and self.stall_blip_count < _STALL_MAX_BLIPS + and abs(self.path_angle_last) < _BLIP_MAX_PATH_ANGLE): + self.stall_blip_frames_left = _STALL_BLIP_FRAMES + self.stall_blip_hold_s = 0.0 + self.stall_blip_count += 1 + else: + self.stall_blip_hold_s = 0.0 + if CS.out.steeringPressed or abs(_stall_gap) < 0.5 * _STALL_GAP_MIN: + self.stall_blip_count = 0 # episode over: the car is tracking again or the driver took it + + ramp_type = 2 + + + return LateralResult( + apply_curvature=0.0, + curvature_rate=curvature_rate, + path_offset=path_offset, + path_angle=path_angle, + ramp_type=ramp_type, + precision_type=self.precision_type, + lateralUncertainty=lateral_uncertainty, + ) diff --git a/opendbc_repo/opendbc/bluepilot_lateral/tests/reference/bpdev_trim.py.txt b/opendbc_repo/opendbc/bluepilot_lateral/tests/reference/bpdev_trim.py.txt new file mode 100644 index 0000000000..5eedebd79e --- /dev/null +++ b/opendbc_repo/opendbc/bluepilot_lateral/tests/reference/bpdev_trim.py.txt @@ -0,0 +1,203 @@ +""" +BluePilot: angle-mode "advanced lane positioning" -- a curvature-domain trim toward true +lane-line center (plus an optional user left/right bias), for use with path_angle-primary +control (``lateral_angle_ext.py``). + +Under curvature-primary control, lane positioning rode on a second DBC signal (path_angle as +a heading trim, c3) layered on top of curvature (c1, the primary). In angle mode, path_angle +IS the primary signal -- there is no separate trim slot on the wire. An earlier attempt ported +the old PID controller as an additive delta on the *final* path_angle value and it never tracked +lane center correctly: path_angle there is a derived quantity (``kappa_cmd * v_ego * +curvature_factor``), so an additive trim in that domain has the wrong (inverted) speed-dependence +for a lane-centering nudge, and it bypasses every limiter angle mode already applies to +``kappa_cmd`` (deviation clip, PSCM-saturation clamp, DBC clip, soft ROC). + +This class instead computes a small correction in the **curvature domain**, meant to be added to +``kappa_cmd`` before any of those limiters run -- so the correction automatically inherits all of +them, with no new safety-relevant code path. This mirrors where a GM-focused fork (StarPilot, +u/jc01rho -- ``selfdrive/controls/lib/drive_helpers.py::LaneCenteringController`` on +``feat/lane-centering-camera-offset``) places their own lane-centering trim: on the universal +``desired_curvature`` signal, upstream of any car-specific actuator conversion. The geometry here +(``raw_correction = 2*error / lookahead**2``) is the same ``y ~= 1/2 * kappa * x**2`` relation +BluePilot already uses for PSCM d_ref / path_angle elsewhere in this package, solved for the +curvature that would eliminate a lateral position error at the lookahead distance. + +**Model-position fallback (blend, not hard gate)**: mirrors ``lateral_curv_ext.py``'s +``path_offset`` blend of ``path_offset_position`` (the model's own predicted path -- a "no +correction" baseline) vs. ``path_offset_lanelines`` (the geometric lane center), weighted by a +laneline confidence score. The *target* we correct toward is that same blend here, so: + +- Good lane lines (confidence -> 1): target -> lane-line center + offset (full centering + bias). +- No/poor lane lines (confidence -> 0): target -> the model's own current path + offset, i.e. the + correction reduces to *just* the user's left/right bias riding on top of whatever the model + already wants to do -- it never goes to zero just because lane lines dropped out. This is the + case that matters on center-stripe-only roads with a curbed edge: there's no reliable lane line + to center between, but the user's bias should still nudge the car off the curb. + +Confidence uses the exact formula and breakpoints ``lateral_curv_ext.py`` already uses for +``laneline_confidence`` / ``min_laneline_confidence_bp`` (smooth width-tolerance + laneline probs, +not a hard cutoff) -- reusing an already-tuned, production formula instead of inventing a second one. +""" +import numpy as np +from numpy import interp + +# Laneline confidence blend -- ported verbatim from lateral_curv_ext.py's path_offset blend +# (laneline_width_tolerance / min_laneline_confidence_bp) so both control schemes agree on what +# "good lane lines" means. +_WIDTH_TOLERANCE_BP = (2.4, 2.8, 3.75, 4.25) # m - the floor is added from StarPilot +_WIDTH_TOLERANCE_V = (0.0, 0.81, 0.81, 0.59) # Adds StarPilot's low edge +_STD_TOLERANCE_BP = (0.3, 0.5) #0.3 is from StarPilot to define bad references +_STD_TOLERANCE_V = (0.81, 0.0) #0.81 is a known good value and allows it to fade to zero as std increases +_CONFIDENCE_BP = (0.6, 0.8) +_CONFIDENCE_V = (0.0, 1.0) + +# Speed ramp: reuses curvature-mode's already-tuned centering-authority envelope +# (LC_PID_speed_bp/v in lateral_curv_ext.py) instead of inventing a new one. +_SPEED_RAMP_BP = (0.0, 9.0, 15.0) # m/s +_SPEED_RAMP_V = (0.0, 0.0, 1.0) + +# Lookahead distance for the position-error sample, clipped to a sane range (m). +_LOOKAHEAD_MIN_M = 8.0 +_LOOKAHEAD_MAX_M = 35.0 + +# Hard safety ceiling on the raw correction magnitude (1/m) -- fixed, not a "feel" knob, same +# treatment as _PSCM_SAT_UNWIND_RATE / _soft_roc in lateral_angle_ext.py. +_MAX_RAW_CORRECTION = 0.004 + +# First-order smoothing time constant (s) -- avoids abrupt jumps in the trim. +_SMOOTH_TAU_S = 0.4 + +# Rate-of-change limit on the applied correction (1/m per 20 Hz tick), independent of the +# smoothing filter above. The filter alone still has its *fastest* slew immediately after a +# target jump -- its per-tick step is proportional to how far the target moved, so a large, +# sudden confidence swing (e.g. crossing into/out of a too-wide merge lane, or lane lines +# dropping out entirely while the model's own path and the laneline center disagree) can still +# produce a big single-tick correction change even though it's technically "smoothed". This caps +# that step explicitly, the same way path_angle's own soft ROC (lateral_angle_ext.py) and +# curvature mode's LC_path_angle_ROC (lateral_curv_ext.py) rate-limit their outputs. At this +# rate, crossing the full -_MAX_RAW_CORRECTION..+_MAX_RAW_CORRECTION span takes ~2.7s; a more +# typical confidence-transition jump (a fraction of that) resolves proportionally faster. +_CORRECTION_ROC_PER_TICK = 0.00015 + + +class LaneCenterTrim: + def __init__(self): + self._correction = 0.0 + + def reset(self) -> None: + self._correction = 0.0 + + def update(self, kappa_cmd: float, model, v_ego: float, enabled: bool, offset: float, + gain: float, lat_active: bool, lane_change: bool) -> float: + """Returns ``kappa_cmd``, nudged toward (lane-blend target + ``offset``) when active. + + ``offset`` (m): positive shifts the target right, negative left (same sign convention as + curvature mode's ``custom_path_offset_curv``). Applied whether or not lane lines are usable + -- see module docstring. + ``gain`` (0.0-1.0): user-tunable authority -- how much of the (already magnitude-clipped) + raw correction is actually applied. 0 disables the trim's effect without disabling detection. + + The applied correction is both exponentially smoothed (_SMOOTH_TAU_S) and rate-limited + (_CORRECTION_ROC_PER_TICK) -- see the constants above -- so a lane-line-confidence + transition (e.g. a merge lane too wide to be trusted, then narrowing back into range) eases + into its new target instead of snapping. + """ + if not enabled or not lat_active or lane_change or model is None: + self.reset() + return kappa_cmd + + speed_factor = float(interp(v_ego, _SPEED_RAMP_BP, _SPEED_RAMP_V)) + if speed_factor <= 0.0: + self.reset() + return kappa_cmd + if not (np.isfinite(offset) and np.isfinite(gain)): #stops not a number from getting to steering command; validation of number + self.reset() + return kappa_cmd + + valid, raw = self._raw_correction(model, v_ego, offset) + if not valid: + # Only true failure case now: model.position itself is unusable, so there's no baseline + # to offset from at all (see _raw_correction). Lane-line-only failures fall back to the + # model-position blend instead of landing here. + self.reset() + return kappa_cmd + + target = float(np.clip(raw, -_MAX_RAW_CORRECTION, _MAX_RAW_CORRECTION)) * float(np.clip(gain, 0.0, 1.0)) * speed_factor + alpha = 1.0 - np.exp(-0.05 / _SMOOTH_TAU_S) # BluePilot lateral tick is 20 Hz (dt=0.05s) + filtered = float(alpha * target + (1.0 - alpha) * self._correction) + # Rate-of-change limit -- see _CORRECTION_ROC_PER_TICK. Bounds the correction's own per-tick + # delta on top of the exponential filter above, so a lane-line-confidence transition can't + # snap the trim toward its new target in one or two frames. + self._correction = float(np.clip(filtered, self._correction - _CORRECTION_ROC_PER_TICK, + self._correction + _CORRECTION_ROC_PER_TICK)) + return kappa_cmd + self._correction + + @property + def correction(self) -> float: + """Telemetry: last applied correction (1/m).""" + return self._correction + + def _raw_correction(self, model, v_ego: float, offset: float) -> tuple[bool, float]: + try: + pos_x = np.asarray(model.position.x, dtype=float) + pos_y = np.asarray(model.position.y, dtype=float) + if pos_x.size < 2 or pos_x.size != pos_y.size: + return False, 0.0 + if not (np.isfinite(pos_x).all() and np.isfinite(pos_y).all() and np.all(np.diff(pos_x) > 0)): + return False, 0.0 + + lookahead = float(np.clip(v_ego, _LOOKAHEAD_MIN_M, _LOOKAHEAD_MAX_M)) + model_y = float(np.interp(lookahead, pos_x, pos_y)) + except (AttributeError, IndexError, TypeError, ValueError): + return False, 0.0 + + # Laneline contribution, blended in by confidence. scale=0 (model-position-only, i.e. just + # the user's offset bias) whenever lines are missing, low-confidence, or structurally bad -- + # see _laneline_blend for the confidence formula (ported from lateral_curv_ext.py). + scale, laneline_center_y = self._laneline_blend(model, lookahead) + target_y = model_y * (1.0 - scale) + laneline_center_y * scale + + error = (target_y + offset) - model_y + raw = 2.0 * error / (lookahead ** 2) + return True, float(raw) + + def _laneline_blend(self, model, lookahead: float) -> tuple[float, float]: + """Returns (scale, laneline_center_y). scale=0 whenever lanelines can't be trusted (missing, + low-probability, structurally invalid) -- center_y is unused/meaningless in that case since + it's weighted out by scale in the caller's blend.""" + try: + lane_lines = model.laneLines + probs = model.laneLineProbs + stds = model.laneLineStds # a line could exist but this verifies how sure it is of where it is + if len(lane_lines) < 3 or len(probs) < 3 or len(stds) < 3: + return 0.0, 0.0 + + left_x = np.asarray(lane_lines[1].x, dtype=float) + left_y = np.asarray(lane_lines[1].y, dtype=float) + right_x = np.asarray(lane_lines[2].x, dtype=float) + right_y = np.asarray(lane_lines[2].y, dtype=float) + if (left_x.size < 2 or left_x.size != left_y.size or + right_x.size < 2 or right_x.size != right_y.size): + return 0.0, 0.0 + if not (np.isfinite(left_x).all() and np.isfinite(left_y).all() and + np.isfinite(right_x).all() and np.isfinite(right_y).all()): + return 0.0, 0.0 + if not (np.all(np.diff(left_x) > 0) and np.all(np.diff(right_x) > 0)): + return 0.0, 0.0 + + left = float(np.interp(lookahead, left_x, left_y)) + right = float(np.interp(lookahead, right_x, right_y)) + width = right - left + + # Same confidence formula as lateral_curv_ext.py's path_offset blend: width-tolerance + # (penalizes implausibly wide/merging-looking detections) combined with per-line + # probability via min() -- a single missing/unreliable line (e.g. no line on the curb + # side, only a center stripe) drags confidence toward 0 on its own. + width_tolerance = float(np.interp(width, _WIDTH_TOLERANCE_BP, _WIDTH_TOLERANCE_V)) + std_tolerance = float(np.interp(max(float(stds[1]), float(stds[2])), _STD_TOLERANCE_BP, _STD_TOLERANCE_V)) #StarPilot stopped at 0.3, this fades the std through the table + confidence = min(float(probs[1]), float(probs[2]), width_tolerance, std_tolerance) #confidence is the weakest signal + scale = float(np.clip(np.interp(confidence, _CONFIDENCE_BP, _CONFIDENCE_V), 0.0, 1.0)) + center_y = 0.5 * (left + right) + return scale, center_y + except (AttributeError, IndexError, TypeError, ValueError): + return 0.0, 0.0 diff --git a/opendbc_repo/opendbc/bluepilot_lateral/tests/reference/builders.py.txt b/opendbc_repo/opendbc/bluepilot_lateral/tests/reference/builders.py.txt new file mode 100644 index 0000000000..296351f704 --- /dev/null +++ b/opendbc_repo/opendbc/bluepilot_lateral/tests/reference/builders.py.txt @@ -0,0 +1,377 @@ +""" +BluePilot Ford CAN message builder extensions. + +Provides extended versions of the stock fordcan.py message builders with additional +parameters for BluePilot features: + - Dynamic ramp_type and precision_type for lateral control + - Split brake_actuate / precharge_actuate for smoother deceleration + - BlueCruise cluster HUD status, TJA warnings, and hands-free messaging + - Independent left/right lane line logic for LKAS UI + - ICBM button injection for intelligent cruise button management + +Each function mirrors the stock fordcan.py function it replaces, with an extended +parameter list. When stock carcontroller.py is refactored, it will import these +functions instead of the stock versions. +""" + +from opendbc.car import structs +from opendbc.car.ford.fordcan import CanBus, calculate_lat_ctl2_checksum + +HUDControl = structs.CarControl.HUDControl + + +_BP_LKA_SHADOW_CURVATURE_SCALE = 1e-6 # 1/meter per raw unit, matches ford.h's decode + + +def create_lka_msg(packer, CAN: CanBus, lat_active: bool, hud_control, + angle_mode_engaged: bool = False, shadow_curvature: float = 0.0): + """ + Creates a CAN message for the Ford LKA Command. + + BluePilot extension: accepts lat_active and hud_control parameters for future + lane departure warning integration (unused so far). + + Also carries angle_mode_engaged + shadow_curvature packed into bits with no DBC signal mapped to + them -- confirmed unused (always 0, no cabana signal) on real F-150 dashcam routes. This message + is one openpilot itself originates every cycle, and ford_tx_hook already reads other fields + (LkaActvStats_D2_Req) directly out of these same bytes synchronously, in the same tx_hook call -- + no separate CAN ID, no RX round-trip needed (panda does not self-receive its own TX, confirmed + 2026-07-09 investigating a controlsMismatch caused by an earlier dedicated-message design). + + Byte layout (bits not covered by any Lane_Assist_Data1 DBC signal): + byte 4 bit 0: angle_mode_engaged + byte 4 bits 1-4: reserved (future bools) + byte 5-6: shadow_curvature (int16, scale 1e-6 1/m) + byte 7: reserved (future value) + Must match the decode in ford.h's FORD_Lane_Assist_Data1 tx_hook check exactly. + + Frequency is 33Hz. + """ + addr, dat, bus = packer.make_can_msg("Lane_Assist_Data1", CAN.main, {}) + dat = bytearray(dat) + + shadow_curvature_raw = int(round(shadow_curvature / _BP_LKA_SHADOW_CURVATURE_SCALE)) + shadow_curvature_raw = max(-32768, min(32767, shadow_curvature_raw)) & 0xFFFF + + dat[4] |= 1 if angle_mode_engaged else 0 + dat[5] = (shadow_curvature_raw >> 8) & 0xFF + dat[6] = shadow_curvature_raw & 0xFF + + return addr, bytes(dat), bus + + +def create_lat_ctl_msg(packer, CAN: CanBus, lat_active: bool, ramp_type: int, precision_type: int, + path_offset: float, path_angle: float, curvature: float, curvature_rate: float): + """ + Creates a CAN message for the Ford TJA/LCA Command (non-CAN FD). + + BluePilot extension: dynamic ramp_type and precision_type parameters. + Stock hardcodes ramp_type=0 (Slow) and precision_type=1 (Precise). + + Ford lane centering uses a third-order polynomial to describe the road centerline: + c0 (path_offset): lateral offset between vehicle and centerline (positive is right) + c1 (path_angle): heading angle between vehicle and centerline (positive is right) + c2 (curvature): curvature of the centerline (positive is left) + c3 (curvature_rate): rate of change of curvature + + Frequency is 20Hz. + """ + values = { + "LatCtlRng_L_Max": 0, # Unknown [0|126] meter + "HandsOffCnfm_B_Rq": 0, # Unknown: 0=Inactive, 1=Active [0|1] + "LatCtl_D_Rq": 1 if lat_active else 0, # Mode: 0=None, 1=ContinuousPathFollowing, 2=InterventionLeft, + # 3=InterventionRight, 4-7=NotUsed [0|7] + "LatCtlRampType_D_Rq": ramp_type, # Ramp speed: 0=Slow, 1=Medium, 2=Fast, 3=Immediate [0|3] + "LatCtlPrecision_D_Rq": precision_type, # Precision: 0=Comfortable, 1=Precise, 2/3=NotUsed [0|3] + "LatCtlPathOffst_L_Actl": path_offset, # Path offset [-5.12|5.11] meter + "LatCtlPath_An_Actl": path_angle, # Path angle [-0.5|0.5235] radians + "LatCtlCurv_NoRate_Actl": curvature_rate, # Curvature rate [-0.001024|0.00102375] 1/meter^2 + "LatCtlCurv_No_Actl": curvature, # Curvature [-0.02|0.02094] 1/meter + } + return packer.make_can_msg("LateralMotionControl", CAN.main, values) + + +def create_lat_ctl2_msg(packer, CAN: CanBus, mode: int, ramp_type: int, precision_type: int, + path_offset: float, path_angle: float, curvature: float, + curvature_rate: float, counter: int): + """ + Creates a CAN message for the Ford Lane Centering command (CAN FD). + + BluePilot extension: dynamic ramp_type and precision_type parameters. + Stock hardcodes ramp_type=0 (Slow) and precision_type=1 (Precise). + + This message replaces LateralMotionControl on CAN FD platforms and includes + counter and checksum fields. + + Frequency is 20Hz. + """ + values = { + "LatCtl_D2_Rq": mode, # Mode: 0=None, 1=PathFollowingLimitedMode, 2=PathFollowingExtendedMode, + # 3=SafeRampOut, 4-7=NotUsed [0|7] + "LatCtlRampType_D_Rq": ramp_type, # 0=Slow, 1=Medium, 2=Fast, 3=Immediate [0|3] + "LatCtlPrecision_D_Rq": precision_type, # 0=Comfortable, 1=Precise, 2/3=NotUsed [0|3] + "LatCtlPathOffst_L_Actl": path_offset, # [-5.12|5.11] meter + "LatCtlPath_An_Actl": path_angle, # [-0.5|0.5235] radians + "LatCtlCurv_No_Actl": curvature, # [-0.02|0.02094] 1/meter + "LatCtlCrv_NoRate2_Actl": curvature_rate, # [-0.001024|0.001023] 1/meter^2 + "HandsOffCnfm_B_Rq": 0, # 0=Inactive, 1=Active [0|1] + "LatCtlPath_No_Cnt": counter, # [0|15] + "LatCtlPath_No_Cs": 0, # [0|255] + } + + # Calculate checksum (reuse stock function) + dat = packer.make_can_msg("LateralMotionControl2", 0, values)[1] + values["LatCtlPath_No_Cs"] = calculate_lat_ctl2_checksum(mode, counter, dat) + + return packer.make_can_msg("LateralMotionControl2", CAN.main, values) + + +def create_acc_msg(packer, CAN: CanBus, long_active: bool, gas: float, accel: float, accel_pred: float, + stopping: bool, brake_actuate: bool, precharge_actuate: bool, v_ego_kph: float): + """ + Creates a CAN message for the Ford ACC Command. + + BluePilot extension: split brake control into brake_actuate and precharge_actuate + (each with independent hysteresis thresholds) for smoother deceleration. Also + accepts accel_pred as a parameter instead of hardcoding -5.0. + + Precharge engages slightly before full brake for smoother initial decel feel. + Both use configurable hysteresis to avoid binary on/off feel. + + Frequency is 50Hz. + """ + values = { + "AccBrkTot_A_Rq": accel, # Brake total accel request: [-20|11.9449] m/s^2 + "Cmbb_B_Enbl": 1 if long_active else 0, # Enabled: 0=No, 1=Yes + "AccPrpl_A_Rq": gas, # Acceleration request: [-5|5.23] m/s^2 + "AccPrpl_A_Pred": accel_pred, # Predicted accel (from carcontroller, not hardcoded) + "AccResumEnbl_B_Rq": 1 if long_active else 0, + "AccVeh_V_Trg": v_ego_kph, # Target speed: [0|255] km/h + "AccBrkPrchg_B_Rq": 1 if precharge_actuate else 0, # Pre-charge brake request (independent hysteresis) + "AccBrkDecel_B_Rq": 1 if brake_actuate else 0, # Deceleration request (independent hysteresis) + "AccStopStat_B_Rq": 1 if stopping else 0, + } + return packer.make_can_msg("ACCDATA", CAN.main, values) + + +def create_acc_ui_msg(packer, CAN: CanBus, CP, main_on: bool, enabled: bool, fcw_alert: bool, + standstill: bool, hud_control, stock_values: dict, send_hands_free_msg: bool, + send_ui: bool, send_bars: bool, tja_warn: int, tja_msg: int): + """ + Creates a CAN message for the Ford IPC adaptive cruise, FCW and TJA status. + + BluePilot extension: replaces stock show_distance_bars with explicit send_ui, + send_bars, and TJA parameters. Adds BlueCruise status 7 for hands-free cluster + UI. TJA warn/msg are set from DM state computation rather than stock passthrough. + + Stock functionality is maintained by passing through unmodified signals. + + Frequency is 5Hz. + """ + + # Tja_D_Stat: TJA status for cluster display + if enabled: + if hud_control.leftLaneDepart: + status = 3 # ActiveInterventionLeft + elif hud_control.rightLaneDepart: + status = 4 # ActiveInterventionRight + elif send_hands_free_msg: + status = 7 # BlueCruise UI in the cluster + else: + status = 2 # Active + elif main_on: + if hud_control.leftLaneDepart: + status = 5 # ActiveWarningLeft + elif hud_control.rightLaneDepart: + status = 6 # ActiveWarningRight + else: + status = 1 # Standby + elif standstill: + status = 0 # Off + else: + status = 1 # Standby + + values = {s: stock_values[s] for s in [ + "HaDsply_No_Cs", + "HaDsply_No_Cnt", + "AccStopStat_D_Dsply", # ACC stopped status message + "AccTrgDist2_D_Dsply", # ACC target distance + "AccStopRes_B_Dsply", + # TjaWarn_D_Rq and TjaMsgTxt_D_Dsply are set explicitly below, not passed through + "IaccLamp_D_Rq", # iACC status icon + "AccMsgTxt_D2_Rq", # ACC text + "FcwDeny_B_Dsply", # FCW disabled + "FcwMemStat_B_Actl", # FCW enabled setting + "AccTGap_B_Dsply", # ACC time gap display setting + "CadsAlignIncplt_B_Actl", + "AccFllwMde_B_Dsply", # ACC follow mode display setting + "CadsRadrBlck_B_Actl", + "CmbbPostEvnt_B_Dsply", # AEB event status + "AccStopMde_B_Dsply", # ACC stop mode display setting + "FcwMemSens_D_Actl", # FCW sensitivity setting + "FcwMsgTxt_D_Rq", # FCW text + "AccWarn_D_Dsply", # ACC warning + "FcwVisblWarn_B_Rq", # FCW visible alert + "FcwAudioWarn_B_Rq", # FCW audio alert + "AccTGap_D_Dsply", # ACC time gap + "AccMemEnbl_B_RqDrv", # ACC adaptive/normal setting + "FdaMem_B_Stat", # FDA enabled setting + ]} + + values.update({ + "Tja_D_Stat": status, # TJA status + "TjaWarn_D_Rq": tja_warn, # TJA warning (from DM state, not stock passthrough) + "TjaMsgTxt_D_Dsply": tja_msg, # TJA text (from DM state, not stock passthrough) + }) + + if CP.openpilotLongitudinalControl: + values.update({ + "AccStopStat_D_Dsply": 2 if standstill else 0, # Stopping status text + "AccMsgTxt_D2_Rq": 0, # ACC text + "AccTGap_B_Dsply": 1 if send_bars else 0, # Show time gap control UI + "AccFllwMde_B_Dsply": 1 if hud_control.leadVisible else 0, # Lead indicator + "AccStopMde_B_Dsply": 1 if standstill else 0, + "AccWarn_D_Dsply": 0, # ACC warning + "AccTGap_D_Dsply": hud_control.leadDistanceBars, # Time gap + }) + + # Forward FCW alert from IPMA + if fcw_alert: + values["FcwVisblWarn_B_Rq"] = 1 # FCW visible alert + values["FcwAudioWarn_B_Rq"] = 1 # FCW audio alert + + return packer.make_can_msg("ACCDATA_3", CAN.main, values) + + +def create_lkas_ui_msg(packer, CAN: CanBus, main_on: bool, enabled: bool, hands: int, + hud_control, stock_values: dict): + """ + Creates a CAN message for the Ford IPC IPMA/LKAS status. + + BluePilot extension: replaces stock steer_alert bool with hands int (0-3), + and uses independent left/right lane line status logic. + + hands values: + 0 = HandsOn + 1 = Level1 (warning without chime) + 2 = Level2 (warning with chime) + 3 = Suppressed + + LaActvStats_D_Dsply value table (left \\ right): + Right → | Intervene | Warning | Suppress | Available | None + Intervene | 24 | 19 | 14 | 9 | 4 + Warning | 23 | 18 | 13 | 8 | 3 + Suppress | 22 | 17 | 12 | 7 | 2 + Available | 21 | 16 | 11 | 6 | 1 + None | 20 | 15 | 10 | 5 | 0 + + Stock functionality is maintained by passing through unmodified signals. + + Frequency is 1Hz. + """ + + lines = 0 + + if hud_control is not None: + # Determine left lane status independently + if hud_control.leftLaneDepart: + left_status = 4 # Intervene (Yellow) + elif hud_control.leftLaneVisible: + left_status = 1 # Available + else: + left_status = 2 # Suppress + + # Determine right lane status independently + if hud_control.rightLaneDepart: + right_status = 20 # Intervene (Yellow) + elif hud_control.rightLaneVisible: + right_status = 5 # Available + else: + right_status = 10 # Suppress + + # Combine left and right lane status + lines = left_status + right_status + + values = {s: stock_values[s] for s in [ + "FeatConfigIpmaActl", + "FeatNoIpmaActl", + "PersIndexIpma_D_Actl", + "AhbcRampingV_D_Rq", # AHB ramping + "LaDenyStats_B_Dsply", # LKAS error + "CamraDefog_B_Req", # Windshield heater? + "CamraStats_D_Dsply", # Camera status + "DasAlrtLvl_D_Dsply", # DAS alert level + "DasStats_D_Dsply", # DAS status + "DasWarn_D_Dsply", # DAS warning + "AhbHiBeam_D_Rq", # AHB status + "Passthru_63", + "Passthru_48", + ]} + + values.update({ + "LaActvStats_D_Dsply": lines, # LKAS status (lane lines) [0|31] + "LaHandsOff_D_Dsply": hands, # 0=HandsOn, 1=Level1 (w/o chime), 2=Level2 (w/ chime), 3=Suppressed + }) + return packer.make_can_msg("IPMA_Data", CAN.main, values) + + +def create_button_msg(packer, bus: int, stock_values: dict, cancel=False, resume=False, + tja_toggle=False, icbm_button=None): + """ + Creates a CAN message for the Ford SCCM buttons/switches. + + BluePilot extension: adds icbm_button parameter for Intelligent Cruise Button + Management. When set, the specified CAN signal is set to 1 in the outgoing + message, enabling openpilot to emulate cruise button presses for speed adjustment. + + Args: + icbm_button: Optional string signal name (e.g., "CcAslButtnSetIncPress", + "CcAslButtnSetDecPress") for ICBM button injection. + + Frequency is 10Hz. + """ + values = {s: stock_values[s] for s in [ + "HeadLghtHiFlash_D_Stat", # SCCM Passthrough the remaining buttons + "TurnLghtSwtch_D_Stat", # SCCM Turn signal switch + "WiprFront_D_Stat", + "LghtAmb_D_Sns", + "AccButtnGapDecPress", + "AccButtnGapIncPress", + "AslButtnOnOffCnclPress", + "AslButtnOnOffPress", + "LaSwtchPos_D_Stat", + "CcAslButtnCnclResPress", + "CcAslButtnDeny_B_Actl", + "CcAslButtnIndxDecPress", + "CcAslButtnIndxIncPress", + "CcAslButtnOffCnclPress", + "CcAslButtnOnOffCncl", + "CcAslButtnOnPress", + "CcAslButtnResDecPress", + "CcAslButtnResIncPress", + "CcAslButtnSetDecPress", + "CcAslButtnSetIncPress", + "CcAslButtnSetPress", + "CcButtnOffPress", + "CcButtnOnOffCnclPress", + "CcButtnOnOffPress", + "CcButtnOnPress", + "HeadLghtHiFlash_D_Actl", + "HeadLghtHiOn_B_StatAhb", + "AhbStat_B_Dsply", + "AccButtnGapTogglePress", + "WiprFrontSwtch_D_Stat", + "HeadLghtHiCtrl_D_RqAhb", + ]} + + values.update({ + "CcAslButtnCnclPress": 1 if cancel else 0, # CC cancel button + "CcAsllButtnResPress": 1 if resume else 0, # CC resume button + "TjaButtnOnOffPress": 1 if tja_toggle else 0, # LCA/TJA toggle button + }) + + # ICBM button support — set the specified button signal to 1 + if icbm_button is not None: + values[icbm_button] = 1 + + return packer.make_can_msg("Steering_Data_FD1", bus, values) diff --git a/opendbc_repo/opendbc/bluepilot_lateral/tests/reference/fordcan.py.txt b/opendbc_repo/opendbc/bluepilot_lateral/tests/reference/fordcan.py.txt new file mode 100644 index 0000000000..2ac68c4427 --- /dev/null +++ b/opendbc_repo/opendbc/bluepilot_lateral/tests/reference/fordcan.py.txt @@ -0,0 +1,342 @@ +from opendbc.car import CanBusBase, structs + +HUDControl = structs.CarControl.HUDControl + + +class CanBus(CanBusBase): + def __init__(self, CP=None, fingerprint=None) -> None: + super().__init__(CP, fingerprint) + + @property + def main(self) -> int: + return self.offset + + @property + def radar(self) -> int: + return self.offset + 1 + + @property + def camera(self) -> int: + return self.offset + 2 + + +def calculate_lat_ctl2_checksum(mode: int, counter: int, dat: bytearray) -> int: + curvature = (dat[2] << 3) | ((dat[3]) >> 5) + curvature_rate = (dat[6] << 3) | ((dat[7]) >> 5) + path_angle = ((dat[3] & 0x1F) << 6) | ((dat[4]) >> 2) + path_offset = ((dat[4] & 0x3) << 8) | dat[5] + + checksum = mode + counter + for sig_val in (curvature, curvature_rate, path_angle, path_offset): + checksum += sig_val + (sig_val >> 8) + + return 0xFF - (checksum & 0xFF) + + +def create_lka_msg(packer, CAN: CanBus): + """ + Creates an empty CAN message for the Ford LKA Command. + + This command can apply "Lane Keeping Aid" maneuvers, which are subject to the PSCM lockout. + + Frequency is 33Hz. + """ + + return packer.make_can_msg("Lane_Assist_Data1", CAN.main, {}) + + +def create_lat_ctl_msg(packer, CAN: CanBus, lat_active: bool, path_offset: float, path_angle: float, curvature: float, + curvature_rate: float): + """ + Creates a CAN message for the Ford TJA/LCA Command. + + This command can apply "Lane Centering" maneuvers: continuous lane centering for traffic jam assist and highway + driving. It is not subject to the PSCM lockout. + + Ford lane centering command uses a third order polynomial to describe the road centerline. The polynomial is defined + by the following coefficients: + c0: lateral offset between the vehicle and the centerline (positive is right) + c1: heading angle between the vehicle and the centerline (positive is right) + c2: curvature of the centerline (positive is left) + c3: rate of change of curvature of the centerline + As the PSCM combines this information with other sensor data, such as the vehicle's yaw rate and speed, the steering + angle cannot be easily controlled. + + The PSCM should be configured to accept TJA/LCA commands before these commands will be processed. This can be done + using tools such as Forscan. + + Frequency is 20Hz. + """ + + values = { + "LatCtlRng_L_Max": 0, # Unknown [0|126] meter + "HandsOffCnfm_B_Rq": 0, # Unknown: 0=Inactive, 1=Active [0|1] + "LatCtl_D_Rq": 1 if lat_active else 0, # Mode: 0=None, 1=ContinuousPathFollowing, 2=InterventionLeft, + # 3=InterventionRight, 4-7=NotUsed [0|7] + "LatCtlRampType_D_Rq": 0, # Ramp speed: 0=Slow, 1=Medium, 2=Fast, 3=Immediate [0|3] + # Makes no difference with curvature control + "LatCtlPrecision_D_Rq": 1, # Precision: 0=Comfortable, 1=Precise, 2/3=NotUsed [0|3] + # The stock system always uses comfortable + "LatCtlPathOffst_L_Actl": path_offset, # Path offset [-5.12|5.11] meter + "LatCtlPath_An_Actl": path_angle, # Path angle [-0.5|0.5235] radians + "LatCtlCurv_NoRate_Actl": curvature_rate, # Curvature rate [-0.001024|0.00102375] 1/meter^2 + "LatCtlCurv_No_Actl": curvature, # Curvature [-0.02|0.02094] 1/meter + } + return packer.make_can_msg("LateralMotionControl", CAN.main, values) + + +def create_lat_ctl2_msg(packer, CAN: CanBus, mode: int, path_offset: float, path_angle: float, curvature: float, + curvature_rate: float, counter: int): + """ + Create a CAN message for the new Ford Lane Centering command. + + This message is used on the CAN FD platform and replaces the old LateralMotionControl message. It is similar but has + additional signals for a counter and checksum. + + Frequency is 20Hz. + """ + + values = { + "LatCtl_D2_Rq": mode, # Mode: 0=None, 1=PathFollowingLimitedMode, 2=PathFollowingExtendedMode, + # 3=SafeRampOut, 4-7=NotUsed [0|7] + "LatCtlRampType_D_Rq": 0, # 0=Slow, 1=Medium, 2=Fast, 3=Immediate [0|3] + "LatCtlPrecision_D_Rq": 1, # 0=Comfortable, 1=Precise, 2/3=NotUsed [0|3] + "LatCtlPathOffst_L_Actl": path_offset, # [-5.12|5.11] meter + "LatCtlPath_An_Actl": path_angle, # [-0.5|0.5235] radians + "LatCtlCurv_No_Actl": curvature, # [-0.02|0.02094] 1/meter + "LatCtlCrv_NoRate2_Actl": curvature_rate, # [-0.001024|0.001023] 1/meter^2 + "HandsOffCnfm_B_Rq": 0, # 0=Inactive, 1=Active [0|1] + "LatCtlPath_No_Cnt": counter, # [0|15] + "LatCtlPath_No_Cs": 0, # [0|255] + } + + # calculate checksum + dat = packer.make_can_msg("LateralMotionControl2", 0, values)[1] + values["LatCtlPath_No_Cs"] = calculate_lat_ctl2_checksum(mode, counter, dat) + + return packer.make_can_msg("LateralMotionControl2", CAN.main, values) + + +def create_acc_msg(packer, CAN: CanBus, long_active: bool, gas: float, accel: float, stopping: bool, brake_request, v_ego_kph: float): + """ + Creates a CAN message for the Ford ACC Command. + + This command can be used to enable ACC, to set the ACC gas/brake/decel values + and to disable ACC. + + Frequency is 50Hz. + """ + values = { + "AccBrkTot_A_Rq": accel, # Brake total accel request: [-20|11.9449] m/s^2 + "Cmbb_B_Enbl": 1 if long_active else 0, # Enabled: 0=No, 1=Yes + "AccPrpl_A_Rq": gas, # Acceleration request: [-5|5.23] m/s^2 + # No observed acceleration seen from this signal alone. During stock system operation, it appears to + # be the raw acceleration request (AccPrpl_A_Rq when positive, AccBrkTot_A_Rq when negative) + "AccPrpl_A_Pred": -5.0, # Acceleration request: [-5|5.23] m/s^2 + "AccResumEnbl_B_Rq": 1 if long_active else 0, + # No observed acceleration seen from this signal alone + "AccVeh_V_Trg": v_ego_kph, # Target speed: [0|255] km/h + # TODO: we may be able to improve braking response by utilizing pre-charging better + # When setting these two bits without AccBrkTot_A_Rq, an initial jerk is observed and car may be able to brake temporarily with AccPrpl_A_Rq + "AccBrkPrchg_B_Rq": 1 if brake_request else 0, # Pre-charge brake request: 0=No, 1=Yes + "AccBrkDecel_B_Rq": 1 if brake_request else 0, # Deceleration request: 0=Inactive, 1=Active + "AccStopStat_B_Rq": 1 if stopping else 0, + } + return packer.make_can_msg("ACCDATA", CAN.main, values) + + +def create_acc_ui_msg(packer, CAN: CanBus, CP, main_on: bool, enabled: bool, fcw_alert: bool, standstill: bool, + show_distance_bars: bool, hud_control, stock_values: dict): + """ + Creates a CAN message for the Ford IPC adaptive cruise, forward collision warning and traffic jam + assist status. + + Stock functionality is maintained by passing through unmodified signals. + + Frequency is 5Hz. + """ + + # Tja_D_Stat + if enabled: + if hud_control.leftLaneDepart: + status = 3 # ActiveInterventionLeft + elif hud_control.rightLaneDepart: + status = 4 # ActiveInterventionRight + else: + status = 2 # Active + elif main_on: + if hud_control.leftLaneDepart: + status = 5 # ActiveWarningLeft + elif hud_control.rightLaneDepart: + status = 6 # ActiveWarningRight + else: + status = 1 # Standby + else: + status = 0 # Off + + values = {s: stock_values[s] for s in [ + "HaDsply_No_Cs", + "HaDsply_No_Cnt", + "AccStopStat_D_Dsply", # ACC stopped status message + "AccTrgDist2_D_Dsply", # ACC target distance + "AccStopRes_B_Dsply", + "TjaWarn_D_Rq", # TJA warning + "TjaMsgTxt_D_Dsply", # TJA text + "IaccLamp_D_Rq", # iACC status icon + "AccMsgTxt_D2_Rq", # ACC text + "FcwDeny_B_Dsply", # FCW disabled + "FcwMemStat_B_Actl", # FCW enabled setting + "AccTGap_B_Dsply", # ACC time gap display setting + "CadsAlignIncplt_B_Actl", + "AccFllwMde_B_Dsply", # ACC follow mode display setting + "CadsRadrBlck_B_Actl", + "CmbbPostEvnt_B_Dsply", # AEB event status + "AccStopMde_B_Dsply", # ACC stop mode display setting + "FcwMemSens_D_Actl", # FCW sensitivity setting + "FcwMsgTxt_D_Rq", # FCW text + "AccWarn_D_Dsply", # ACC warning + "FcwVisblWarn_B_Rq", # FCW visible alert + "FcwAudioWarn_B_Rq", # FCW audio alert + "AccTGap_D_Dsply", # ACC time gap + "AccMemEnbl_B_RqDrv", # ACC adaptive/normal setting + "FdaMem_B_Stat", # FDA enabled setting + ]} + + values.update({ + "Tja_D_Stat": status, # TJA status + }) + + if CP.openpilotLongitudinalControl: + values.update({ + "AccStopStat_D_Dsply": 2 if standstill else 0, # Stopping status text + "AccMsgTxt_D2_Rq": 0, # ACC text + "AccTGap_B_Dsply": 1 if show_distance_bars else 0, # Show time gap control UI + "AccFllwMde_B_Dsply": 1 if hud_control.leadVisible else 0, # Lead indicator + "AccStopMde_B_Dsply": 1 if standstill else 0, + "AccWarn_D_Dsply": 0, # ACC warning + "AccTGap_D_Dsply": hud_control.leadDistanceBars, # Time gap + }) + + # Forwards FCW alert from IPMA + if fcw_alert: + values["FcwVisblWarn_B_Rq"] = 1 # FCW visible alert + + return packer.make_can_msg("ACCDATA_3", CAN.main, values) + + +def create_lkas_ui_msg(packer, CAN: CanBus, main_on: bool, enabled: bool, steer_alert: bool, hud_control, + stock_values: dict): + """ + Creates a CAN message for the Ford IPC IPMA/LKAS status. + + Show the LKAS status with the "driver assist" lines in the IPC. + + Stock functionality is maintained by passing through unmodified signals. + + Frequency is 1Hz. + """ + + # LaActvStats_D_Dsply + # R Intvn Warn Supprs Avail No + # L + # Intvn 24 19 14 9 4 + # Warn 23 18 13 8 3 + # Supprs 22 17 12 7 2 + # Avail 21 16 11 6 1 + # No 20 15 10 5 0 + # + # TODO: test suppress state + if enabled: + lines = 0 # NoLeft_NoRight + if hud_control.leftLaneDepart: + lines += 4 + elif hud_control.leftLaneVisible: + lines += 1 + if hud_control.rightLaneDepart: + lines += 20 + elif hud_control.rightLaneVisible: + lines += 5 + elif main_on: + lines = 0 + else: + if hud_control.leftLaneDepart: + lines = 3 # WarnLeft_NoRight + elif hud_control.rightLaneDepart: + lines = 15 # NoLeft_WarnRight + else: + lines = 30 # LA_Off + + hands_on_wheel_dsply = 1 if steer_alert else 0 + + values = {s: stock_values[s] for s in [ + "FeatConfigIpmaActl", + "FeatNoIpmaActl", + "PersIndexIpma_D_Actl", + "AhbcRampingV_D_Rq", # AHB ramping + "LaDenyStats_B_Dsply", # LKAS error + "CamraDefog_B_Req", # Windshield heater? + "CamraStats_D_Dsply", # Camera status + "DasAlrtLvl_D_Dsply", # DAS alert level + "DasStats_D_Dsply", # DAS status + "DasWarn_D_Dsply", # DAS warning + "AhbHiBeam_D_Rq", # AHB status + "Passthru_63", + "Passthru_48", + ]} + + values.update({ + "LaActvStats_D_Dsply": lines, # LKAS status (lines) [0|31] + "LaHandsOff_D_Dsply": hands_on_wheel_dsply, # 0=HandsOn, 1=Level1 (w/o chime), 2=Level2 (w/ chime), 3=Suppressed + }) + return packer.make_can_msg("IPMA_Data", CAN.main, values) + + +def create_button_msg(packer, bus: int, stock_values: dict, cancel=False, resume=False, tja_toggle=False): + """ + Creates a CAN message for the Ford SCCM buttons/switches. + + Includes cruise control buttons, turn lights and more. + + Frequency is 10Hz. + """ + + values = {s: stock_values[s] for s in [ + "HeadLghtHiFlash_D_Stat", # SCCM Passthrough the remaining buttons + "TurnLghtSwtch_D_Stat", # SCCM Turn signal switch + "WiprFront_D_Stat", + "LghtAmb_D_Sns", + "AccButtnGapDecPress", + "AccButtnGapIncPress", + "AslButtnOnOffCnclPress", + "AslButtnOnOffPress", + "LaSwtchPos_D_Stat", + "CcAslButtnCnclResPress", + "CcAslButtnDeny_B_Actl", + "CcAslButtnIndxDecPress", + "CcAslButtnIndxIncPress", + "CcAslButtnOffCnclPress", + "CcAslButtnOnOffCncl", + "CcAslButtnOnPress", + "CcAslButtnResDecPress", + "CcAslButtnResIncPress", + "CcAslButtnSetDecPress", + "CcAslButtnSetIncPress", + "CcAslButtnSetPress", + "CcButtnOffPress", + "CcButtnOnOffCnclPress", + "CcButtnOnOffPress", + "CcButtnOnPress", + "HeadLghtHiFlash_D_Actl", + "HeadLghtHiOn_B_StatAhb", + "AhbStat_B_Dsply", + "AccButtnGapTogglePress", + "WiprFrontSwtch_D_Stat", + "HeadLghtHiCtrl_D_RqAhb", + ]} + + values.update({ + "CcAslButtnCnclPress": 1 if cancel else 0, # CC cancel button + "CcAsllButtnResPress": 1 if resume else 0, # CC resume button + "TjaButtnOnOffPress": 1 if tja_toggle else 0, # LCA/TJA toggle button + }) + return packer.make_can_msg("Steering_Data_FD1", bus, values) diff --git a/opendbc_repo/opendbc/bluepilot_lateral/tests/reference/human.py.txt b/opendbc_repo/opendbc/bluepilot_lateral/tests/reference/human.py.txt new file mode 100644 index 0000000000..96f05760ee --- /dev/null +++ b/opendbc_repo/opendbc/bluepilot_lateral/tests/reference/human.py.txt @@ -0,0 +1,71 @@ +""" +BluePilot: shared manual-steering-override ("human turn") detection for Ford lateral control. + +Both Ford lateral strategies hand control back to the driver on a sustained manual turn, and the +detection is identical, so it lives here as one class instead of being copied into each mode. What +each mode DOES with the signal differs: curvature-primary (``lateral_curv_ext``) zeroes its command +(reset_steering + post-reset ramp); angle-primary (``lateral_angle_ext``) forces lateral inactive +(mode 0 on the wire) and ramps path_angle back in from zero through its soft ROC on release. +""" +from opendbc.car import DT_CTRL +from opendbc.car.ford.values import CarControllerParams + +# Require sustained hands-on AND a large angle (avoids resetting on small wheel nudges in a curve). +HUMAN_TURN_ANGLE_DEG = 45.0 +HUMAN_TURN_HOLD_S = 1.5 +# When the wheel was ALREADY past HUMAN_TURN_ANGLE_DEG at first contact -- lateral control had it +# turned mid-curve -- the angle condition is pre-satisfied, so a brief corrective nudge would latch +# after only HUMAN_TURN_HOLD_S of light contact and kill steering mid-curve. Require a longer hold +# there before reading it as an intentional takeover. Route 000000bd (2026-07-14) showed the +# discriminator holds on-road: all 7 deliberate turns began with the wheel below the threshold +# (driver wound it up through 45 deg); only mid-maneuver grabs/nudges began beyond it. +HUMAN_TURN_HOLD_PRETURNED_S = 3.0 +_STEER_DT = CarControllerParams.STEER_STEP * DT_CTRL # 20 Hz lateral tick + + +class HumanTurnDetector: + """Latches ``active`` once the driver holds real steering pressure AND ``|wheel angle|`` > + ``HUMAN_TURN_ANGLE_DEG`` continuously for ``HUMAN_TURN_HOLD_S`` — long enough to tell an + intentional turn from a brief nudge. ``just_released`` pulses True on the first frame after the + override clears, so a mode can re-seed its command as it re-engages. + + Call ``update`` once per lateral tick while control is active. Modes that want the timer to zero + on disengage call ``reset`` on their inactive path; modes that want it to persist simply stop + calling ``update`` (the timer holds its value). + """ + + def __init__(self): + self.hold_timer_s = 0.0 + self.active = False + self._active_last = False + self._pressed_last = False + self._press_started_preturned = False + + def update(self, enabled: bool, steering_pressed: bool, steering_angle_deg: float) -> bool: + self._active_last = self.active + # Was the wheel already past the angle threshold when this press began? If so the driver is + # touching a wheel that lateral control turned (mid-curve nudge), not driving a turn -- hold + # the longer HUMAN_TURN_HOLD_PRETURNED_S before latching. + if steering_pressed and not self._pressed_last: + self._press_started_preturned = abs(steering_angle_deg) > HUMAN_TURN_ANGLE_DEG + self._pressed_last = steering_pressed + if not enabled: + self.hold_timer_s = 0.0 + elif steering_pressed and abs(steering_angle_deg) > HUMAN_TURN_ANGLE_DEG: + self.hold_timer_s += _STEER_DT + else: + self.hold_timer_s = 0.0 + hold_req = HUMAN_TURN_HOLD_PRETURNED_S if self._press_started_preturned else HUMAN_TURN_HOLD_S + self.active = self.hold_timer_s >= hold_req + return self.active + + @property + def just_released(self) -> bool: + return self._active_last and not self.active + + def reset(self) -> None: + self.hold_timer_s = 0.0 + self.active = False + self._active_last = False + self._pressed_last = False + self._press_started_preturned = False diff --git a/opendbc_repo/opendbc/bluepilot_lateral/tests/reference/manifest.json b/opendbc_repo/opendbc/bluepilot_lateral/tests/reference/manifest.json new file mode 100644 index 0000000000..081e6f7204 --- /dev/null +++ b/opendbc_repo/opendbc/bluepilot_lateral/tests/reference/manifest.json @@ -0,0 +1,37 @@ +{ + "angle": { + "origin": "opendbc_repo/opendbc/sunnypilot/car/ford/lateral_angle_ext.py", + "sha256": "18fa5290edade52137c7c6705a2eb2d42c94d39d1fa649eae06b7828c68207b3", + "revision": "e1d051d7ba270261b4455068bd68f1a58db15a4a" + }, + "human": { + "origin": "opendbc_repo/opendbc/sunnypilot/car/ford/human_turn.py", + "sha256": "82735e348c5ce3e7b2c6a28ea3e298cca71ae8867433c270f7b54a9ee315ef37", + "revision": "e1d051d7ba270261b4455068bd68f1a58db15a4a" + }, + "builders": { + "origin": "opendbc_repo/opendbc/sunnypilot/car/ford/fordcan_ext.py", + "sha256": "65ad2114db7210371fc5de06de962c0e29ce396a651c1dd2d58b07a80555a1bf", + "revision": "e1d051d7ba270261b4455068bd68f1a58db15a4a" + }, + "fordcan": { + "origin": "opendbc_repo/opendbc/car/ford/fordcan.py", + "sha256": "0c35b8663afcaa3a58ab028a56f076c2c9f2f0296416c0abaf5905c674672956", + "revision": "e1d051d7ba270261b4455068bd68f1a58db15a4a" + }, + "values": { + "origin": "opendbc_repo/opendbc/sunnypilot/car/ford/values_ext.py", + "sha256": "74802d82314eaa27eb610810d2815d3da77003c4a1c62e0437e57e785ba25f52", + "revision": "e1d051d7ba270261b4455068bd68f1a58db15a4a" + }, + "starpilot_curvature_controller": { + "origin": "opendbc_repo/opendbc/car/ford/carcontroller.py", + "sha256": "c131d1d5f4231004e00f46968988b5d5f379ec22ef8c44d7f67ded8464344855", + "revision": "d2ae98eb3959c88011ed537e7cbc033d91fd3efa" + }, + "bpdev_trim": { + "origin": "opendbc_repo/opendbc/sunnypilot/car/ford/lane_center_trim.py", + "sha256": "1affc0abeaeeabaefca4741b0d75d8f249590c157340c5a9760a395d28f0a621", + "revision": "e22afa6be9b881fa784c92ebb316db47728a3d81" + } +} diff --git a/opendbc_repo/opendbc/bluepilot_lateral/tests/reference/starpilot_curvature_controller.py.txt b/opendbc_repo/opendbc/bluepilot_lateral/tests/reference/starpilot_curvature_controller.py.txt new file mode 100644 index 0000000000..9dd97a9ec2 --- /dev/null +++ b/opendbc_repo/opendbc/bluepilot_lateral/tests/reference/starpilot_curvature_controller.py.txt @@ -0,0 +1,329 @@ +import math +import numpy as np +from opendbc.can import CANPacker +from opendbc.car import ACCELERATION_DUE_TO_GRAVITY, Bus, DT_CTRL, apply_hysteresis, structs +from opendbc.car.ford import fordcan +from opendbc.car.ford.manual_turn import ManualTurnLatch +from opendbc.car.ford.aol import qualified as qualified_aol +from opendbc.car.ford.stock_cruise import FordStockCruiseButton, qualified as stock_switch_qualified +from opendbc.car.ford.curvature_preview import blend_curvature +from opendbc.car.ford import mache_can +from opendbc.car.ford.extended_classic_can import create_extended_classic_lat_ctl_msg +from opendbc.car.ford.classic_lateral import create_controller as create_classic_controller, bounded_command as classic_bounded_command +from opendbc.car.ford.generic_canfd_can import create_extended_canfd_msg +from opendbc.car.ford.generic_canfd_lateral import ( + GenericCanfdLateralController, qualified as generic_canfd_qualified, bounded_command as generic_canfd_bounded_command, +) +from opendbc.car.ford.mache_lateral import MachELateralController, FordLateralResult, bounded_command, qualified as mache_qualified +from opendbc.car.ford.values import CarControllerParams, FordFlags, FordSafetyFlags, CAR +from opendbc.car.interfaces import CarControllerBase, V_CRUISE_MAX + +LongCtrlState = structs.CarControl.Actuators.LongControlState +VisualAlert = structs.CarControl.HUDControl.VisualAlert + +def anti_overshoot(apply_curvature, apply_curvature_last, v_ego): + diff = 0.1 + tau = 5 # 5s smooths over the overshoot + dt = DT_CTRL * CarControllerParams.STEER_STEP + alpha = 1 - np.exp(-dt / tau) + + lataccel = apply_curvature * (v_ego ** 2) + last_lataccel = apply_curvature_last * (v_ego ** 2) + last_lataccel = apply_hysteresis(lataccel, last_lataccel, diff) + last_lataccel = alpha * lataccel + (1 - alpha) * last_lataccel + + output_curvature = last_lataccel / (max(v_ego, 1) ** 2) + + return float(np.interp(v_ego, [5, 10], [apply_curvature, output_curvature])) + + +def apply_creep_compensation(accel: float, v_ego: float, car_fingerprint: str, *, standstill: bool, stopping: bool) -> float: + if car_fingerprint == CAR.FORD_MUSTANG_MACH_E_MK1 and not (standstill and stopping): + return accel + creep_accel = np.interp(v_ego, [1., 3.], [0.6, 0.]) + creep_accel = np.interp(accel, [0., 0.2], [creep_accel, 0.]) + accel -= creep_accel + return float(accel) + + +def apply_brake_rate_limit(accel: float, gas: float, accel_last: float, v_ego: float, car_fingerprint: str, + *, stopping: bool, standstill: bool, fcw: bool) -> tuple[float, float]: + mild_mach_e_braking = ( + car_fingerprint == CAR.FORD_MUSTANG_MACH_E_MK1 and + -1.0 < gas < 0.0 and v_ego >= 5.0 and not (stopping or standstill or fcw) + ) + if mild_mach_e_braking: + accel = max(accel, min(accel_last, 0.0) - 2.0 * CarControllerParams.ACC_CONTROL_STEP * DT_CTRL) + gas = accel + else: + accel = max(accel, accel_last - 3.5 * CarControllerParams.ACC_CONTROL_STEP * DT_CTRL) + return float(accel), float(gas) + + +class CarController(CarControllerBase): + def __init__(self, dbc_names, CP): + super().__init__(dbc_names, CP) + self.packer = CANPacker(dbc_names[Bus.pt]) + self.CAN = fordcan.CanBus(CP) + + self.manual_turn = ManualTurnLatch() if CP.carFingerprint == CAR.FORD_MUSTANG_MACH_E_MK1 and not CP.flags & FordFlags.LKA_STEERING else None + self.stock_cruise_button = FordStockCruiseButton() + self.manual_turn_inputs = None + self.mache_lateral = MachELateralController(CP) if mache_qualified(CP) else None + self.mache_extended_announced = False + self.generic_canfd = generic_canfd_qualified(CP) + self.classic_lateral = GenericCanfdLateralController(CP) if self.generic_canfd else create_classic_controller(CP) + self.classic_extended_announced = False + self.classic_profile = any(s.safetyModel == structs.CarParams.SafetyModel.ford and + s.safetyParam & (FordSafetyFlags.CLASSIC_EXTENDED | FordSafetyFlags.GENERIC_CANFD_EXTENDED) for s in CP.safetyConfigs) + self.mache_profile = any(s.safetyModel == structs.CarParams.SafetyModel.ford and + s.safetyParam & FordSafetyFlags.MACH_E_EXTENDED for s in CP.safetyConfigs) + self.apply_curvature_last = 0 + self.anti_overshoot_curvature_last = 0 + self.accel = 0.0 + self.gas = 0.0 + self.brake_request = False + self.main_on_last = False + self.lkas_enabled_last = False + self.steer_alert_last = False + self.lead_distance_bars_last = None + self.distance_bar_frame = 0 + self.apply_lka_angle_last = 0. + self.apply_lka_curvature_last = 0. + + def update(self, CC, CS, now_nanos): + can_sends = [] + if (self.mache_lateral is not None or self.classic_lateral is not None) and self.manual_turn_inputs is not None: + self.manual_turn_inputs.update() + self.manual_turn_inputs.apply_blend_settings(self) + + actuators = CC.actuators + hud_control = CC.hudControl + + main_on = CS.out.cruiseState.available + steer_alert = hud_control.visualAlert in (VisualAlert.steerRequired, VisualAlert.ldw) + fcw_alert = hud_control.visualAlert == VisualAlert.fcw + + ### acc buttons ### + stock_cancel = False + stock_resume = False + if stock_switch_qualified(self.CP): + stock_cancel, stock_resume = self.stock_cruise_button.update( + bool(CS.buttons_stock_values["CcAslButtnCnclResPress"]), + CS.out.cruiseState.available, CS.out.cruiseState.enabled) + + if CC.cruiseControl.cancel: + can_sends.append(fordcan.create_button_msg(self.packer, self.CAN.camera, CS.buttons_stock_values, cancel=True)) + can_sends.append(fordcan.create_button_msg(self.packer, self.CAN.main, CS.buttons_stock_values, cancel=True)) + elif (stock_cancel or stock_resume) and (self.frame % CarControllerParams.BUTTONS_STEP) == 0: + can_sends.append(fordcan.create_button_msg( + self.packer, self.CAN.camera, CS.buttons_stock_values, cancel=stock_cancel, resume=stock_resume)) + can_sends.append(fordcan.create_button_msg( + self.packer, self.CAN.main, CS.buttons_stock_values, cancel=stock_cancel, resume=stock_resume)) + elif CC.cruiseControl.resume and (self.frame % CarControllerParams.BUTTONS_STEP) == 0: + can_sends.append(fordcan.create_button_msg(self.packer, self.CAN.camera, CS.buttons_stock_values, resume=True)) + can_sends.append(fordcan.create_button_msg(self.packer, self.CAN.main, CS.buttons_stock_values, resume=True)) + # if stock lane centering isn't off, send a button press to toggle it off + # the stock system checks for steering pressed, and eventually disengages cruise control + elif CS.acc_tja_status_stock_values["Tja_D_Stat"] != 0 and (self.frame % CarControllerParams.ACC_UI_STEP) == 0: + can_sends.append(fordcan.create_button_msg(self.packer, self.CAN.camera, CS.buttons_stock_values, tja_toggle=True)) + + ### lateral control ### + # send steer msg at 20Hz + if (self.frame % CarControllerParams.STEER_STEP) == 0 and self.CP.flags & FordFlags.LKA_STEERING: + # Preserve the stock LMC heartbeat without requesting lateral action. + can_sends.append(fordcan.create_lat_ctl_msg(self.packer, self.CAN, False, 0., 0., 0., 0., + stock_lmc=CS.lateral_motion_control)) + elif (self.frame % CarControllerParams.STEER_STEP) == 0 and self.mache_lateral is not None: + permission = getattr(self.manual_turn_inputs, "assist_permission", None) + self.mache_lateral.set_assist_permission(*(permission() if permission is not None else ((), False))) + inputs = self.manual_turn_inputs.lateral_snapshot(CS.out.vEgoRaw) if self.manual_turn_inputs is not None else None + if inputs is not None: + self.mache_lateral.set_inputs(*inputs) + else: + # Withdraw stale preview while retaining current actuator/manual-turn control. + self.mache_lateral.set_inputs(None, (), 0.2, self.manual_turn_inputs.enabled if self.manual_turn_inputs is not None else True) + previous = self.mache_lateral.curvature_last + previous_path_angle = self.mache_lateral.path_angle_last + demanded = self.mache_lateral.update(CC, CS, actuators) if self.mache_extended_announced else FordLateralResult() + lateral = bounded_command(self.mache_lateral, demanded, previous, CS.out.vEgoRaw, previous_path_angle) + self.mache_lateral_demand = demanded + self.apply_curvature_last = lateral.curvature + counter = (self.frame // CarControllerParams.STEER_STEP) % 0x10 + can_sends.append(mache_can.create_lat_ctl2_msg( + self.packer, self.CAN, int(lateral.active), lateral.ramp_type, lateral.precision_type, + -lateral.curvature, -lateral.curvature_rate, counter, -lateral.path_angle)) + elif (self.frame % CarControllerParams.STEER_STEP) == 0 and self.classic_lateral is not None: + inputs = self.manual_turn_inputs.lateral_snapshot(CS.out.vEgoRaw) if self.manual_turn_inputs is not None else None + if inputs is not None: + self.classic_lateral.set_inputs(*inputs) + else: + self.classic_lateral.set_inputs(None, (), 0.2, self.manual_turn_inputs.enabled if self.manual_turn_inputs is not None else True) + previous = self.classic_lateral.curvature_last + demanded = self.classic_lateral.update(CC, CS, actuators) if self.classic_extended_announced else FordLateralResult() + bound = generic_canfd_bounded_command if self.generic_canfd else classic_bounded_command + lateral = bound(self.classic_lateral, demanded, previous, CS.out.vEgoRaw, + -CS.out.yawRate / max(CS.out.vEgoRaw, 0.1)) + self.classic_lateral_demand = demanded + self.apply_curvature_last = lateral.curvature + if self.generic_canfd: + counter = (self.frame // CarControllerParams.STEER_STEP) % 0x10 + can_sends.append(create_extended_canfd_msg( + self.packer, self.CAN, lateral.active, lateral.ramp_type, lateral.precision_type, + -lateral.curvature, -lateral.curvature_rate, counter)) + else: + can_sends.append(create_extended_classic_lat_ctl_msg( + self.packer, self.CAN, lateral.active, lateral.ramp_type, lateral.precision_type, + -lateral.curvature, -lateral.curvature_rate)) + elif (self.frame % CarControllerParams.STEER_STEP) == 0: + lateral_active = CC.latActive and not self.mache_profile and not self.classic_profile + manual_turn = False + if self.manual_turn is not None and self.manual_turn_inputs is not None: + detection_enabled, lane_change, model_ready = self.manual_turn_inputs.update() + manual_turn = self.manual_turn.update(CC, CS, float(actuators.curvature), detection_enabled, lane_change, model_ready) + if manual_turn: + lateral_active = False + self.apply_curvature_last = 0. + # Bronco and some other cars consistently overshoot curv requests + # Apply some deadzone + smoothing convergence to avoid oscillations + if self.CP.carFingerprint in (CAR.FORD_BRONCO_SPORT_MK1, CAR.FORD_F_150_MK14): + self.anti_overshoot_curvature_last = anti_overshoot(actuators.curvature, self.anti_overshoot_curvature_last, CS.out.vEgoRaw) + apply_curvature = self.anti_overshoot_curvature_last + else: + apply_curvature = actuators.curvature + + # apply rate limits, curvature error limit, and clip to signal range + current_curvature = -CS.out.yawRate / max(CS.out.vEgoRaw, 0.1) + if self.manual_turn is not None and self.manual_turn_inputs is not None and lateral_active: + prediction = getattr(self.manual_turn_inputs, "preview_curvature", None) + preview = prediction(CS.out.vEgoRaw) if prediction is not None else None + if preview is not None: + apply_curvature = blend_curvature(apply_curvature, preview, current_curvature) + # No blending at low speed due to lack of torque wind-up and inaccurate current curvature + if CS.out.vEgoRaw > 9: + apply_curvature = float(np.clip(apply_curvature, current_curvature - CarControllerParams.CURVATURE_ERROR, + current_curvature + CarControllerParams.CURVATURE_ERROR)) + apply_curvature = CarControllerParams.CURVATURE_LIMITS.apply_limits(apply_curvature, self.apply_curvature_last, CS.out.vEgoRaw, + 0., lateral_active, CarControllerParams.STEER_STEP) + self.apply_curvature_last = 0. if manual_turn else apply_curvature + + if self.CP.flags & FordFlags.CANFD: + # TODO: extended mode + # Ford uses four individual signals to dictate how to drive to the car. Curvature alone (limited to 0.02 m^-1) + # can actuate the steering for a large portion of any lateral movements. However, in order to get further control on + # steer actuation, the other three signals are necessary. Ford controls vehicles differently than most other makes. + # A detailed explanation on ford control can be found here: + # https://www.f150gen14.com/forum/threads/introducing-bluepilot-a-ford-specific-fork-for-comma3x-openpilot.24241/#post-457706 + mode = 1 if lateral_active else 0 + counter = (self.frame // CarControllerParams.STEER_STEP) % 0x10 + can_sends.append(fordcan.create_lat_ctl2_msg(self.packer, self.CAN, mode, 0., 0., -self.apply_curvature_last, 0., counter)) + else: + can_sends.append(fordcan.create_lat_ctl_msg(self.packer, self.CAN, lateral_active, 0., 0., -self.apply_curvature_last, 0.)) + + # send lka msg at 33Hz + if (self.frame % CarControllerParams.LKA_STEP) == 0: + if self.CP.flags & FordFlags.LKA_STEERING: + source_age_ns = now_nanos - CS.lkas_available_ts_nanos + lka_active = (CC.latActive and CS.lkas_available and 0 <= source_age_ns <= 100_000_000 and + (CS.out.cruiseState.enabled or qualified_aol(self.CP, marked_only=True)) and + not CS.out.steerFaultTemporary and + not CS.out.vehicleSensorsInvalid) + if lka_active: + desired_angle = float(np.clip(actuators.steeringAngleDeg - CS.out.steeringAngleDeg, -5.8, 5.8)) + self.apply_lka_angle_last = float(np.clip(desired_angle, self.apply_lka_angle_last - 1., + self.apply_lka_angle_last + 1.)) + desired_curvature = -actuators.curvature + current_curvature = CS.out.yawRate / max(CS.out.vEgoRaw, 0.1) + if CS.out.vEgoRaw > 9.: + desired_curvature = float(np.clip(desired_curvature, current_curvature - CarControllerParams.CURVATURE_ERROR, + current_curvature + CarControllerParams.CURVATURE_ERROR)) + self.apply_lka_curvature_last = CarControllerParams.LKA_CURVATURE_LIMITS.apply_limits( + desired_curvature, self.apply_lka_curvature_last, CS.out.vEgoRaw, 0., True, CarControllerParams.LKA_STEP) + else: + self.apply_lka_angle_last = 0. + self.apply_lka_curvature_last = 0. + self.apply_curvature_last = -self.apply_lka_curvature_last + direction = 2 if self.apply_lka_angle_last >= 0. else 4 + can_sends.append(fordcan.create_lka_msg(self.packer, self.CAN, lka_active, self.apply_lka_angle_last, + direction, self.apply_lka_curvature_last, transit=True)) + elif self.mache_lateral is not None: + can_sends.append(mache_can.create_lka_msg(self.packer, self.CAN)) + self.mache_extended_announced = True + elif self.classic_lateral is not None: + can_sends.append(mache_can.create_lka_msg(self.packer, self.CAN)) + self.classic_extended_announced = True + else: + can_sends.append(fordcan.create_lka_msg(self.packer, self.CAN)) + + ### longitudinal control ### + # send acc msg at 50Hz + if self.CP.openpilotLongitudinalControl and (self.frame % CarControllerParams.ACC_CONTROL_STEP) == 0: + accel = actuators.accel + gas = accel + stopping = actuators.longControlState == LongCtrlState.stopping + + if CC.longActive: + accel = apply_creep_compensation(accel, CS.out.vEgo, self.CP.carFingerprint, + standstill=CS.out.standstill, stopping=stopping) + + accel, gas = apply_brake_rate_limit( + accel, gas, self.accel, CS.out.vEgo, self.CP.carFingerprint, + stopping=stopping, standstill=CS.out.standstill, + fcw=fcw_alert or CS.out.stockFcw or CS.out.stockAeb, + ) + + accel = float(np.clip(accel, CarControllerParams.ACCEL_MIN, CarControllerParams.ACCEL_MAX)) + gas = float(np.clip(gas, CarControllerParams.ACCEL_MIN, CarControllerParams.ACCEL_MAX)) + + # Both gas and accel are in m/s^2, accel is used solely for braking + if not CC.longActive or gas < CarControllerParams.MIN_GAS: + gas = CarControllerParams.INACTIVE_GAS + + # PCM applies pitch compensation to gas/accel, but we need to compensate for the brake/pre-charge bits + accel_due_to_pitch = 0.0 + if len(CC.orientationNED) == 3: + accel_due_to_pitch = math.sin(CC.orientationNED[1]) * ACCELERATION_DUE_TO_GRAVITY + + accel_pitch_compensated = accel + accel_due_to_pitch + if accel_pitch_compensated > 0.3 or not CC.longActive: + self.brake_request = False + elif accel_pitch_compensated < 0.0: + self.brake_request = True + + # TODO: look into using the actuators packet to send the desired speed + can_sends.append(fordcan.create_acc_msg(self.packer, self.CAN, CC.longActive, gas, accel, stopping, self.brake_request, v_ego_kph=V_CRUISE_MAX)) + + self.accel = accel + self.gas = gas + + ### ui ### + send_ui = (self.main_on_last != main_on) or (self.lkas_enabled_last != CC.latActive) or (self.steer_alert_last != steer_alert) + # send lkas ui msg at 1Hz or if ui state changes + if (self.frame % CarControllerParams.LKAS_UI_STEP) == 0 or send_ui: + can_sends.append(fordcan.create_lkas_ui_msg(self.packer, self.CAN, main_on, CC.latActive, steer_alert, hud_control, CS.lkas_status_stock_values)) + + # send acc ui msg at 5Hz or if ui state changes + if hud_control.leadDistanceBars != self.lead_distance_bars_last: + send_ui = True + self.distance_bar_frame = self.frame + + if (self.frame % CarControllerParams.ACC_UI_STEP) == 0 or send_ui: + show_distance_bars = self.frame - self.distance_bar_frame < 400 + can_sends.append(fordcan.create_acc_ui_msg(self.packer, self.CAN, self.CP, main_on, CC.latActive, + fcw_alert, CS.out.cruiseState.standstill, show_distance_bars, + hud_control, CS.acc_tja_status_stock_values)) + + self.main_on_last = main_on + self.lkas_enabled_last = CC.latActive + self.steer_alert_last = steer_alert + self.lead_distance_bars_last = hud_control.leadDistanceBars + + new_actuators = actuators.as_builder() + new_actuators.curvature = self.apply_curvature_last + if self.CP.flags & FordFlags.LKA_STEERING: + new_actuators.steeringAngleDeg = CS.out.steeringAngleDeg + self.apply_lka_angle_last + new_actuators.accel = self.accel + new_actuators.gas = self.gas + + self.frame += 1 + return new_actuators, can_sends diff --git a/opendbc_repo/opendbc/bluepilot_lateral/tests/reference/values.py.txt b/opendbc_repo/opendbc/bluepilot_lateral/tests/reference/values.py.txt new file mode 100644 index 0000000000..a748a6f97c --- /dev/null +++ b/opendbc_repo/opendbc/bluepilot_lateral/tests/reference/values.py.txt @@ -0,0 +1,125 @@ +""" +Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors. + +This file is part of sunnypilot and is licensed under the MIT License. +See the LICENSE.md file in the root directory for more details. +""" + +from collections import namedtuple + +from opendbc.car import structs +from opendbc.car.docs_definitions import CarParts, Device +from opendbc.car.ford.values import CAR +from opendbc.car.lateral import AngleSteeringLimits + +ButtonType = structs.CarState.ButtonEvent.Type +Button = namedtuple('Button', ['event_type', 'can_addr', 'can_msg', 'values']) + +# Ford cruise control buttons are in the Steering_Data_FD1 message (CAN ID 131) +# These signals are 1-bit flags: 1 = pressed, 0 = not pressed +# +# Note: Some buttons are combo buttons that emit multiple ButtonEvent types: +# - CcAslButtnSetIncPress emits both accelCruise (type 3) and setCruise (type 9) +# - CcAslButtnCnclResPress emits both cancel (type 5) and resumeCruise (type 10) +# +# There is also a separate CcAslButtnSetPress signal for the standalone "Set" button, +# but based on user mapping, setCruise is mapped to the combo button instead. +BUTTONS = [ + # Combo button: Set + Increase (emits accelCruise when enabled, setCruise when disabled) + Button(ButtonType.accelCruise, "Steering_Data_FD1", "CcAslButtnSetIncPress", [1]), + Button(ButtonType.setCruise, "Steering_Data_FD1", "CcAslButtnSetIncPress", [1]), + + # Combo button: Set + Decrease (emits decelCruise when enabled, setCruise when disabled) + Button(ButtonType.decelCruise, "Steering_Data_FD1", "CcAslButtnSetDecPress", [1]), + Button(ButtonType.setCruise, "Steering_Data_FD1", "CcAslButtnSetDecPress", [1]), + + # Combo button: Cancel/Resume (emits cancel when enabled, resumeCruise when disabled) + Button(ButtonType.cancel, "Steering_Data_FD1", "CcAslButtnCnclResPress", [1]), + Button(ButtonType.resumeCruise, "Steering_Data_FD1", "CcAslButtnCnclResPress", [1]), + + # Main cruise button (on/off toggle) + Button(ButtonType.mainCruise, "Steering_Data_FD1", "CcButtnOnOffPress", [1]), +] + + +class FordSafetyFlagsSP: + """Sunnypilot-level safety flags for Ford. + + Carried in CP_SP.safetyParam and delivered to the safety firmware as + current_safety_param_sp (the separate SP uint16, USB control 0xdf) -- NOT the main + safetyConfigs[].safetyParam. ford_init reads it with GET_FLAG(current_safety_param_sp, + ...), same pattern as Subaru STOP_AND_GO (subaru_common.h). Plain int constants, not + IntFlag: CP_SP.safetyParam must stay a plain int through capnp serialization in card. + """ + STEER_ANGLE_CURVATURE = 1 + + +# Geometry-table index for the steering-angle curvature measurement, packed into +# CP_SP.safetyParam bits 1-4 when STEER_ANGLE_CURVATURE is set. Must match the +# ford_pinion_geometry table in safety/modes/ford.h row for row (enforced by +# test_ford.py's geometry-consistency test against CarSpecs + calc_slip_factor). +# Index 0 is reserved as invalid: the firmware treats flag-set-but-no-index as feature +# off, so a half-configured param can never select the wrong geometry silently. +# FORD_EDGE_MK2 is deliberately absent: ALT_STEER_ANGLE platforms read a RELATIVE pinion +# angle (SteeringPinion_Data_Alt + learned offset) and lack the absolute measurement +# this feature needs -- the toggle no-ops there and yaw behavior is kept. +FORD_PINION_GEOMETRY_SHIFT = 1 +FORD_PINION_GEOMETRY_INDEX = { + CAR.FORD_BRONCO_SPORT_MK1: 1, + CAR.FORD_ESCAPE_MK4: 2, + CAR.FORD_ESCAPE_MK4_5: 3, + CAR.FORD_EXPEDITION_MK4: 4, + CAR.FORD_EXPLORER_MK6: 5, + CAR.FORD_FOCUS_MK4: 6, + CAR.FORD_F_150_LIGHTNING_MK1: 7, + CAR.FORD_F_150_MK14: 8, + CAR.FORD_MAVERICK_MK1: 9, + CAR.FORD_MONDEO_MK5: 10, + CAR.FORD_MUSTANG_MACH_E_MK1: 11, + CAR.FORD_RANGER_MK2: 12, +} + + +# BluePilot: Max curvature for steering command (m^-1), from DBC file limits +CURVATURE_MAX = 0.02 + +# BluePilot: Curvature rate limits — 3-point breakpoints for smoother lateral control. +# Upstream opendbc uses 2-point ([5, 25]) with more conservative values. +# These allow higher rates at low speed for responsiveness, lower rates at mid-speed +# for comfort, and very low rates at highway speed for stability. +# +# Control (Python) uses stricter windup than unwind so OP stays inside panda when apply_std +# picks the wrong table vs steer_angle_cmd_checks. Safety firmware uses looser symmetric ROCs +# (former “down” table for both up/down) — see ford.h FORD_LIMITS. +# Tests: test_ford.py ANGLE_RATE_* match ford.h, not the stricter BP_ANGLE_LIMITS up row. +_BP_ANGLE_RATE_UP = ([5, 16, 25], [0.0025, 0.0012, 0.00008]) +_BP_ANGLE_RATE_DOWN = ([5, 16, 25], [0.0025, 0.0014, 0.00018]) +BP_ANGLE_LIMITS = AngleSteeringLimits( + 0.02, # Max curvature for steering command, m^-1 + _BP_ANGLE_RATE_UP, + _BP_ANGLE_RATE_DOWN, +) + + +def apply_bp_device_mount(car_docs, CP): + """BluePilot: Select comma3 mount type per vehicle. + + Most Ford vehicles use the angled mount due to windshield angle. + Vehicles not in this list use the standard mount. + """ + from opendbc.car.ford.values import CAR, CarHarness, FordFlags + harness = CarHarness.ford_q4 if CP.flags & FordFlags.CANFD else CarHarness.ford_q3 + if CP.carFingerprint in ( + CAR.FORD_BRONCO_SPORT_MK1, + CAR.FORD_MAVERICK_MK1, + CAR.FORD_F_150_MK14, + CAR.FORD_F_150_LIGHTNING_MK1, + CAR.FORD_ESCAPE_MK4_5, + CAR.FORD_MUSTANG_MACH_E_MK1, + CAR.FORD_RANGER_MK2, + CAR.FORD_EDGE_MK2, + ): + car_docs.car_parts = CarParts([Device.threex_angled_mount, harness]) + else: + car_docs.car_parts = CarParts([Device.threex, harness]) + diff --git a/opendbc_repo/opendbc/bluepilot_lateral/tests/test_angle_core.py b/opendbc_repo/opendbc/bluepilot_lateral/tests/test_angle_core.py new file mode 100644 index 0000000000..71170ad0c6 --- /dev/null +++ b/opendbc_repo/opendbc/bluepilot_lateral/tests/test_angle_core.py @@ -0,0 +1,213 @@ +"""Pure angle host-independent finite inputs and explicit override/blip reset.""" +import math +import unittest +from opendbc.bluepilot_lateral.core.angle import AngleController, Inputs, Command +from opendbc.bluepilot_lateral.params import limits +from opendbc.bluepilot_lateral.tests import reference +from opendbc.bluepilot_lateral.hosts.starpilot import CLASSIC, CANFD, TRUCKS +from opendbc.bluepilot_lateral.can.ford import lateral, lka +from opendbc.can import CANPacker +from types import SimpleNamespace +from dataclasses import replace +from opendbc.bluepilot_lateral.core.trim import LaneCenterTrim, LaneGeometry, TrimConfig +from opendbc.bluepilot_lateral.hosts.starpilot import model_geometry +from openpilot.selfdrive.modeld.constants import ModelConstants + + +class TestAngleCore(unittest.TestCase): + def test_finite_permission_and_inactive_state_clear_pending_history(self): + for value in (math.nan, math.inf, -math.inf): + for field in ("speed", "desired_curvature", "measured_curvature", "steering_angle", "lateral_delay"): + core = AngleController() + inputs = Inputs(active=True, speed=15., measured_curvature=0., desired_curvature=.001) + self.assertEqual(core.step(replace(inputs, **{field: value})), Command()) + core = AngleController() + for _ in range(10): + self.assertTrue(core.step(Inputs(True, 15., 0., .001)).active) + self.assertEqual(core.step(Inputs(False, 15., 0., .001)), Command()) + self.assertEqual(core.path_last, 0.) + + def test_actual_equivalent_jerk_and_cap_both_signs_and_speeds(self): + for speed in (1., 9., 10., 15., 25., 40., 55.): + for direction in (-1, 1): + core = AngleController(low_gain=.95, high_gain=.95) + previous = 0. + for _ in range(60): + command = core.step(Inputs(True, speed, 0., direction * .002)) + if command.active: + equivalent = command.path_angle / speed / limits.GAIN_MIN + self.assertLessEqual(abs(equivalent), min(limits.CURVATURE_MAX, limits.LATERAL_ACCEL / max(speed, 1.) ** 2)) + self.assertLessEqual(abs(equivalent - previous), limits.LATERAL_JERK / max(speed - 1., 1.) ** 2 * .05) + previous = equivalent + else: + previous = 0. + + def test_human_turn_and_release_blips_are_neutral_then_bounded(self): + core = AngleController() + for _ in range(61): + result = core.step(Inputs(True, 15., 0., .001, steering_pressed=True, steering_angle=60.)) + self.assertFalse(result.active) + self.assertEqual(result.path_angle, 0.) + core = AngleController() + for _ in range(12): + core.step(Inputs(True, 15., 0., .001, steering_pressed=True)) + for _ in range(6): + self.assertEqual(core.step(Inputs(True, 15., 0., .001)), Command()) + resumed = core.step(Inputs(True, 15., 0., .001)) + self.assertTrue(resumed.active) + self.assertLess(abs(resumed.path_angle), .02) + + def test_pinned_bp7_pure_angle_and_actual_control_bytes_with_documented_limits(self): + builders = reference.builders() + bus = SimpleNamespace(main=0) + differences = set() + packer = CANPacker("ford_lincoln_base_pt") + for identity in sorted(CLASSIC | CANFD): + gains = (.95, .95) if identity in TRUCKS else ((1., 1.05) if identity in CANFD else (1., 1.15)) + for speed in (5., 15., 25., 40.): + for direction in (-1, 1): + adapted, upstream = AngleController(low_gain=gains[0], high_gain=gains[1]), reference.Angle(identity) + for tick in range(60): + # Tiny tracking curves stay clear of all intentional envelope changes. + desired = direction * .00005 * (1. + .2 * math.sin(tick / 8.)) + inputs = Inputs(True, speed, desired, desired, + yaw_predictions=tuple(desired * speed for _ in ModelConstants.T_IDXS), + time_indices=tuple(ModelConstants.T_IDXS), lateral_delay=.15, + lane_change=tick >= 30, lane_direction=1 if direction < 0 else 2) + result = upstream.step(inputs) + command = adapted.step(inputs) + self.assertTrue(command.active) + self.assertAlmostEqual(command.path_angle, result.path_angle, places=12) + self.assertEqual(command.precision, result.precision_type) + fd = identity in CANFD + actual = lateral(packer, 0, command, canfd=fd, counter=tick % 16) + expected = (builders["create_lat_ctl2_msg"](packer, bus, 1, result.ramp_type, result.precision_type, + 0., -result.path_angle, 0., 0., tick % 16) if fd else + builders["create_lat_ctl_msg"](packer, bus, True, result.ramp_type, result.precision_type, + 0., -result.path_angle, 0., 0.)) + self.assertEqual(actual, expected) + old_shadow = builders["create_lka_msg"](packer, bus, True, SimpleNamespace(), True, upstream.controller.bp_kappa_cmd) + new_shadow = lka(packer, 0, command.shadow_curvature, tick % 8) + # bp7 packs an empty body as raw zeros; the strict native contract requires physical zeros. + self.assertEqual(old_shadow[1][:4], b"\x00\x00\x00\x00") + self.assertEqual(new_shadow[1][:4], b"\x00\x80\x08\x00") + differences.update(("physical_neutral_dbc_offsets", "versioned_side_channel")) + # Aggressive entry demonstrates the required stricter native-equivalent derivative/cap. + adapted, upstream = AngleController(low_gain=gains[0], high_gain=gains[1]), reference.Angle(identity) + previous = 0. + for _tick in range(8): + inputs = Inputs(True, speed, 0., direction * .02, + yaw_predictions=tuple(direction * .02 * speed for _ in ModelConstants.T_IDXS), + time_indices=tuple(ModelConstants.T_IDXS), lateral_delay=.15) + result, command = upstream.step(inputs), adapted.step(inputs) + if command.active: + equivalent = command.path_angle / max(speed, .1) / limits.GAIN_MIN + self.assertLessEqual(abs(equivalent), min(limits.CURVATURE_MAX, limits.LATERAL_ACCEL / max(speed, 1.) ** 2)) + self.assertLessEqual(abs(equivalent - previous), limits.LATERAL_JERK / max(speed - 1., 1.) ** 2 * .05) + previous = equivalent + if abs(command.path_angle - result.path_angle) > 1e-7: + differences.add("native_cap_jerk_deviation_packing") + else: + previous = 0. + self.assertEqual(differences, {"physical_neutral_dbc_offsets", "versioned_side_channel", "native_cap_jerk_deviation_packing"}) + + +class TestAngleTrim(unittest.TestCase): + @staticmethod + def geometry(direction=1., *, width=3.3, probability=.9): + xs = (0., 10., 40.) + return LaneGeometry(xs, (direction * .3,) * 3, xs, (-width / 2,) * 3, + xs, (width / 2,) * 3, (probability,) * 2, (.1,) * 2, True) + + @staticmethod + def model(g): + return SimpleNamespace(position=SimpleNamespace(x=g.position_x, y=g.position_y), + laneLines=[SimpleNamespace(x=(), y=()), SimpleNamespace(x=g.left_x, y=g.left_y), + SimpleNamespace(x=g.right_x, y=g.right_y)], + laneLineProbs=[0., *g.probabilities], laneLineStds=[0., *g.standard_deviations]) + + def test_disabled_trim_preserves_all_eleven_default_commands_and_wire_bytes(self): + packer = CANPacker("ford_lincoln_base_pt") + for identity in sorted(CLASSIC | CANFD): + low, high = (.95, .95) if identity in TRUCKS else ((1., 1.05) if identity in CANFD else (1., 1.15)) + for speed in (5., 15., 25., 40.): + for direction in (-1, 1): + baseline, supplied = AngleController(low_gain=low, high_gain=high), AngleController(low_gain=low, high_gain=high) + self.assertFalse(supplied.trim_config.enabled) + for tick in range(30): + i = Inputs(True, speed, 0., direction * .0002) + a, b = baseline.step(i), supplied.step(replace(i, geometry=self.geometry(direction))) + self.assertEqual(a, b) + self.assertEqual(lateral(packer, 0, a, canfd=identity in CANFD, counter=tick % 16), + lateral(packer, 0, b, canfd=identity in CANFD, counter=tick % 16)) + self.assertEqual(lka(packer, 0, a.shadow_curvature, tick % 8), lka(packer, 0, b.shadow_curvature, tick % 8)) + self.assertEqual(supplied.trim.correction, 0.) + + def test_fresh_geometry_matches_exact_currentdev_trim_and_model_fallback(self): + for speed in (5., 9., 12., 15., 25., 40.): + for direction in (-1, 1): + adapted, upstream = LaneCenterTrim(), reference.trim()() + config = TrimConfig(True, direction * .1, .25) + for tick in range(90): + g = self.geometry(direction, width=3.3 if tick < 30 or tick >= 60 else 1.5, + probability=.9 if tick < 60 else .3) + actual = adapted.update(.0001, speed, g, config, active=True, lane_change=False) + expected = upstream.update(.0001, self.model(g), speed, True, config.offset_m, config.gain, True, False) + self.assertAlmostEqual(actual, expected, places=14) + self.assertAlmostEqual(adapted.correction, upstream.correction, places=14) + projected = model_geometry(self.model(g), fresh=True) + self.assertEqual(projected, g) + self.assertIsNone(model_geometry(self.model(g), fresh=False)) + + def test_invalid_stale_driver_and_lane_change_suppress_trim_and_reset_history(self): + original = self.geometry() + config = TrimConfig(True, 0., .25) + for geometry in (replace(original, fresh=False), replace(original, position_x=(0., 0., 40.)), + replace(original, position_y=(0., math.nan, 0.)), replace(original, position_y=(0.,)), None): + trim = LaneCenterTrim() + self.assertNotEqual(trim.update(0., 15., original, config, active=True, lane_change=False), 0.) + self.assertEqual(trim.update(.001, 15., geometry, config, active=True, lane_change=False), .001) + self.assertEqual(trim.correction, 0.) + for changes in ({"active": False}, {"lane_change": True}, {"steering_pressed": True}): + trim = LaneCenterTrim() + trim.update(0., 15., original, config, active=True, lane_change=False) + flags = dict(active=True, lane_change=False, steering_pressed=False) + flags.update(changes) + self.assertEqual(trim.update(.001, 15., original, config, **flags), .001) + self.assertEqual(trim.correction, 0.) + for invalid in (TrimConfig(True, math.nan, .25), TrimConfig(True, 0., math.inf), TrimConfig(True, .6, .25)): + self.assertEqual(LaneCenterTrim().update(.001, 15., original, invalid, active=True, lane_change=False), .001) + # Bad lane-only references fall back to the model+offset, not a stale lane correction. + bad = replace(original, probabilities=(math.nan, .9)) + without_lines = replace(original, left_x=(), right_x=()) + a, b = LaneCenterTrim(), LaneCenterTrim() + self.assertEqual(a.update(0., 15., bad, TrimConfig(True, .1, .25), active=True, lane_change=False), + b.update(0., 15., without_lines, TrimConfig(True, .1, .25), active=True, lane_change=False)) + core = AngleController(trim_config=config) + core.step(Inputs(True, 15., 0., 0., geometry=original)) + self.assertNotEqual(core.trim.correction, 0.) + self.assertEqual(core.step(Inputs(False, 15., 0., 0., geometry=original)), Command()) + self.assertEqual(core.trim.correction, 0.) + + def test_enabled_trim_remains_inside_final_curvature_jerk_and_shadow_bounds(self): + for speed in (9., 10., 15., 25., 40.): + for direction in (-1, 1): + core = AngleController(low_gain=.95, high_gain=.95, trim_config=TrimConfig(True, direction * .5, 1.)) + previous, previous_trim, previous_active = 0., 0., False + for _tick in range(100): + command = core.step(Inputs(True, speed, 0., direction * .02, geometry=self.geometry(-direction))) + if command.active and previous_active: + self.assertLessEqual(abs(core.trim.correction - previous_trim), .00015 + 1e-12) + previous_trim, previous_active = core.trim.correction, command.active + if command.active: + equivalent = command.path_angle / speed / limits.GAIN_MIN + self.assertLessEqual(abs(equivalent), min(limits.CURVATURE_MAX, limits.LATERAL_ACCEL / max(speed, 1.) ** 2)) + self.assertLessEqual(abs(equivalent - previous), limits.LATERAL_JERK / max(speed - 1., 1.) ** 2 * .05) + self.assertLessEqual(abs(command.shadow_curvature), min(limits.CURVATURE_MAX, limits.LATERAL_ACCEL / max(speed, 1.) ** 2)) + # Shadow comes from the final path; no independent trim/shadow command can bypass bounds. + ratio = command.path_angle / (speed * command.shadow_curvature) if command.shadow_curvature else 1. + self.assertTrue(limits.GAIN_MIN - 1e-12 <= ratio <= limits.GAIN_MAX + 1e-12) + previous = equivalent + else: + previous = 0. + self.assertEqual(core.trim.correction, 0.) diff --git a/opendbc_repo/opendbc/bluepilot_lateral/tests/test_angle_native.py b/opendbc_repo/opendbc/bluepilot_lateral/tests/test_angle_native.py new file mode 100644 index 0000000000..0e2cbfc4cf --- /dev/null +++ b/opendbc_repo/opendbc/bluepilot_lateral/tests/test_angle_native.py @@ -0,0 +1,307 @@ +"""Public packed angle/native boundaries; uses the runner-selected safety library.""" +from opendbc.bluepilot_lateral.core.angle import AngleController, Inputs, Command +from opendbc.bluepilot_lateral.can.ford import lateral, lka, checksum4 +from opendbc.safety.tests import common +from opendbc.safety.tests.libsafety import libsafety_py +from opendbc.car.structs import CarParams +from opendbc.can import CANPacker + + +class TestFordAngleNative(common.SafetyTestBase): + DBC = "ford_lincoln_base_pt" + SAFETY_MODEL = CarParams.SafetyModel.ford + SAFETY_PARAM = 128 + + def setUp(self): + super().setUp() + self.debug = self.safety.set_safety_hooks(CarParams.SafetyModel.allOutput, 0) == 0 + self.safety.set_safety_hooks(self.SAFETY_MODEL, self.SAFETY_PARAM) + self.safety.init_tests() + self.now = 1_000_000 + self.lka_count = 0 + self.control_count = 0 + self.word = self.SAFETY_PARAM + + def packet(self, msg): + addr, dat, bus = msg + return libsafety_py.make_CANPacket(addr, bus, dat) + + def rx(self, name, values, *, bus=0): + self.assertTrue(self._rx(self.packer.make_can_msg_safety(name, bus, values))) + + def warm(self, speed=15.0, curvature=0.0): + self.safety.set_timer(self.now) + for _ in range(6): + self.rx("BrakeSysFeatures", {"Veh_V_ActlBrk": speed * 3.6, "VehVActlBrk_D_Qf": 3}) + self.rx("EngVehicleSpThrottle2", {"Veh_V_ActlEng": speed * 3.6, "VehVActlEng_D_Qf": 3}) + self.rx("Yaw_Data_FD1", {"VehYaw_W_Actl": curvature * speed, "VehYawWActl_D_Qf": 3}) + self.rx("EngVehicleSpThrottle", {"ApedPos_Pc_ActlArb": 0}) + self.rx("DesiredTorqBrk", {"VehStop_D_Stat": 0}) + self.rx("Steering_Data_FD1", {"CcAslButtnCnclResPress": 0}) + if not self.safety.get_controls_allowed(): + self.rx("EngBrakeData", {"BpedDrvAppl_D_Actl": 1, "CcStat_D_Actl": 0}) + self.rx("EngBrakeData", {"BpedDrvAppl_D_Actl": 1, "CcStat_D_Actl": 5}) + self.assertTrue(self.safety.get_controls_allowed()) + + def reset_word(self, word): + self.safety.set_alternative_experience(0) + self.safety.set_safety_hooks(self.SAFETY_MODEL, word) + self.word = word + self.lka_count = self.control_count = 0 + self.now += 1_000_000 + self.warm() + + def shadow(self, command): + msg = lka(self.packer, 0, command.shadow_curvature, self.lka_count) + self.lka_count = (self.lka_count + 1) % 8 + return msg + + def control(self, command): + msg = lateral(self.packer, 0, command, canfd=bool(self.word & 2), counter=self.control_count) + self.control_count = (self.control_count + 1) % 16 + return msg + + def send(self, msg, expected=True): + self.assertEqual(bool(self._tx(self.packet(msg))), expected) + + def tick(self, command): + self.now += 50_000 + self.warm() + self.send(self.shadow(command)) + self.send(self.control(command)) + + def test_real_packer_physical_neutral_shadow_and_corruptions(self): + packer = CANPacker(self.DBC) + for word in (128, 130): + for direction in (-1, 1): + for fault in ("angle", "curvature", "checksum", "version", "counter", "replay"): + with self.subTest(word=word, direction=direction, fault=fault): + self.reset_word(word) + command = Command(True, direction * 0.005, direction * 0.005 / 15.0) + # Real RX and PCM edges in warm() establish permission, with no allowance setter. + self.assertTrue(self.safety.get_controls_allowed()) + good = lka(packer, 0, command.shadow_curvature, 0) + addr, data, bus = good + self.assertEqual((addr, bus), (0x3CA, 0)) + self.assertEqual(data[:4], b"\x00\x80\x08\x00") + self.assertEqual(((data[2] & 15) << 8) | data[3], 2048) + self.assertEqual((data[1] << 4) | (data[2] >> 4), 2048) + self.assertEqual(data[7] & 15, 1) + self.assertEqual(data[7] >> 4, checksum4(data)) + self.assertEqual(int.from_bytes(data[5:7], "big", signed=True), round(-command.shadow_curvature * 1e6)) + self.send(good) + self.send(lateral(packer, 0, command, canfd=bool(word & 2), counter=0)) + self.now += 50_000 + self.warm() + next_good = lka(packer, 0, command.shadow_curvature, 1) + mutated = bytearray(next_good[1]) + if fault == "angle": + mutated[3] ^= 1 + elif fault == "curvature": + mutated[1] ^= 1 + elif fault == "checksum": + mutated[7] ^= 16 + elif fault == "version": + mutated[7] ^= 1 + elif fault == "counter": + mutated[4] ^= 4 + if fault in ("angle", "curvature", "counter"): + mutated[7] = 1 | (checksum4(mutated) << 4) + bad = good if fault == "replay" else (addr, bytes(mutated), bus) + self.send(bad, False) + self.assertTrue(self.safety.get_controls_allowed()) + self.send(lateral(packer, 0, command, canfd=bool(word & 2), counter=1), False) + # A new valid announcement restores the same bounded path without relaxing native checks. + self.now += 50_000 + self.warm() + self.send(next_good) + self.send(lateral(packer, 0, command, canfd=bool(word & 2), counter=1)) + + def test_actual_core_packer_boundary_all_namespaces(self): + words = [128, 129, 130] + if self.debug: + words.append(131) + for word in words: + for direction in (-1, 1): + self.reset_word(word) + core = AngleController(low_gain=0.95, high_gain=0.95) + active_seen = False + for _ in range(40): + command = core.step(Inputs(True, 15.0, 0.0, direction * 0.02)) + active_seen |= command.active + self.tick(command) + self.assertTrue(active_seen) + self.tick(Command()) + + def test_cold_and_stale_shadow_require_new_valid_announcement(self): + command = Command(True, 0.005, 0.005 / 15.0) + self.warm() + self.send(self.control(command), False) + self.send(self.shadow(command)) + self.send(self.control(command)) + self.now += 60_001 + self.warm() + self.send(self.control(command), False) + self.now += 50_000 + self.warm() + self.send(self.shadow(command)) + self.send(self.control(command)) + + def test_invalid_shadow_version_checksum_and_dbc_bits_withdraw(self): + command = Command(True, 0.005, 0.005 / 15.0) + for index, mask in ((7, 1), (7, 16), (0, 32), (4, 2), (4, 32)): + self.reset_word(128) + valid = self.shadow(command) + addr, data, bus = valid + mutated = bytearray(data) + mutated[index] ^= mask + if index != 7: + mutated[7] = 1 | (checksum4(mutated) << 4) + self.send((addr, bytes(mutated), bus), False) + self.send(self.control(command), False) + self.send(valid) + self.send(self.control(command)) + + def test_replay_wrong_bus_and_length_cannot_refresh_shadow(self): + command = Command(True, 0.005, 0.005 / 15.0) + self.warm() + msg = self.shadow(command) + self.send(msg) + self.send(msg, False) + self.send(self.control(command), False) + for bus, size in ((2, 8), (0, 7), (0, 16)): + addr, dat, _ = self.shadow(command) + self.send((addr, (dat + b"\x00" * 8)[:size], bus), False) + self.now += 30_000 + self.rx("EngBrakeData", {"BpedDrvAppl_D_Actl": 1, "CcStat_D_Actl": 0}) + self.send(self.shadow(Command())) + self.now += 30_000 + self.warm() + self.send(self.shadow(command)) + self.send(self.control(command)) + + def test_native_actual_path_cannot_be_laundered_by_shadow(self): + for command in (Command(True, 0.0005, 0.0), Command(True, -0.0005, 0.0), Command(True, 0.5, 0.0), Command(True, -0.01, 0.001), + Command(True, 0.04, 0.002), Command(True, 0.10, 0.005)): + self.reset_word(128) + self.send(self.shadow(command)) + self.send(self.control(command), False) + # A rejected command does not seed an excessive subsequent ROC. + self.reset_word(128) + large = Command(True, 0.20, 0.01) + self.send(self.shadow(large)) + self.send(self.control(large), False) + self.now += 50_000 + self.warm() + small = Command(True, 0.005, 0.005 / 15.0) + self.send(self.shadow(small)) + self.send(self.control(small)) + + def test_permission_and_rx_withdrawals(self): + command = Command(True, 0.005, 0.005 / 15.0) + for source in ("brake", "gas", "cruise", "speed_quality", "yaw_checksum", "stale"): + self.reset_word(128) + self.send(self.shadow(command)) + self.send(self.control(command)) + self.now += 50_000 + self.warm() + self.send(self.shadow(command)) + if source == "brake": + self.rx("EngBrakeData", {"BpedDrvAppl_D_Actl": 2, "CcStat_D_Actl": 5}) + elif source == "gas": + self.rx("EngVehicleSpThrottle", {"ApedPos_Pc_ActlArb": 50}) + elif source == "cruise": + self.rx("EngBrakeData", {"BpedDrvAppl_D_Actl": 1, "CcStat_D_Actl": 3}) + elif source == "speed_quality": + self.assertFalse(self._rx(self.packer.make_can_msg_safety("BrakeSysFeatures", 0, {"VehVActlBrk_D_Qf": 0}))) + elif source == "yaw_checksum": + packet = self.packer.make_can_msg_safety("Yaw_Data_FD1", 0, {"VehYawWActl_D_Qf": 3}) + packet[0].data[4] ^= 1 + self.assertFalse(self._rx(packet)) + else: + self.now += 200_001 + self.safety.set_timer(self.now) + self.send(self.control(command), False) + self.send(self.control(Command())) + + def test_fd_bad_crc_counter_and_mode_neutral_recovery(self): + self.reset_word(130) + command = Command(True, 0.005, 0.005 / 15.0) + self.send(self.shadow(command)) + good = self.control(command) + addr, dat, bus = good + bad = bytearray(dat) + bad[1] ^= 1 + self.send((addr, bytes(bad), bus), False) + self.send(good, False) # bad CRC withdrew shadow + self.now += 50_000 + self.warm() + self.send(self.shadow(command)) + self.send(self.control(Command())) # valid mode0 resynchronizes skipped counters + self.now += 50_000 + self.warm() + self.send(self.shadow(command)) + self.send(self.control(command)) + self.now += 50_000 + self.warm() + self.send(self.shadow(command)) + self.control_count = (self.control_count + 1) % 16 + self.send(self.control(command), False) + + def test_adjacent_profile_version_and_release_long_denials(self): + command = Command(True, 0.005, 0.005 / 15.0) + for word in (0, 2, 4, 8, 10, 12, 18, 32, 66, 132, 134, 136, 160, 194, 256): + self.reset_word(word) + announcement = self.shadow(command) + if word & 128: + self.send(announcement, False) + else: + self._tx(self.packet(announcement)) # Existing neutral metadata is not angle authority. + self.send(self.control(command), False) + self.reset_word(131) + expected = bool(self.debug) + self.send(self.shadow(command), expected) + self.send(self.control(command), expected) + + def test_rejected_metadata_does_not_erase_last_accepted_path_and_neutral_resync(self): + self.reset_word(128) + # At25m/s ROC is tight enough that erasing the accepted path would reject a same-path retry. + core = AngleController(low_gain=.95, high_gain=.95) + for _ in range(30): + self.now += 50_000 + self.warm(speed=25., curvature=.001) + command = core.step(Inputs(True, 25., -.001, -.001)) + self.send(self.shadow(command)) + self.send(self.control(command)) + self.assertGreater(abs(command.path_angle), .01) + self.now += 50_000 + self.warm(speed=25., curvature=.001) + good = self.shadow(command) + addr, data, bus = good + bad = bytearray(data) + bad[7] ^= 16 + self.send((addr, bytes(bad), bus), False) + self.send(good) + self.send(self.control(command)) + self.now += 50_000 + self.warm(speed=25., curvature=.001) + self.send(self.control(Command())) + self.now += 50_000 + self.warm(speed=25., curvature=.001) + recovery = AngleController(low_gain=.95, high_gain=.95).step(Inputs(True, 25., -.001, -.001)) + self.send(self.shadow(recovery)) + self.send(self.control(recovery)) + + def test_rt_rate_denial_expires_and_neutral_can_recover(self): + self.reset_word(130) + for _ in range(8): + self.send(self.control(Command())) + self.send(self.control(Command()), False) + self.now += 250_000 + self.warm() + self.send(self.control(Command())) + self.now += 50_000 + self.warm() + command = Command(True, .005, .005 / 15.) + self.send(self.shadow(command)) + self.send(self.control(command)) diff --git a/opendbc_repo/opendbc/bluepilot_lateral/upstream-root-LICENSE b/opendbc_repo/opendbc/bluepilot_lateral/upstream-root-LICENSE new file mode 100644 index 0000000000..7dafa9443b --- /dev/null +++ b/opendbc_repo/opendbc/bluepilot_lateral/upstream-root-LICENSE @@ -0,0 +1,7 @@ +Copyright (c) 2018, Comma.ai, Inc. + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/opendbc_repo/opendbc/bluepilot_lateral/upstream-root-LICENSE.md b/opendbc_repo/opendbc/bluepilot_lateral/upstream-root-LICENSE.md new file mode 100644 index 0000000000..650b6f55b3 --- /dev/null +++ b/opendbc_repo/opendbc/bluepilot_lateral/upstream-root-LICENSE.md @@ -0,0 +1,21 @@ +# Custom MIT License + +Copyright (c) 2024, Haibin Wen, SUNNYPILOT LLC + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to view and modify the Software, subject to the following conditions: + +1. **Permission Required**: Permission Required for Commercial, For-Profit, or Closed Source Use: Use of the Software, in whole or in part, for any commercial purposes, for-profit projects, or in closed source projects requires explicit written permission from the original author(s). + +2. **Redistribution**: Any redistribution of the Software, modified or unmodified, must retain this license notice and the following acknowledgment: + "This software is licensed under a custom license requiring permission for use." + +3. **Visibility**: Any project that uses the Software must visibly mention the following acknowledgment: + "This project uses software from Haibin Wen and SUNNYPILOT LLC and is licensed under a custom license requiring permission for use." + +4. **No Warranty**: THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +Contact sunnypilot Support for permission requests. + +--- + +Haibin Wen, SUNNYPILOT LLC diff --git a/opendbc_repo/opendbc/car/ford/aol.py b/opendbc_repo/opendbc/car/ford/aol.py new file mode 100644 index 0000000000..a8cfa60247 --- /dev/null +++ b/opendbc_repo/opendbc/car/ford/aol.py @@ -0,0 +1,53 @@ +from opendbc.car import structs +from opendbc.car.ford.values import CAR, FordFlags + +AOL_EXPERIENCE = 32 +CLASSIC = frozenset((CAR.FORD_BRONCO_SPORT_MK1, CAR.FORD_ESCAPE_MK4, CAR.FORD_FOCUS_MK4, + CAR.FORD_MAVERICK_MK1, CAR.FORD_EXPLORER_MK6)) +GENERIC_CANFD = frozenset((CAR.FORD_ESCAPE_MK4_5, CAR.FORD_EXPEDITION_MK4, CAR.FORD_F_150_MK14, + CAR.FORD_F_150_LIGHTNING_MK1, CAR.FORD_RANGER_MK2)) +AOL_WORDS = frozenset((8, 9, 10, 11, 12, 13, 18, 19, 32, 33, 66, 67)) + + +def qualified(cp, *, marked_only=False): + if (cp.brand != 'ford' or cp.carFingerprint not in tuple(CAR) or cp.passive or cp.notCar or cp.dashcamOnly or + cp.steerControlType != structs.CarParams.SteerControlType.angle or + cp.transmissionType != structs.CarParams.TransmissionType.automatic or len(cp.safetyConfigs) != 1 or + cp.alternativeExperience not in ((32,) if marked_only else (0, 32))): + return False + flags = int(cp.flags) & ~int(FordFlags.HAS_BSM) + if cp.carFingerprint in CLASSIC and flags == 0: + base = 32 + elif cp.carFingerprint == CAR.FORD_MUSTANG_MACH_E_MK1 and flags == int(FordFlags.CANFD): + base = 18 + elif cp.carFingerprint in GENERIC_CANFD and flags == int(FordFlags.CANFD): + base = 66 + elif cp.carFingerprint == CAR.FORD_EDGE_MK2 and flags == int(FordFlags.NEW_PORT | FordFlags.ALT_STEER_ANGLE): + base = 8 + elif cp.carFingerprint == CAR.FORD_MONDEO_MK5 and flags == int(FordFlags.NEW_PORT | FordFlags.CANFD): + base = 10 + elif cp.carFingerprint == CAR.FORD_TRANSIT_MK5 and flags == int(FordFlags.NEW_PORT | FordFlags.LKA_STEERING): + base = 12 + else: + return False + safety = cp.safetyConfigs[0] + return (cp.pcmCruise and + safety.safetyModel == structs.CarParams.SafetyModel.ford and + safety.safetyParam == (base | int(cp.openpilotLongitudinalControl))) + + +def temporary_restriction(cp, state): + gears = structs.CarState.GearShifter + return bool(state is not None and qualified(cp, marked_only=True) and state.canValid and not state.canTimeout + and not state.steerFaultPermanent and + (state.gearShifter not in (gears.drive, gears.sport, gears.low) or state.steerFaultTemporary or state.vehicleSensorsInvalid)) + + +def native_observation(native, *, latched, panda_ready, restricted, now_ns, pending_since_ns): + lost = not panda_ready or native is None + if not latched or lost or restricted: + return 0, lost, False + if native.requestedLateral and native.lateralAllowed: + return 0, False, False + pending_since_ns = pending_since_ns or now_ns + return pending_since_ns, False, now_ns - pending_since_ns >= 200_000_000 diff --git a/opendbc_repo/opendbc/car/ford/carcontroller.py b/opendbc_repo/opendbc/car/ford/carcontroller.py index 8690e74fc5..6c7a91da33 100644 --- a/opendbc_repo/opendbc/car/ford/carcontroller.py +++ b/opendbc_repo/opendbc/car/ford/carcontroller.py @@ -1,9 +1,24 @@ import math import numpy as np from opendbc.can import CANPacker +from opendbc.bluepilot_lateral import BluePilotLateral +from opendbc.bluepilot_lateral.hosts.starpilot import qualified as angle_qualified from opendbc.car import ACCELERATION_DUE_TO_GRAVITY, Bus, DT_CTRL, apply_hysteresis, structs from opendbc.car.ford import fordcan -from opendbc.car.ford.values import CarControllerParams, FordFlags, CAR +from opendbc.car.ford.manual_turn import ManualTurnLatch +from opendbc.car.ford.aol import qualified as qualified_aol +from opendbc.car.ford.stock_cruise import FordStockCruiseButton, qualified as stock_switch_qualified +from opendbc.car.ford.curvature_preview import blend_curvature +from opendbc.car.ford import mache_can +from opendbc.car.ford.extended_classic_can import create_extended_classic_lat_ctl_msg +from opendbc.car.ford.classic_lateral import create_controller as create_classic_controller, bounded_command as classic_bounded_command +from opendbc.car.ford.generic_canfd_can import create_extended_canfd_msg +from opendbc.car.ford.generic_canfd_lateral import ( + GenericCanfdLateralController, qualified as generic_canfd_qualified, bounded_command as generic_canfd_bounded_command, +) +from opendbc.car.ford.mache_lateral import MachELateralController, FordLateralResult, bounded_command, qualified as mache_qualified +from opendbc.car.ford.new_port_curvature import create_controller as create_new_port_curvature, bounded_command as new_port_bounded_command +from opendbc.car.ford.values import CarControllerParams, FordFlags, FordSafetyFlags, CAR from opendbc.car.interfaces import CarControllerBase, V_CRUISE_MAX LongCtrlState = structs.CarControl.Actuators.LongControlState @@ -25,19 +40,49 @@ def anti_overshoot(apply_curvature, apply_curvature_last, v_ego): return float(np.interp(v_ego, [5, 10], [apply_curvature, output_curvature])) -def apply_creep_compensation(accel: float, v_ego: float) -> float: +def apply_creep_compensation(accel: float, v_ego: float, car_fingerprint: str, *, standstill: bool, stopping: bool) -> float: + if car_fingerprint == CAR.FORD_MUSTANG_MACH_E_MK1 and not (standstill and stopping): + return accel creep_accel = np.interp(v_ego, [1., 3.], [0.6, 0.]) creep_accel = np.interp(accel, [0., 0.2], [creep_accel, 0.]) accel -= creep_accel return float(accel) +def apply_brake_rate_limit(accel: float, gas: float, accel_last: float, v_ego: float, car_fingerprint: str, + *, stopping: bool, standstill: bool, fcw: bool) -> tuple[float, float]: + mild_mach_e_braking = ( + car_fingerprint == CAR.FORD_MUSTANG_MACH_E_MK1 and + -1.0 < gas < 0.0 and v_ego >= 5.0 and not (stopping or standstill or fcw) + ) + if mild_mach_e_braking: + accel = max(accel, min(accel_last, 0.0) - 2.0 * CarControllerParams.ACC_CONTROL_STEP * DT_CTRL) + gas = accel + else: + accel = max(accel, accel_last - 3.5 * CarControllerParams.ACC_CONTROL_STEP * DT_CTRL) + return float(accel), float(gas) + + class CarController(CarControllerBase): def __init__(self, dbc_names, CP): super().__init__(dbc_names, CP) self.packer = CANPacker(dbc_names[Bus.pt]) self.CAN = fordcan.CanBus(CP) + self.bp_lat = BluePilotLateral(CP) if angle_qualified(CP) else None + self.manual_turn = ManualTurnLatch() if CP.carFingerprint == CAR.FORD_MUSTANG_MACH_E_MK1 and not CP.flags & FordFlags.LKA_STEERING else None + self.stock_cruise_button = FordStockCruiseButton() + self.manual_turn_inputs = None + self.mache_lateral = MachELateralController(CP) if mache_qualified(CP) else None + self.mache_extended_announced = False + self.generic_canfd = generic_canfd_qualified(CP) + self.classic_lateral = GenericCanfdLateralController(CP) if self.generic_canfd else create_classic_controller(CP) + self.new_port_curvature = create_new_port_curvature(CP) + self.classic_extended_announced = False + self.classic_profile = any(s.safetyModel == structs.CarParams.SafetyModel.ford and + s.safetyParam & (FordSafetyFlags.CLASSIC_EXTENDED | FordSafetyFlags.GENERIC_CANFD_EXTENDED) for s in CP.safetyConfigs) + self.mache_profile = any(s.safetyModel == structs.CarParams.SafetyModel.ford and + s.safetyParam & FordSafetyFlags.MACH_E_EXTENDED for s in CP.safetyConfigs) self.apply_curvature_last = 0 self.anti_overshoot_curvature_last = 0 self.accel = 0.0 @@ -48,9 +93,14 @@ class CarController(CarControllerBase): self.steer_alert_last = False self.lead_distance_bars_last = None self.distance_bar_frame = 0 + self.apply_lka_angle_last = 0. + self.apply_lka_curvature_last = 0. def update(self, CC, CS, now_nanos): can_sends = [] + if (self.mache_lateral is not None or self.classic_lateral is not None or self.new_port_curvature is not None) and self.manual_turn_inputs is not None: + self.manual_turn_inputs.update() + self.manual_turn_inputs.apply_blend_settings(self) actuators = CC.actuators hud_control = CC.hudControl @@ -60,9 +110,21 @@ class CarController(CarControllerBase): fcw_alert = hud_control.visualAlert == VisualAlert.fcw ### acc buttons ### + stock_cancel = False + stock_resume = False + if stock_switch_qualified(self.CP): + stock_cancel, stock_resume = self.stock_cruise_button.update( + bool(CS.buttons_stock_values["CcAslButtnCnclResPress"]), + CS.out.cruiseState.available, CS.out.cruiseState.enabled) + if CC.cruiseControl.cancel: can_sends.append(fordcan.create_button_msg(self.packer, self.CAN.camera, CS.buttons_stock_values, cancel=True)) can_sends.append(fordcan.create_button_msg(self.packer, self.CAN.main, CS.buttons_stock_values, cancel=True)) + elif (stock_cancel or stock_resume) and (self.frame % CarControllerParams.BUTTONS_STEP) == 0: + can_sends.append(fordcan.create_button_msg( + self.packer, self.CAN.camera, CS.buttons_stock_values, cancel=stock_cancel, resume=stock_resume)) + can_sends.append(fordcan.create_button_msg( + self.packer, self.CAN.main, CS.buttons_stock_values, cancel=stock_cancel, resume=stock_resume)) elif CC.cruiseControl.resume and (self.frame % CarControllerParams.BUTTONS_STEP) == 0: can_sends.append(fordcan.create_button_msg(self.packer, self.CAN.camera, CS.buttons_stock_values, resume=True)) can_sends.append(fordcan.create_button_msg(self.packer, self.CAN.main, CS.buttons_stock_values, resume=True)) @@ -73,7 +135,79 @@ class CarController(CarControllerBase): ### lateral control ### # send steer msg at 20Hz - if (self.frame % CarControllerParams.STEER_STEP) == 0: + if (self.frame % CarControllerParams.STEER_STEP) == 0 and self.bp_lat is not None: + can_sends += self.bp_lat.step_lateral(CC, CS, self.packer, self.CAN, self.frame, now_nanos) + self.apply_curvature_last = self.bp_lat.apply_curvature_last + elif (self.frame % CarControllerParams.STEER_STEP) == 0 and self.CP.flags & FordFlags.LKA_STEERING: + # Preserve the stock LMC heartbeat without requesting lateral action. + can_sends.append(fordcan.create_lat_ctl_msg(self.packer, self.CAN, False, 0., 0., 0., 0., + stock_lmc=CS.lateral_motion_control)) + elif (self.frame % CarControllerParams.STEER_STEP) == 0 and self.mache_lateral is not None: + permission = getattr(self.manual_turn_inputs, "assist_permission", None) + self.mache_lateral.set_assist_permission(*(permission() if permission is not None else ((), False))) + inputs = self.manual_turn_inputs.lateral_snapshot(CS.out.vEgoRaw) if self.manual_turn_inputs is not None else None + if inputs is not None: + self.mache_lateral.set_inputs(*inputs) + else: + # Withdraw stale preview while retaining current actuator/manual-turn control. + self.mache_lateral.set_inputs(None, (), 0.2, self.manual_turn_inputs.enabled if self.manual_turn_inputs is not None else True) + previous = self.mache_lateral.curvature_last + previous_path_angle = self.mache_lateral.path_angle_last + demanded = self.mache_lateral.update(CC, CS, actuators) if self.mache_extended_announced else FordLateralResult() + lateral = bounded_command(self.mache_lateral, demanded, previous, CS.out.vEgoRaw, previous_path_angle) + self.mache_lateral_demand = demanded + self.apply_curvature_last = lateral.curvature + counter = (self.frame // CarControllerParams.STEER_STEP) % 0x10 + can_sends.append(mache_can.create_lat_ctl2_msg( + self.packer, self.CAN, int(lateral.active), lateral.ramp_type, lateral.precision_type, + -lateral.curvature, -lateral.curvature_rate, counter, -lateral.path_angle)) + elif (self.frame % CarControllerParams.STEER_STEP) == 0 and self.classic_lateral is not None: + inputs = self.manual_turn_inputs.lateral_snapshot(CS.out.vEgoRaw) if self.manual_turn_inputs is not None else None + if inputs is not None: + self.classic_lateral.set_inputs(*inputs) + else: + self.classic_lateral.set_inputs(None, (), 0.2, self.manual_turn_inputs.enabled if self.manual_turn_inputs is not None else True) + previous = self.classic_lateral.curvature_last + demanded = self.classic_lateral.update(CC, CS, actuators) if self.classic_extended_announced else FordLateralResult() + bound = generic_canfd_bounded_command if self.generic_canfd else classic_bounded_command + lateral = bound(self.classic_lateral, demanded, previous, CS.out.vEgoRaw, + -CS.out.yawRate / max(CS.out.vEgoRaw, 0.1)) + self.classic_lateral_demand = demanded + self.apply_curvature_last = lateral.curvature + if self.generic_canfd: + counter = (self.frame // CarControllerParams.STEER_STEP) % 0x10 + can_sends.append(create_extended_canfd_msg( + self.packer, self.CAN, lateral.active, lateral.ramp_type, lateral.precision_type, + -lateral.curvature, -lateral.curvature_rate, counter)) + else: + can_sends.append(create_extended_classic_lat_ctl_msg( + self.packer, self.CAN, lateral.active, lateral.ramp_type, lateral.precision_type, + -lateral.curvature, -lateral.curvature_rate)) + elif (self.frame % CarControllerParams.STEER_STEP) == 0 and self.new_port_curvature is not None: + inputs = self.manual_turn_inputs.lateral_snapshot(CS.out.vEgoRaw) if self.manual_turn_inputs is not None else None + self.new_port_curvature.set_inputs(*(inputs if inputs is not None else + (None, (), 0.2, self.manual_turn_inputs.enabled if self.manual_turn_inputs is not None else True))) + previous = self.new_port_curvature.curvature_last + demanded = self.new_port_curvature.update(CC, CS, actuators) + lateral = new_port_bounded_command(self.new_port_curvature, demanded, previous, CS.out.vEgoRaw, + -CS.out.yawRate / max(CS.out.vEgoRaw, 0.1)) + self.new_port_curvature_demand = demanded + self.apply_curvature_last = lateral.curvature + if self.CP.flags & FordFlags.CANFD: + counter = (self.frame // CarControllerParams.STEER_STEP) % 0x10 + can_sends.append(fordcan.create_lat_ctl2_msg(self.packer, self.CAN, int(lateral.active), 0., 0., + -lateral.curvature, 0., counter)) + else: + can_sends.append(fordcan.create_lat_ctl_msg(self.packer, self.CAN, lateral.active, 0., 0., -lateral.curvature, 0.)) + elif (self.frame % CarControllerParams.STEER_STEP) == 0: + lateral_active = CC.latActive and not self.mache_profile and not self.classic_profile + manual_turn = False + if self.manual_turn is not None and self.manual_turn_inputs is not None: + detection_enabled, lane_change, model_ready = self.manual_turn_inputs.update() + manual_turn = self.manual_turn.update(CC, CS, float(actuators.curvature), detection_enabled, lane_change, model_ready) + if manual_turn: + lateral_active = False + self.apply_curvature_last = 0. # Bronco and some other cars consistently overshoot curv requests # Apply some deadzone + smoothing convergence to avoid oscillations if self.CP.carFingerprint in (CAR.FORD_BRONCO_SPORT_MK1, CAR.FORD_F_150_MK14): @@ -84,13 +218,18 @@ class CarController(CarControllerBase): # apply rate limits, curvature error limit, and clip to signal range current_curvature = -CS.out.yawRate / max(CS.out.vEgoRaw, 0.1) + if self.manual_turn is not None and self.manual_turn_inputs is not None and lateral_active: + prediction = getattr(self.manual_turn_inputs, "preview_curvature", None) + preview = prediction(CS.out.vEgoRaw) if prediction is not None else None + if preview is not None: + apply_curvature = blend_curvature(apply_curvature, preview, current_curvature) # No blending at low speed due to lack of torque wind-up and inaccurate current curvature if CS.out.vEgoRaw > 9: apply_curvature = float(np.clip(apply_curvature, current_curvature - CarControllerParams.CURVATURE_ERROR, current_curvature + CarControllerParams.CURVATURE_ERROR)) apply_curvature = CarControllerParams.CURVATURE_LIMITS.apply_limits(apply_curvature, self.apply_curvature_last, CS.out.vEgoRaw, - 0., CC.latActive, CarControllerParams.STEER_STEP) - self.apply_curvature_last = apply_curvature + 0., lateral_active, CarControllerParams.STEER_STEP) + self.apply_curvature_last = 0. if manual_turn else apply_curvature if self.CP.flags & FordFlags.CANFD: # TODO: extended mode @@ -99,31 +238,65 @@ class CarController(CarControllerBase): # steer actuation, the other three signals are necessary. Ford controls vehicles differently than most other makes. # A detailed explanation on ford control can be found here: # https://www.f150gen14.com/forum/threads/introducing-bluepilot-a-ford-specific-fork-for-comma3x-openpilot.24241/#post-457706 - mode = 1 if CC.latActive else 0 + mode = 1 if lateral_active else 0 counter = (self.frame // CarControllerParams.STEER_STEP) % 0x10 can_sends.append(fordcan.create_lat_ctl2_msg(self.packer, self.CAN, mode, 0., 0., -self.apply_curvature_last, 0., counter)) else: - can_sends.append(fordcan.create_lat_ctl_msg(self.packer, self.CAN, CC.latActive, 0., 0., -self.apply_curvature_last, 0.)) + can_sends.append(fordcan.create_lat_ctl_msg(self.packer, self.CAN, lateral_active, 0., 0., -self.apply_curvature_last, 0.)) # send lka msg at 33Hz if (self.frame % CarControllerParams.LKA_STEP) == 0: - can_sends.append(fordcan.create_lka_msg(self.packer, self.CAN)) + if self.bp_lat is not None: + can_sends += self.bp_lat.step_lka(self.packer, self.CAN, now_nanos) + elif self.CP.flags & FordFlags.LKA_STEERING: + source_age_ns = now_nanos - CS.lkas_available_ts_nanos + lka_active = (CC.latActive and CS.lkas_available and 0 <= source_age_ns <= 100_000_000 and + (CS.out.cruiseState.enabled or qualified_aol(self.CP, marked_only=True)) and + not CS.out.steerFaultTemporary and + not CS.out.vehicleSensorsInvalid) + if lka_active: + desired_angle = float(np.clip(actuators.steeringAngleDeg - CS.out.steeringAngleDeg, -5.8, 5.8)) + self.apply_lka_angle_last = float(np.clip(desired_angle, self.apply_lka_angle_last - 1., + self.apply_lka_angle_last + 1.)) + desired_curvature = -actuators.curvature + current_curvature = CS.out.yawRate / max(CS.out.vEgoRaw, 0.1) + if CS.out.vEgoRaw > 9.: + desired_curvature = float(np.clip(desired_curvature, current_curvature - CarControllerParams.CURVATURE_ERROR, + current_curvature + CarControllerParams.CURVATURE_ERROR)) + self.apply_lka_curvature_last = CarControllerParams.LKA_CURVATURE_LIMITS.apply_limits( + desired_curvature, self.apply_lka_curvature_last, CS.out.vEgoRaw, 0., True, CarControllerParams.LKA_STEP) + else: + self.apply_lka_angle_last = 0. + self.apply_lka_curvature_last = 0. + self.apply_curvature_last = -self.apply_lka_curvature_last + direction = 2 if self.apply_lka_angle_last >= 0. else 4 + can_sends.append(fordcan.create_lka_msg(self.packer, self.CAN, lka_active, self.apply_lka_angle_last, + direction, self.apply_lka_curvature_last, transit=True)) + elif self.mache_lateral is not None: + can_sends.append(mache_can.create_lka_msg(self.packer, self.CAN)) + self.mache_extended_announced = True + elif self.classic_lateral is not None: + can_sends.append(mache_can.create_lka_msg(self.packer, self.CAN)) + self.classic_extended_announced = True + else: + can_sends.append(fordcan.create_lka_msg(self.packer, self.CAN)) ### longitudinal control ### # send acc msg at 50Hz if self.CP.openpilotLongitudinalControl and (self.frame % CarControllerParams.ACC_CONTROL_STEP) == 0: accel = actuators.accel gas = accel + stopping = actuators.longControlState == LongCtrlState.stopping if CC.longActive: - # Compensate for engine creep at low speed. - # Either the ABS does not account for engine creep, or the correction is very slow - # TODO: verify this applies to EV/hybrid - accel = apply_creep_compensation(accel, CS.out.vEgo) + accel = apply_creep_compensation(accel, CS.out.vEgo, self.CP.carFingerprint, + standstill=CS.out.standstill, stopping=stopping) - # The stock system has been seen rate limiting the brake accel to 5 m/s^3, - # however even 3.5 m/s^3 causes some overshoot with a step response. - accel = max(accel, self.accel - (3.5 * CarControllerParams.ACC_CONTROL_STEP * DT_CTRL)) + accel, gas = apply_brake_rate_limit( + accel, gas, self.accel, CS.out.vEgo, self.CP.carFingerprint, + stopping=stopping, standstill=CS.out.standstill, + fcw=fcw_alert or CS.out.stockFcw or CS.out.stockAeb, + ) accel = float(np.clip(accel, CarControllerParams.ACCEL_MIN, CarControllerParams.ACCEL_MAX)) gas = float(np.clip(gas, CarControllerParams.ACCEL_MIN, CarControllerParams.ACCEL_MAX)) @@ -143,7 +316,6 @@ class CarController(CarControllerBase): elif accel_pitch_compensated < 0.0: self.brake_request = True - stopping = CC.actuators.longControlState == LongCtrlState.stopping # TODO: look into using the actuators packet to send the desired speed can_sends.append(fordcan.create_acc_msg(self.packer, self.CAN, CC.longActive, gas, accel, stopping, self.brake_request, v_ego_kph=V_CRUISE_MAX)) @@ -174,6 +346,8 @@ class CarController(CarControllerBase): new_actuators = actuators.as_builder() new_actuators.curvature = self.apply_curvature_last + if self.CP.flags & FordFlags.LKA_STEERING: + new_actuators.steeringAngleDeg = CS.out.steeringAngleDeg + self.apply_lka_angle_last new_actuators.accel = self.accel new_actuators.gas = self.gas diff --git a/opendbc_repo/opendbc/car/ford/carstate.py b/opendbc_repo/opendbc/car/ford/carstate.py index 9c98f36075..63a25fdadd 100644 --- a/opendbc_repo/opendbc/car/ford/carstate.py +++ b/opendbc_repo/opendbc/car/ford/carstate.py @@ -1,9 +1,14 @@ +import math + from opendbc.can import CANDefine, CANParser +from opendbc.can.dbc import DBC as CANDBC from opendbc.car import Bus, create_button_events, structs from opendbc.car.common.conversions import Conversions as CV from opendbc.car.ford.fordcan import CanBus -from opendbc.car.ford.values import DBC, CarControllerParams, FordFlags +from opendbc.car.ford.stock_cruise import FordStockCruiseButton +from opendbc.car.ford.values import CAR, DBC, CarControllerParams, FordFlags from opendbc.car.interfaces import CarStateBase +from opendbc.car.dashboard_speed_limit import Tracker as LimitTracker, ford_sign, parser_expiry ButtonType = structs.CarState.ButtonEvent.Type GearShifter = structs.CarState.GearShifter @@ -15,10 +20,22 @@ class CarState(CarStateBase): super().__init__(CP) can_define = CANDefine(DBC[CP.carFingerprint][Bus.pt]) if CP.transmissionType == TransmissionType.automatic: - self.shifter_values = can_define.dv["PowertrainData_10"]["TrnRng_D_Rq"] + if CP.carFingerprint == CAR.FORD_MONDEO_MK5: + self.shifter_values = can_define.dv["Gear_Shift_by_Wire_FD1"]["TrnRng_D_RqGsm"] + elif CP.flags & FordFlags.ALT_STEER_ANGLE: + self.shifter_values = can_define.dv["TransGearData"]["GearLvrPos_D_Actl"] + else: + self.shifter_values = can_define.dv["PowertrainData_10"]["TrnRng_D_Rq"] self.distance_button = 0 + self.dashboard_limit = LimitTracker() self.lc_button = 0 + self.cancel_button = False + self.cancel_resume_button = FordStockCruiseButton() + self.steering_angle_offset_deg = 0.0 + self.lkas_available = False + self.lkas_available_ts_nanos = 0 + self.lateral_motion_control = None def update(self, can_parsers) -> structs.CarState: cp = can_parsers[Bus.pt] @@ -28,7 +45,14 @@ class CarState(CarStateBase): # Occasionally on startup, the ABS module recalibrates the steering pinion offset, so we need to block engagement # The vehicle usually recovers out of this state within a minute of normal driving - ret.vehicleSensorsInvalid = cp.vl["SteeringPinion_Data"]["StePinCompAnEst_D_Qf"] != 3 + if self.CP.flags & FordFlags.ALT_STEER_ANGLE: + park_aid = cp.vl["ParkAid_Data"] + ret.vehicleSensorsInvalid = (cp.ts_nanos["ParkAid_Data"]["ExtSteeringAngleReq2"] == 0 or + cp.ts_nanos["SteeringPinion_Data_Alt"]["StePinRelInit_An_Sns"] == 0 or + int((park_aid["ExtSteeringAngleReq2"] + 1000) * 10) in (32766, 32767) or + park_aid["EPASExtAngleStatReq"] != 0 or park_aid["ApaSys_D_Stat"] not in (0, 1)) + else: + ret.vehicleSensorsInvalid = cp.vl["SteeringPinion_Data"]["StePinCompAnEst_D_Qf"] != 3 # car speed ret.vEgoRaw = cp.vl["BrakeSysFeatures"]["Veh_V_ActlBrk"] * CV.KPH_TO_MS @@ -44,7 +68,13 @@ class CarState(CarStateBase): ret.parkingBrake = cp.vl["DesiredTorqBrk"]["PrkBrkStatus"] in (1, 2) # steering wheel - ret.steeringAngleDeg = cp.vl["SteeringPinion_Data"]["StePinComp_An_Est"] + if self.CP.flags & FordFlags.ALT_STEER_ANGLE: + initial_angle = cp.vl["SteeringPinion_Data_Alt"]["StePinRelInit_An_Sns"] + if not ret.vehicleSensorsInvalid: + self.steering_angle_offset_deg = cp.vl["ParkAid_Data"]["ExtSteeringAngleReq2"] - initial_angle + ret.steeringAngleDeg = initial_angle + self.steering_angle_offset_deg + else: + ret.steeringAngleDeg = cp.vl["SteeringPinion_Data"]["StePinComp_An_Est"] ret.steeringTorque = cp.vl["EPAS_INFO"]["SteeringColumnTorque"] ret.steeringPressed = self.update_steering_pressed(abs(ret.steeringTorque) > CarControllerParams.STEER_DRIVER_ALLOWANCE, 5) ret.steerFaultTemporary = cp.vl["EPAS_INFO"]["EPAS_Failure"] == 1 @@ -54,6 +84,13 @@ class CarState(CarStateBase): if self.CP.flags & FordFlags.CANFD: # this signal is always 0 on non-CAN FD cars ret.steerFaultTemporary |= cp.vl["Lane_Assist_Data3_FD1"]["LatCtlSte_D_Stat"] not in (1, 2, 3) + if self.CP.flags & FordFlags.LKA_STEERING: + self.lkas_available_ts_nanos = cp.ts_nanos["Lane_Assist_Data3_FD1"]["LaActAvail_D_Actl"] + self.lkas_available = (self.lkas_available_ts_nanos > 0 and + cp.vl["Lane_Assist_Data3_FD1"]["LaActAvail_D_Actl"] == 3 and + cp.vl["Lane_Assist_Data3_FD1"]["LaActDeny_B_Actl"] == 0) + self.lateral_motion_control = cp_cam.vl["LateralMotionControl"] + ret.steerFaultTemporary |= not self.lkas_available # cruise state is_metric = cp.vl["INSTRUMENT_PANEL"]["METRIC_UNITS"] == 1 if not self.CP.flags & FordFlags.CANFD else False @@ -68,7 +105,14 @@ class CarState(CarStateBase): # gear if self.CP.transmissionType == TransmissionType.automatic: - gear = self.shifter_values.get(cp.vl["PowertrainData_10"]["TrnRng_D_Rq"]) + if self.CP.carFingerprint == CAR.FORD_MONDEO_MK5: + gear = self.shifter_values.get(cp.vl["Gear_Shift_by_Wire_FD1"]["TrnRng_D_RqGsm"]) + elif self.CP.flags & FordFlags.ALT_STEER_ANGLE: + gear = self.shifter_values.get(cp.vl["TransGearData"]["GearLvrPos_D_Actl"]) + else: + gear = self.shifter_values.get(cp.vl["PowertrainData_10"]["TrnRng_D_Rq"]) + if self.CP.carFingerprint in (CAR.FORD_EDGE_MK2, CAR.FORD_MONDEO_MK5) and gear == "SPORT_DRIVESPORT": + gear = "SPORT" ret.gearShifter = self.parse_gear_shifter(gear) elif self.CP.transmissionType == TransmissionType.manual: if bool(cp.vl["BCM_Lamp_Stat_FD1"]["RvrseLghtOn_B_Stat"]): @@ -89,6 +133,11 @@ class CarState(CarStateBase): prev_lc_button = self.lc_button self.distance_button = cp.vl["Steering_Data_FD1"]["AccButtnGapTogglePress"] self.lc_button = bool(cp.vl["Steering_Data_FD1"]["TjaButtnOnOffPress"]) + prev_cancel_button = self.cancel_button + cancel, _ = self.cancel_resume_button.update( + bool(cp.vl["Steering_Data_FD1"]["CcAslButtnCnclResPress"]), + ret.cruiseState.available, ret.cruiseState.enabled) + self.cancel_button = bool(cp.vl["Steering_Data_FD1"]["CcAslButtnCnclPress"]) or cancel # lock info ret.doorOpen = any([cp.vl["BodyInfo_3_FD1"]["DrStatDrv_B_Actl"], cp.vl["BodyInfo_3_FD1"]["DrStatPsngr_B_Actl"], @@ -107,16 +156,48 @@ class CarState(CarStateBase): self.acc_tja_status_stock_values = cp_cam.vl["ACCDATA_3"] self.lkas_status_stock_values = cp_cam.vl["IPMA_Data"] - ret.buttonEvents = [ + button_events = [ *create_button_events(self.distance_button, prev_distance_button, {1: ButtonType.gapAdjustCruise}), *create_button_events(self.lc_button, prev_lc_button, {1: ButtonType.lkas}), ] + if self.CP.openpilotLongitudinalControl: + button_events += create_button_events(self.cancel_button, prev_cancel_button, {1: ButtonType.cancel}) + + ret.buttonEvents = button_events + + timestamp, expiry = parser_expiry(cp_cam, "Traffic_RecognitnData", "TsrVLim1MsgTxt_D_Rq") + if timestamp > self.dashboard_limit.observation.observed_ns: + speed = int(cp_cam.vl["Traffic_RecognitnData"]["TsrVLim1MsgTxt_D_Rq"]) + unit = int(cp_cam.vl["Traffic_RecognitnData"]["TsrVlUnitMsgTxt_D_Rq"]) + status, value_mps = ford_sign(speed, unit) + self.dashboard_limit.update(timestamp, status, value_mps, valid_until_ns=expiry) + return ret @staticmethod def get_can_parsers(CP): + dbc_name = DBC[CP.carFingerprint][Bus.pt] + cam_messages = [("Traffic_RecognitnData", math.nan)] if "Traffic_RecognitnData" in CANDBC(dbc_name).name_to_msg else [] + pt_messages = [] + if CP.flags & FordFlags.NEW_PORT: + # Subscribe before the first update so the new ports cannot miss their first source frame. + pt_messages = [(name, math.nan) for name in ( + "BrakeSysFeatures", "Yaw_Data_FD1", "DesiredTorqBrk", "EngVehicleSpThrottle", + "EngBrakeData", "EPAS_INFO", "Cluster_Info1_FD1", "Steering_Data_FD1", + "BodyInfo_3_FD1", "RCMStatusMessage2_FD1", "SteeringPinion_Data", + )] + if CP.flags & FordFlags.CANFD: + pt_messages += [("Gear_Shift_by_Wire_FD1", math.nan), ("Lane_Assist_Data3_FD1", 30)] + elif CP.flags & FordFlags.ALT_STEER_ANGLE: + pt_messages += [("ParkAid_Data", 50), ("SteeringPinion_Data_Alt", 100), + ("TransGearData", math.nan), ("INSTRUMENT_PANEL", math.nan)] + else: + pt_messages += [(name, math.nan) for name in ("PowertrainData_10", "INSTRUMENT_PANEL")] + if CP.flags & FordFlags.LKA_STEERING: + pt_messages.append(("Lane_Assist_Data3_FD1", 30)) + cam_messages.append(("LateralMotionControl", 20)) return { - Bus.pt: CANParser(DBC[CP.carFingerprint][Bus.pt], [], CanBus(CP).main), - Bus.cam: CANParser(DBC[CP.carFingerprint][Bus.pt], [], CanBus(CP).camera), + Bus.pt: CANParser(DBC[CP.carFingerprint][Bus.pt], pt_messages, CanBus(CP).main), + Bus.cam: CANParser(dbc_name, cam_messages, CanBus(CP).camera), } diff --git a/opendbc_repo/opendbc/car/ford/classic_lateral.py b/opendbc_repo/opendbc/car/ford/classic_lateral.py new file mode 100644 index 0000000000..d95fdb435b --- /dev/null +++ b/opendbc_repo/opendbc/car/ford/classic_lateral.py @@ -0,0 +1,52 @@ +"""Shared source-derived classic Ford family; model transport stays outside opendbc. + +The reused extended strategy derives from BluePilot Ford work by Alan Polk and +contributors. Its original attribution and licenses remain in lateral_strategy.py, +CREDITS.md and THIRD_PARTY_NOTICES.md; this module only selects admitted callers. +""" + +from opendbc.car import structs +from opendbc.car.ford.explorer_lateral import ExplorerLateralController, bounded_command as bounded_command, qualified as explorer_qualified +from opendbc.car.ford.lateral_strategy import FordLateralController +from opendbc.car.ford.values import CAR, FordFlags, FordSafetyFlags + +GENERIC_CLASSIC_CARS = frozenset({CAR.FORD_BRONCO_SPORT_MK1, CAR.FORD_ESCAPE_MK4, + CAR.FORD_FOCUS_MK4, CAR.FORD_MAVERICK_MK1}) +CLASSIC_EXTENDED_CARS = GENERIC_CLASSIC_CARS | {CAR.FORD_EXPLORER_MK6} + + +def qualified(cp): + if cp.alternativeExperience == 32 and len(cp.safetyConfigs) != 1: + return False + if cp.carFingerprint == CAR.FORD_EXPLORER_MK6: + return explorer_qualified(cp) + if (cp.brand != "ford" or cp.carFingerprint not in GENERIC_CLASSIC_CARS or + cp.flags & ~int(FordFlags.HAS_BSM) or cp.passive or cp.dashcamOnly or cp.notCar or + cp.alternativeExperience not in (0, 32) or len(cp.safetyConfigs) not in (1, 2)): + return False + if len(cp.safetyConfigs) == 2 and (cp.safetyConfigs[0].safetyModel != structs.CarParams.SafetyModel.noOutput or + cp.safetyConfigs[0].safetyParam != 0): + return False + safety = cp.safetyConfigs[-1] + expected = int(FordSafetyFlags.CLASSIC_EXTENDED | (FordSafetyFlags.LONG_CONTROL if cp.openpilotLongitudinalControl else 0)) + return safety.safetyModel == structs.CarParams.SafetyModel.ford and safety.safetyParam == expected + + +class GenericClassicLateralController(FordLateralController): + """Original generic liveDelay preview; no Explorer fixed-delay or Mach-E latch.""" + + def __init__(self, cp): + if not qualified(cp) or cp.carFingerprint not in GENERIC_CLASSIC_CARS: + raise ValueError("Generic classic controller requires the exact admitted family") + super().__init__(cp) + self.manual_turn_detected = False + + def _manual_turn(self, CC, CS, desired, driver_assisting): + self.manual_turn_detected = super()._manual_turn(CC, CS, desired, driver_assisting) + return self.manual_turn_detected + + +def create_controller(cp): + if not qualified(cp): + return None + return ExplorerLateralController(cp) if cp.carFingerprint == CAR.FORD_EXPLORER_MK6 else GenericClassicLateralController(cp) diff --git a/opendbc_repo/opendbc/car/ford/curvature_preview.py b/opendbc_repo/opendbc/car/ford/curvature_preview.py new file mode 100644 index 0000000000..6b63937d31 --- /dev/null +++ b/opendbc_repo/opendbc/car/ford/curvature_preview.py @@ -0,0 +1,14 @@ +"""Mach-E default model preview, before the upstream actuator limits.""" + +import math + + +def blend_curvature(desired: float, predicted: float, current: float) -> float: + if not all(math.isfinite(value) for value in (desired, predicted, current)): + return desired + blend = 0.4 + if desired * predicted <= 0.0: + blend = 0.0 + elif current * predicted > 0.0 and abs(current) > abs(desired) and abs(predicted) > abs(desired): + blend *= abs(desired) / abs(predicted) + return predicted * blend + desired * (1.0 - blend) diff --git a/opendbc_repo/opendbc/car/ford/explorer_lateral.py b/opendbc_repo/opendbc/car/ford/explorer_lateral.py new file mode 100644 index 0000000000..85db461a8b --- /dev/null +++ b/opendbc_repo/opendbc/car/ford/explorer_lateral.py @@ -0,0 +1,92 @@ +"""Explorer/Aviator source-derived demand and exact native profile contract. + +The inherited strategy is adapted from BluePilot Ford work. Attribution and +license notices are preserved in lateral_strategy.py, CREDITS.md and +THIRD_PARTY_NOTICES.md. +""" + +from dataclasses import replace +from typing import Protocol + +import numpy as np + +from opendbc.car import structs +from opendbc.car.ford.lateral_strategy import FordLateralController, FordLateralResult, FORD_CURVATURE_LIMITS, STEER_DT +from opendbc.car.ford.values import CAR, CarControllerParams, FordFlags, FordSafetyFlags + + +class ExplorerLateralController(FordLateralController): + """Exact classic Explorer family, including the Aviator identity alias.""" + + def __init__(self, CP): + if CP.carFingerprint != CAR.FORD_EXPLORER_MK6 or CP.flags & ~int(FordFlags.HAS_BSM): + raise ValueError("Explorer demand strategy requires the exact classic family") + super().__init__(CP) + self.manual_turn_detected = False + + def _manual_turn(self, CC, CS, desired: float, driver_assisting: bool = False) -> bool: + self.manual_turn_detected = super()._manual_turn(CC, CS, desired, driver_assisting) + return self.manual_turn_detected + + def _curvature_lookahead(self) -> float: + # Original reached family override precedes liveDelay inspection. + return 0.20 + + +def qualified(CP) -> bool: + if CP.alternativeExperience == 32 and len(CP.safetyConfigs) != 1: + return False + if (CP.brand != "ford" or CP.carFingerprint != CAR.FORD_EXPLORER_MK6 or + CP.flags & ~int(FordFlags.HAS_BSM) or CP.passive or CP.dashcamOnly or CP.notCar or + CP.alternativeExperience not in (0, 32) or len(CP.safetyConfigs) not in (1, 2)): + return False + if len(CP.safetyConfigs) == 2 and (CP.safetyConfigs[0].safetyModel != structs.CarParams.SafetyModel.noOutput or + CP.safetyConfigs[0].safetyParam != 0): + return False + safety = CP.safetyConfigs[-1] + expected = int(FordSafetyFlags.EXPLORER_EXTENDED | (FordSafetyFlags.LONG_CONTROL if CP.openpilotLongitudinalControl else 0)) + return safety.safetyModel == structs.CarParams.SafetyModel.ford and safety.safetyParam == expected + + +class CurvatureOwner(Protocol): + manual_turn_detected: bool + curvature_last: float + path_angle_last: float + + +def bounded_command(owner: CurvatureOwner, demanded: FordLateralResult, + previous: float, speed: float, measured: float, *, absolute_cap: float | None = None) -> FordLateralResult: + """Keep classic demand inside the modern common ISO/jerk envelope.""" + limits = CarControllerParams.CURVATURE_LIMITS + cap = min(limits.CURVATURE_MAX, limits.MAX_LATERAL_ACCEL / max(speed, 1.0) ** 2) + if absolute_cap is not None: + cap = min(cap, absolute_cap) + modern_delta = limits.MAX_LATERAL_JERK / max(speed, 1.0) ** 2 * STEER_DT + source_up = FORD_CURVATURE_LIMITS.ANGLE_RATE_LIMIT_UP + source_down = FORD_CURVATURE_LIMITS.ANGLE_RATE_LIMIT_DOWN + rise = float(np.interp(speed, source_up[0], source_up[1])) + fall = float(np.interp(speed, source_down[0], source_down[1])) + # Same sign plus increasing magnitude uses rise; unwind/opposite uses fall. + source_low = previous - (fall if previous > 0.0 else rise) + source_high = previous + (fall if previous < 0.0 else rise) + low = max(-cap, previous - modern_delta, source_low) + high = min(cap, previous + modern_delta, source_high) + # Match modern recovery toward the actual measured-curvature error window. + # Outside the window, require directional progress without jumping into it. + if speed > 10.0: + error_low = measured - CarControllerParams.CURVATURE_ERROR + error_high = measured + CarControllerParams.CURVATURE_ERROR + if previous < error_low: + low = max(low, min(previous + modern_delta, error_low, cap)) + elif previous > error_high: + high = min(high, max(previous - modern_delta, error_high, -cap)) + else: + low = max(low, error_low) + high = min(high, error_high) + if not demanded.active or owner.manual_turn_detected or low > high: + command = FordLateralResult() + else: + command = replace(demanded, curvature=float(np.clip(demanded.curvature, low, high)), path_angle=0.0) + owner.curvature_last = command.curvature + owner.path_angle_last = 0.0 + return command diff --git a/opendbc_repo/opendbc/car/ford/extended_classic_can.py b/opendbc_repo/opendbc/car/ford/extended_classic_can.py new file mode 100644 index 0000000000..f7cffbcb87 --- /dev/null +++ b/opendbc_repo/opendbc/car/ford/extended_classic_can.py @@ -0,0 +1,25 @@ +"""Source-derived classic Ford extended lateral constructor. + +Adapted from BluePilot fordcan_ext.py; see CREDITS.md and +THIRD_PARTY_NOTICES.md. This codec does not grant native authority. +""" + +from opendbc.car.ford.fordcan import CanBus + + +def create_extended_classic_lat_ctl_msg(packer, CAN: CanBus, active: bool, ramp_type: int, precision_type: int, + curvature: float, curvature_rate: float): + # 13-bit DBC endpoint: positive .001024 would wrap to negative .001024. + curvature_rate = max(-0.001024, min(curvature_rate, 0.00102375)) + values = { + "LatCtlRng_L_Max": 0, + "HandsOffCnfm_B_Rq": 0, + "LatCtl_D_Rq": 1 if active else 0, + "LatCtlRampType_D_Rq": ramp_type, + "LatCtlPrecision_D_Rq": precision_type, + "LatCtlPathOffst_L_Actl": 0.0, + "LatCtlPath_An_Actl": 0.0, + "LatCtlCurv_NoRate_Actl": curvature_rate, + "LatCtlCurv_No_Actl": curvature, + } + return packer.make_can_msg("LateralMotionControl", CAN.main, values) diff --git a/opendbc_repo/opendbc/car/ford/fingerprints.py b/opendbc_repo/opendbc/car/ford/fingerprints.py index ee400e1eca..22199d9840 100644 --- a/opendbc_repo/opendbc/car/ford/fingerprints.py +++ b/opendbc_repo/opendbc/car/ford/fingerprints.py @@ -15,6 +15,8 @@ FW_VERSIONS = { b'LX6C-2D053-RD\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', b'LX6C-2D053-RE\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', b'LX6C-2D053-RF\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', + b'LX6C-2D053-KF\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', + b'LX6C-2D053-KG\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', ], (Ecu.fwdRadar, 0x764, None): [ b'LB5T-14D049-AB\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', @@ -50,6 +52,8 @@ FW_VERSIONS = { CAR.FORD_ESCAPE_MK4_5: { (Ecu.eps, 0x730, None): [ b'PZ11-14D003-EA\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', + b'PZ11-14D003-AB\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', + b'PZ11-14D003-FA\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', ], (Ecu.abs, 0x760, None): [ b'PZ1C-2D053-EJ\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', @@ -59,6 +63,11 @@ FW_VERSIONS = { ], (Ecu.fwdCamera, 0x706, None): [ b'PJ6T-14H102-ABL\x00\x00\x00\x00\x00\x00\x00\x00\x00', + b'PJ6T-14H102-ABE\x00\x00\x00\x00\x00\x00\x00\x00\x00', + b'PJ6T-14H102-MDC\x00\x00\x00\x00\x00\x00\x00\x00\x00', + b'PJ6T-14H102-MDF\x00\x00\x00\x00\x00\x00\x00\x00\x00', + b'PJ6T-14H102-SCD\x00\x00\x00\x00\x00\x00\x00\x00\x00', + b'PJ6T-14H102-SCG\x00\x00\x00\x00\x00\x00\x00\x00\x00', ], }, CAR.FORD_EXPLORER_MK6: { @@ -69,6 +78,10 @@ FW_VERSIONS = { b'M1MC-14D003-AB\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', b'M1MC-14D003-AC\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', b'P1MC-14D003-AA\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', + b'R1MC-14D003-AE\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', + b'R1MC-14D003-AF\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', + b'R1MC-14D003-AG\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', + b'R1MC-14D003-AH\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', ], (Ecu.abs, 0x760, None): [ b'L1MC-2D053-AJ\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', @@ -96,6 +109,7 @@ FW_VERSIONS = { ], (Ecu.abs, 0x760, None): [ b'RL14-2D053-AA\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', + b'PL14-2D053-AB\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', ], (Ecu.fwdRadar, 0x764, None): [ b'ML3T-14D049-AL\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', @@ -109,6 +123,7 @@ FW_VERSIONS = { b'ML3V-14D003-BA\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', b'ML3V-14D003-BC\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', b'ML3V-14D003-BD\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', + b'MB3C-14D003-AA\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', ], (Ecu.abs, 0x760, None): [ b'ML34-2D053-AJ\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', @@ -138,6 +153,9 @@ FW_VERSIONS = { (Ecu.abs, 0x760, None): [ b'PL38-2D053-AA\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', b'RL38-2D053-BD\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', + b'NL38-2D053-AF\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', + b'RL38-2D053-BC\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', + b'TL38-2D053-AD\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', ], (Ecu.fwdCamera, 0x706, None): [ b'ML3T-14H102-ABT\x00\x00\x00\x00\x00\x00\x00\x00\x00', @@ -146,9 +164,13 @@ FW_VERSIONS = { ], (Ecu.fwdRadar, 0x764, None): [ b'ML3T-14D049-AL\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', + b'ML3T-14D049-AH\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', + b'RB5T-14D049-AB\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', ], (Ecu.eps, 0x730, None): [ b'RL38-14D003-AA\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', + b'NL38-14D003-AA\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', + b'NL38-14D003-AC\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', ], }, CAR.FORD_MUSTANG_MACH_E_MK1: { @@ -165,6 +187,8 @@ FW_VERSIONS = { ], (Ecu.fwdRadar, 0x764, None): [ b'ML3T-14D049-AL\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', + b'ML3T-14D049-AH\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', + b'ML3T-14D049-AK\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', ], (Ecu.fwdCamera, 0x706, None): [ b'ML3T-14H102-ABS\x00\x00\x00\x00\x00\x00\x00\x00\x00', @@ -175,10 +199,13 @@ FW_VERSIONS = { (Ecu.eps, 0x730, None): [ b'JX6C-14D003-AH\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', b'NX6C-14D003-AL\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', + b'JX6C-14D003-AL\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', + b'JX6C-14D003-BB\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', ], (Ecu.abs, 0x760, None): [ b'JX61-2D053-CJ\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', b'LX61-2D053-AD\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', + b'NX61-2D053-MD\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', ], (Ecu.fwdRadar, 0x764, None): [ b'JX7T-14D049-AC\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', @@ -214,19 +241,49 @@ FW_VERSIONS = { b'NB3C-14D003-AB\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', b'NL14-14D003-AE\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', b'RB3C-14D003-AA\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', + b'JR3C-14D003-AA\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', + b'NL14-14D003-AC\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', ], (Ecu.abs, 0x760, None): [ b'PB3C-2D053-ZD\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', b'PB3C-2D053-ZG\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', b'PB3C-2D053-ZJ\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', b'RB3C-2D053-AK\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', + b'MB3C-2D053-AE\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', + b'MB3C-2D053-ZJ\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', + b'PB3C-2D053-ZB\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', + b'PB3C-2D053-ZC\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', + b'PB9C-2D053-ZG\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', ], (Ecu.fwdRadar, 0x764, None): [ b'ML3T-14D049-AL\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', + b'JX7T-14D049-AD\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', ], (Ecu.fwdCamera, 0x706, None): [ b'PJ6T-14H102-ABJ\x00\x00\x00\x00\x00\x00\x00\x00\x00', b'RJ6T-14H102-BBB\x00\x00\x00\x00\x00\x00\x00\x00\x00', ], }, + CAR.FORD_EDGE_MK2: { + (Ecu.eps, 0x730, None): [b'M2GC-14D003-AA\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'], + (Ecu.abs, 0x760, None): [b'M2GC-2D053-CB\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', + b'M2GC-2D053-EA\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'], + (Ecu.fwdRadar, 0x764, None): [b'JX7T-14D049-AD\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'], + (Ecu.fwdCamera, 0x706, None): [b'KT4T-14F397-AF\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'], + }, + CAR.FORD_MONDEO_MK5: { + (Ecu.fwdCamera, 0x706, None): [b'KT4T-14F397-AE\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'], + (Ecu.abs, 0x760, None): [b'KG9C-2D053-DF\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'], + (Ecu.eps, 0x730, None): [b'K2GC-14D003-AJ\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'], + (Ecu.fwdRadar, 0x764, None): [b'JX7T-14D049-AD\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'], + }, + CAR.FORD_TRANSIT_MK5: { + (Ecu.eps, 0x730, None): [b'KK21-14D003-AM\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'], + (Ecu.abs, 0x760, None): [b'NK41-2D053-DF\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'], + (Ecu.fwdRadar, 0x764, None): [b'PC4T-14D049-AA\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'], + (Ecu.fwdCamera, 0x706, None): [ + b'NK3T-14F397-AB\x00\x00\x00\x00\x00\x00\x00\x00\x00', + b'NK3T-14F397-AB\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', + ], + }, } diff --git a/opendbc_repo/opendbc/car/ford/fordcan.py b/opendbc_repo/opendbc/car/ford/fordcan.py index 64209cced3..7a67fcd0e6 100644 --- a/opendbc_repo/opendbc/car/ford/fordcan.py +++ b/opendbc_repo/opendbc/car/ford/fordcan.py @@ -1,3 +1,4 @@ +import math from opendbc.car import CanBusBase @@ -18,7 +19,7 @@ class CanBus(CanBusBase): return self.offset + 2 -def create_lka_msg(packer, CAN: CanBus): +def create_lka_msg(packer, CAN: CanBus, active=False, apply_angle=0., direction=0, curvature=0., transit=False): """ Creates an empty CAN message for the Ford LKA Command. @@ -27,11 +28,24 @@ def create_lka_msg(packer, CAN: CanBus): Frequency is 33Hz. """ - return packer.make_can_msg("Lane_Assist_Data1", CAN.main, {}) + values = {} + if transit: + values = {"LaRefAng_No_Req": 0., "LaCurvature_No_Calc": 0., "LdwActvIntns_D_Req": 3} + if active: + values = { + "LkaDrvOvrrd_D_Rq": 0, + "LkaActvStats_D2_Req": direction, + "LaRefAng_No_Req": math.radians(max(-5.8, min(5.8, apply_angle))) * 1000., + "LaRampType_B_Req": int(abs(apply_angle) >= 5.), + "LaCurvature_No_Calc": max(-0.01023, min(0.01023, curvature)), + "LdwActvStats_D_Req": 0, + "LdwActvIntns_D_Req": 3, + } + return packer.make_can_msg("Lane_Assist_Data1", CAN.main, values) def create_lat_ctl_msg(packer, CAN: CanBus, lat_active: bool, path_offset: float, path_angle: float, curvature: float, - curvature_rate: float): + curvature_rate: float, stock_lmc=None): """ Creates a CAN message for the Ford TJA/LCA Command. @@ -67,6 +81,11 @@ def create_lat_ctl_msg(packer, CAN: CanBus, lat_active: bool, path_offset: float "LatCtlCurv_NoRate_Actl": curvature_rate, # Curvature rate [-0.001024|0.00102375] 1/meter^2 "LatCtlCurv_No_Actl": curvature, # Curvature [-0.02|0.02094] 1/meter } + if stock_lmc is not None: + values = {key: stock_lmc[key] for key in values} + values.update({"LatCtl_D_Rq": 0, "HandsOffCnfm_B_Rq": 0, + "LatCtlPathOffst_L_Actl": 0., "LatCtlPath_An_Actl": 0., + "LatCtlCurv_NoRate_Actl": 0., "LatCtlCurv_No_Actl": 0.}) return packer.make_can_msg("LateralMotionControl", CAN.main, values) diff --git a/opendbc_repo/opendbc/car/ford/generic_canfd_can.py b/opendbc_repo/opendbc/car/ford/generic_canfd_can.py new file mode 100644 index 0000000000..aee70d36ce --- /dev/null +++ b/opendbc_repo/opendbc/car/ford/generic_canfd_can.py @@ -0,0 +1,9 @@ +"""Generic extended CAN FD wire endpoint, using the attributed shared codec.""" +from opendbc.car.ford.mache_can import create_lat_ctl2_msg + + +def create_extended_canfd_msg(packer, CAN, active, ramp, precision, curvature, rate, counter): + # Generic original lower rate negates to +.001024, outside the 11-bit field. + # Clamp the physical wire endpoint before packing instead of wrapping sign. + rate = max(-.001024, min(.001023, rate)) + return create_lat_ctl2_msg(packer, CAN, int(active), ramp, precision, curvature, rate, counter, 0.) diff --git a/opendbc_repo/opendbc/car/ford/generic_canfd_lateral.py b/opendbc_repo/opendbc/car/ford/generic_canfd_lateral.py new file mode 100644 index 0000000000..e62a7b2826 --- /dev/null +++ b/opendbc_repo/opendbc/car/ford/generic_canfd_lateral.py @@ -0,0 +1,47 @@ +"""Exact generic CAN FD caller; no Mach-E error, path assist, or latch. + +The reused BluePilot-derived strategy retains its original attribution in +lateral_strategy.py, CREDITS.md and THIRD_PARTY_NOTICES.md. +""" +from opendbc.car import structs +from opendbc.car.ford.explorer_lateral import bounded_command as shared_bound +from opendbc.car.ford.lateral_strategy import FordLateralController +from opendbc.car.ford.values import CAR, FordFlags, FordSafetyFlags + +GENERIC_CANFD_CARS = frozenset({CAR.FORD_ESCAPE_MK4_5, CAR.FORD_EXPEDITION_MK4, + CAR.FORD_F_150_MK14, CAR.FORD_F_150_LIGHTNING_MK1, CAR.FORD_RANGER_MK2}) +SOURCE_ACCEL_CAP = 3.0 - 9.81 * .06 + + +def qualified(cp): + if cp.alternativeExperience == 32 and len(cp.safetyConfigs) != 1: + return False + if (cp.brand != "ford" or cp.carFingerprint not in GENERIC_CANFD_CARS or + not cp.flags & FordFlags.CANFD or cp.flags & ~int(FordFlags.CANFD | FordFlags.HAS_BSM) or + cp.passive or cp.dashcamOnly or cp.notCar or cp.alternativeExperience not in (0, 32) or + len(cp.safetyConfigs) not in (1, 2)): + return False + if len(cp.safetyConfigs) == 2 and (cp.safetyConfigs[0].safetyModel != structs.CarParams.SafetyModel.noOutput or + cp.safetyConfigs[0].safetyParam != 0): + return False + s = cp.safetyConfigs[-1] + expected = int(FordSafetyFlags.GENERIC_CANFD_EXTENDED | FordSafetyFlags.CANFD | + (FordSafetyFlags.LONG_CONTROL if cp.openpilotLongitudinalControl else 0)) + return s.safetyModel == structs.CarParams.SafetyModel.ford and s.safetyParam == expected + + +class GenericCanfdLateralController(FordLateralController): + def __init__(self, cp): + if not qualified(cp): + raise ValueError("Generic CAN FD controller requires its exact source-owned profile") + super().__init__(cp) + self.manual_turn_detected = False + + def _manual_turn(self, CC, CS, desired, driver_assisting): + self.manual_turn_detected = super()._manual_turn(CC, CS, desired, driver_assisting) + return self.manual_turn_detected + + +def bounded_command(owner, demanded, previous, speed, measured): + return shared_bound(owner, demanded, previous, speed, measured, + absolute_cap=SOURCE_ACCEL_CAP / max(speed, 1.) ** 2) diff --git a/opendbc_repo/opendbc/car/ford/interface.py b/opendbc_repo/opendbc/car/ford/interface.py index 3a5e52f2a7..f7b0676173 100644 --- a/opendbc_repo/opendbc/car/ford/interface.py +++ b/opendbc_repo/opendbc/car/ford/interface.py @@ -4,9 +4,11 @@ from opendbc.car.carlog import carlog from opendbc.car.common.conversions import Conversions as CV from opendbc.car.ford.carcontroller import CarController from opendbc.car.ford.carstate import CarState +from opendbc.car.ford.classic_lateral import CLASSIC_EXTENDED_CARS +from opendbc.car.ford.generic_canfd_lateral import GENERIC_CANFD_CARS from opendbc.car.ford.fordcan import CanBus from opendbc.car.ford.radar_interface import RadarInterface -from opendbc.car.ford.values import CarControllerParams, DBC, Ecu, FordFlags, RADAR, FordSafetyFlags +from opendbc.car.ford.values import CarControllerParams, DBC, Ecu, FordFlags, RADAR, FordSafetyFlags, CAR from opendbc.car.interfaces import CarInterfaceBase TransmissionType = structs.CarParams.TransmissionType @@ -33,12 +35,12 @@ class CarInterface(CarInterfaceBase): ret.radarUnavailable = Bus.radar not in DBC[candidate] ret.steerControlType = structs.CarParams.SteerControlType.angle - ret.steerActuatorDelay = 0.2 + ret.steerActuatorDelay = 0.05 if ret.flags & FordFlags.LKA_STEERING else 0.22 ret.steerLimitTimer = 1.0 ret.steerAtStandstill = True ret.longitudinalTuning.kiBP = [0.] - ret.longitudinalTuning.kiV = [0.5] + ret.longitudinalTuning.kiV = [0.3] if candidate == CAR.FORD_MUSTANG_MACH_E_MK1 else [0.5] if not ret.radarUnavailable and DBC[candidate][Bus.radar] == RADAR.DELPHI_MRR: # average of 33.3 Hz radar timestep / 4 scan modes = 60 ms @@ -51,10 +53,28 @@ class CarInterface(CarInterfaceBase): cfgs.insert(0, get_safety_config(structs.CarParams.SafetyModel.noOutput)) ret.safetyConfigs = cfgs - ret.alphaLongitudinalAvailable = ret.radarUnavailable - if alpha_long or not ret.radarUnavailable: + new_port = bool(ret.flags & FordFlags.NEW_PORT) + if candidate in GENERIC_CANFD_CARS: + ret.alphaLongitudinalAvailable = not is_release + ret.steerActuatorDelay = 0.22 + longitudinal_requested = bool(alpha_long and not is_release) + elif candidate == CAR.FORD_MUSTANG_MACH_E_MK1: + ret.alphaLongitudinalAvailable = not is_release + longitudinal_requested = bool(alpha_long and not is_release) + elif candidate in CLASSIC_EXTENDED_CARS: + # Original shared classic ownership is explicit stock/OP-long selection. + # Actuator delay is live; modern LongControl already supplies the original P=0. + ret.alphaLongitudinalAvailable = True + ret.steerActuatorDelay = 0.22 + longitudinal_requested = bool(alpha_long) + else: + ret.alphaLongitudinalAvailable = (not is_release if ret.flags & FordFlags.CANFD else True) if new_port else ret.radarUnavailable + longitudinal_requested = bool(alpha_long and ret.alphaLongitudinalAvailable) if new_port else alpha_long or not ret.radarUnavailable + if longitudinal_requested: ret.safetyConfigs[-1].safetyParam |= FordSafetyFlags.LONG_CONTROL.value ret.openpilotLongitudinalControl = True + if new_port: + ret.safetyConfigs[-1].safetyParam |= FordSafetyFlags.NEW_PORT.value if ret.flags & FordFlags.CANFD: ret.safetyConfigs[-1].safetyParam |= FordSafetyFlags.CANFD.value @@ -65,6 +85,8 @@ class CarInterface(CarInterfaceBase): if fingerprint[CAN.camera].get(0x3d6) != 8 or fingerprint[CAN.camera].get(0x186) != 8: carlog.error('dashcamOnly: SecOC is unsupported') ret.dashcamOnly = True + elif ret.flags & FordFlags.LKA_STEERING: + ret.safetyConfigs[-1].safetyParam |= FordSafetyFlags.LKA_STEERING.value else: # Lock out if the car does not have needed lateral and longitudinal control APIs. # Note that we also check CAN for adaptive cruise, but no known signal for LCA exists @@ -98,4 +120,34 @@ class CarInterface(CarInterfaceBase): ret.autoResumeSng = ret.minEnableSpeed == -1. ret.centerToFront = ret.wheelbase * 0.44 + + classic_extended = ( + candidate in CLASSIC_EXTENDED_CARS and not (ret.flags & ~int(FordFlags.HAS_BSM)) + and not ret.dashcamOnly and ret.alternativeExperience == 0 + and ret.safetyConfigs[-1].safetyParam in (0, 1) + ) + if classic_extended: + ret.safetyConfigs[-1].safetyParam |= FordSafetyFlags.CLASSIC_EXTENDED.value + + # The source-derived Mach-E owner has a separate native namespace. SecOC, + # unrelated static flags and alternative experiences retain no extension. + mach_e_extended = ( + candidate == CAR.FORD_MUSTANG_MACH_E_MK1 + and bool(ret.flags & FordFlags.CANFD) + and not (ret.flags & ~int(FordFlags.CANFD | FordFlags.HAS_BSM)) + and not ret.dashcamOnly and ret.alternativeExperience == 0 + and ret.safetyConfigs[-1].safetyParam in (2, 3) + ) + if mach_e_extended: + if is_release: + # The native CANFD LONG profile is DEBUG-only; RELEASE stays stock. + ret.alphaLongitudinalAvailable = False + ret.openpilotLongitudinalControl = False + ret.safetyConfigs[-1].safetyParam = FordSafetyFlags.CANFD.value + ret.safetyConfigs[-1].safetyParam |= FordSafetyFlags.MACH_E_EXTENDED.value + if (candidate in GENERIC_CANFD_CARS and ret.flags & FordFlags.CANFD and + not ret.flags & ~int(FordFlags.CANFD | FordFlags.HAS_BSM) and + not ret.dashcamOnly and not ret.passive and not ret.notCar and ret.alternativeExperience == 0): + ret.safetyConfigs[-1].safetyParam |= FordSafetyFlags.GENERIC_CANFD_EXTENDED.value + return ret diff --git a/opendbc_repo/opendbc/car/ford/lateral_strategy.py b/opendbc_repo/opendbc/car/ford/lateral_strategy.py new file mode 100644 index 0000000000..5f3160eee4 --- /dev/null +++ b/opendbc_repo/opendbc/car/ford/lateral_strategy.py @@ -0,0 +1,757 @@ +"""Ford lateral-control extensions. + +The extended curvature strategy, manual-turn detector, and related safety protocol are substantially +adapted from BluePilot's Ford work, principally by Alan Polk and additional contributors. The audited +bp-7.0 reference is e1d051d7ba270261b4455068bd68f1a58db15a4a; source attribution is retained in +CREDITS.md and THIRD_PARTY_NOTICES.md. StarPilot reorganized that work for its own architecture and has since +changed its tuning and lookahead behavior. + +See CREDITS.md for feature-level authorship and upstream commits, and THIRD_PARTY_NOTICES.md for the +published upstream license notices. Upstream contributors do not maintain this adaptation. +""" + +from collections import deque +from dataclasses import dataclass + +import numpy as np + +from opendbc.car import ACCELERATION_DUE_TO_GRAVITY, DT_CTRL, structs +from opendbc.car.ford.values import CAR, CarControllerParams, FordFlags, FordSafetyFlags +from opendbc.car.lateral import AngleSteeringLimits, ISO_LATERAL_ACCEL, apply_std_steer_angle_limits + + +# These rate-limit values descend from BluePilot's ``values_ext.py``, which carries the Haibin Wen +# and sunnypilot contributors copyright notice reproduced in THIRD_PARTY_NOTICES.md. +FORD_CURVATURE_LIMITS = AngleSteeringLimits( + 0.02, + ([5, 16, 25], [0.0025, 0.0012, 0.00008]), + ([5, 16, 25], [0.0025, 0.0014, 0.00018]), +) + +MAX_LATERAL_ACCEL = ISO_LATERAL_ACCEL - ACCELERATION_DUE_TO_GRAVITY * 0.06 +STEER_DT = CarControllerParams.STEER_STEP * DT_CTRL +CURVATURE_LOOKAHEAD_MIN = 0.20 +CURVATURE_LOOKAHEAD_MAX = 0.40 +MACH_E_HIGH_SPEED_LOOKAHEAD_EXTRA = 0.40 +MACH_E_HIGH_SPEED_LOOKAHEAD_START_SPEED = 16.0 +MACH_E_HIGH_SPEED_LOOKAHEAD_FULL_SPEED = 23.0 +MACH_E_TURN_IN_LOOKAHEAD_EXTRA = 0.80 +MACH_E_LOW_SPEED_TURN_IN_LOOKAHEAD_EXTRA = 1.60 +MACH_E_LOW_SPEED_TURN_IN_START_SPEED = 2.0 +MACH_E_LOW_SPEED_TURN_IN_FULL_SPEED = 3.0 +MACH_E_LOW_SPEED_TURN_IN_MAX_SPEED = 12.0 +MACH_E_LOW_SPEED_TURN_IN_FADE_SPEED = 15.0 +MACH_E_TURN_IN_MIN_CURVATURE = 0.002 +MACH_E_TURN_IN_FULL_CURVATURE = 0.008 +MACH_E_TURN_IN_LAG_CURVATURE = 0.006 +MACH_E_TURN_IN_PREVIEW_HOLD_SECONDS = 0.10 +MACH_E_TURN_IN_PREVIEW_HOLD_MIN_LAG = 0.0005 +MACH_E_TURN_IN_RATE_MIN_SPEED = 3.0 +MACH_E_TURN_IN_RATE_MIN_DEFICIT = 0.002 +MACH_E_UNWIND_LOOKAHEAD_EXTRA = 0.80 +MACH_E_UNWIND_FULL_LAG_CURVATURE = 0.0005 +MACH_E_UNWIND_PREVIEW_LAG_CURVATURE = 0.002 +MACH_E_UNWIND_PREVIEW_HOLD_SECONDS = 0.10 +MACH_E_UNWIND_PREVIEW_RISE_TOLERANCE = 0.0002 +MACH_E_UNWIND_RELEASE_GAIN = 0.40 +MACH_E_DIRECTION_CHANGE_MIN_SPEED = 9.0 +MACH_E_DIRECTION_CHANGE_LOOKAHEAD_RAMP_SPEED = 10.0 +MACH_E_DIRECTION_CHANGE_LOOKAHEAD_FULL_SPEED = 12.0 +MACH_E_DIRECTION_CHANGE_LOOKAHEAD_FADE_SPEED = 15.0 +MACH_E_DIRECTION_CHANGE_LOOKAHEAD_EXTRA = 2.40 +MACH_E_DIRECTION_CHANGE_MIN_PREVIEW_CURVATURE = 0.0005 +MACH_E_DIRECTION_CHANGE_FULL_PREVIEW_CURVATURE = 0.002 +MACH_E_DIRECTION_CHANGE_MIN_LAG_CURVATURE = 0.0008 +MACH_E_DIRECTION_CHANGE_FULL_LAG_CURVATURE = 0.0015 +MACH_E_DIRECTION_CHANGE_EARLY_MIN_LAG_CURVATURE = -0.001 +MACH_E_DIRECTION_CHANGE_EARLY_FULL_LAG_CURVATURE = 0.0008 +MACH_E_DIRECTION_CHANGE_EARLY_MIN_CURVATURE = 0.002 +MACH_E_DIRECTION_CHANGE_EARLY_FULL_CURVATURE = 0.004 +MACH_E_LOW_SPEED_DIRECTION_CHANGE_START_SPEED = 1.8 +MACH_E_LOW_SPEED_DIRECTION_CHANGE_FULL_SPEED = 2.0 +MACH_E_LOW_SPEED_DIRECTION_CHANGE_HOLD_SPEED = 2.8 +MACH_E_LOW_SPEED_DIRECTION_CHANGE_FADE_SPEED = 3.5 +MACH_E_LOW_SPEED_DIRECTION_CHANGE_MIN_CURVATURE = 0.0004 +MACH_E_LOW_SPEED_DIRECTION_CHANGE_FULL_CURVATURE = 0.0006 +MACH_E_LOW_SPEED_DIRECTION_CHANGE_MAX_CURVATURE = 0.0015 +MACH_E_SHARP_DIRECTION_CHANGE_START_SPEED = 1.5 +MACH_E_SHARP_DIRECTION_CHANGE_FULL_SPEED = 1.8 +MACH_E_SHARP_DIRECTION_CHANGE_HOLD_SPEED = 3.0 +MACH_E_SHARP_DIRECTION_CHANGE_FADE_SPEED = 4.0 +MACH_E_SHARP_DIRECTION_CHANGE_MIN_CURVATURE = 0.0002 +MACH_E_SHARP_DIRECTION_CHANGE_FULL_CURVATURE = 0.0005 +MACH_E_SHARP_DIRECTION_CHANGE_MIN_PREVIEW_CURVATURE = 0.008 +MACH_E_SHARP_DIRECTION_CHANGE_FULL_PREVIEW_CURVATURE = 0.012 +MACH_E_SHARP_DIRECTION_CHANGE_MIN_ACCEL = 1.8 +MACH_E_SHARP_DIRECTION_CHANGE_FULL_ACCEL = 2.2 +MACH_E_SHARP_DIRECTION_CHANGE_MIN_LAG_CURVATURE = -0.0005 +MACH_E_SHARP_DIRECTION_CHANGE_FULL_LAG_CURVATURE = 0.0008 +MACH_E_CURVATURE_ERROR_MAX = 0.006 +MACH_E_UNDERSTEER_ERROR_MIN_DEFICIT = 0.002 +MACH_E_UNDERSTEER_ERROR_FULL_DEFICIT = 0.004 +MACH_E_PATH_ANGLE_MAX = 0.16 +MACH_E_PATH_ANGLE_STEP = 0.055 +MACH_E_PATH_ANGLE_FADE_START_SPEED = 8.0 +MACH_E_PATH_ANGLE_MAX_SPEED = 8.8 +MACH_E_PATH_ANGLE_TRACKING_FACTOR = 0.75 +MACH_E_PATH_ANGLE_DRIVER_COOLDOWN = 0.75 +MACH_E_DRIVER_ASSIST_MIN_SPEED = 2.0 +MACH_E_DRIVER_ASSIST_MAX_SPEED = 15.0 +MACH_E_DRIVER_ASSIST_MAX_TORQUE = 3.5 +FORD_CURVATURE_LOOKAHEAD = { + CAR.FORD_EXPLORER_MK6: 0.20, +} +FORD_CONSERVATIVE_PREVIEW_CARS = frozenset({ + CAR.FORD_MUSTANG_MACH_E_MK1, +}) +FORD_SHARP_DIRECTION_CHANGE_CARS = frozenset({ + CAR.FORD_MUSTANG_MACH_E_MK1, +}) +FORD_MANUAL_TURN_LATCH_CARS = frozenset({ + CAR.FORD_MUSTANG_MACH_E_MK1, +}) +MANUAL_TURN_ENTRY_ANGLE_DEG = 12.0 +MANUAL_TURN_RELEASE_ANGLE_DEG = 12.0 +MANUAL_TURN_RECOVERY_SECONDS = 0.25 + + +@dataclass(frozen=True) +class FordLateralResult: + curvature: float = 0.0 + curvature_rate: float = 0.0 + path_angle: float = 0.0 + ramp_type: int = 0 + precision_type: int = 1 + active: bool = False + + +# Adapted from BluePilot HumanTurnDetector (Alan Polk, 97867c1eb57b7472f6fc3de62f0fef576e5a5497). +class HumanTurnDetector: + ANGLE_DEG = 45.0 + HOLD_SECONDS = 1.5 + PRETURNED_HOLD_SECONDS = 3.0 + + def __init__(self): + self.timer = 0.0 + self.active = False + self._pressed_last = False + self._press_started_preturned = False + + def update(self, enabled: bool, steering_pressed: bool, steering_angle_deg: float) -> bool: + if steering_pressed and not self._pressed_last: + self._press_started_preturned = abs(steering_angle_deg) > self.ANGLE_DEG + self._pressed_last = steering_pressed + + if enabled and steering_pressed and abs(steering_angle_deg) > self.ANGLE_DEG: + self.timer += STEER_DT + else: + self.timer = 0.0 + + hold_time = self.PRETURNED_HOLD_SECONDS if self._press_started_preturned else self.HOLD_SECONDS + self.active = self.timer + 1e-9 >= hold_time + return self.active + + def reset(self): + self.timer = 0.0 + self.active = False + self._pressed_last = False + self._press_started_preturned = False + + +class FordLateralController: + + def __init__(self, CP): + self.CP = CP + self.model = None + self.time_indices = () + self.lookahead = CURVATURE_LOOKAHEAD_MIN + + self.human_turn_enabled = True + self.curvature_blend_low = 0.4 + self.curvature_blend_high = 0.4 + self.curvature_lane_change_factor = 0.85 + + self.human_turn = HumanTurnDetector() + self.manual_turn_latched = False + self.manual_turn_recovery_timer = 0.0 + self.manual_turn_direction = 0.0 + self.curvature_samples = deque(maxlen=max(2, round(0.3 / STEER_DT))) + self.curvature_last = 0.0 + self.path_angle_last = 0.0 + self.path_angle_driver_cooldown = 0.0 + self.desired_curvature_last = 0.0 + self.turn_in_preview_hold_timer = 0.0 + self.unwind_preview_hold_timer = 0.0 + self.assist_engagement_retained = False + + def set_assist_permission(self, panda_states, healthy: bool): + ford_pandas = [p for p in panda_states if p.safetyModel == structs.CarParams.SafetyModel.ford] if healthy else [] + assist_flags = FordSafetyFlags.CANFD | FordSafetyFlags.MACH_E_EXTENDED + self.assist_engagement_retained = bool(ford_pandas) and all( + p.controlsAllowed and p.safetyParam & assist_flags == assist_flags and + not p.safetyParam & FordSafetyFlags.LKA_STEERING for p in ford_pandas + ) + + def _path_angle_assist_permitted(self, CC, CS) -> bool: + if not CC.enabled or CS.out.brakePressed: + return False + return not CS.out.gasPressed or (CS.out.cruiseState.enabled and self.assist_engagement_retained) + + def set_blend_settings(self, low: float, high: float, lane_change: float): + self.curvature_blend_low = float(np.clip(low if np.isfinite(low) else 0.4, 0.0, 1.0)) + self.curvature_blend_high = float(np.clip(high if np.isfinite(high) else 0.4, 0.0, 1.0)) + self.curvature_lane_change_factor = float(np.clip(lane_change if np.isfinite(lane_change) else 0.85, 0.5, 1.25)) + + def set_inputs(self, model, time_indices, lookahead: float, human_turn_enabled: bool): + self.model = model + self.time_indices = time_indices + self.lookahead = float(np.clip(lookahead, CURVATURE_LOOKAHEAD_MIN, CURVATURE_LOOKAHEAD_MAX)) + self.human_turn_enabled = human_turn_enabled + + def _predicted_curvature(self, v_ego: float, lookup_time: float) -> float: + if self.model is None or len(self.model.orientationRate.z) < 17: + return 0.0 + curvatures = np.asarray(self.model.orientationRate.z) / max(v_ego, 0.01) + return float(np.interp(lookup_time, self.time_indices, curvatures)) + + def _curvature_lookahead(self) -> float: + return self.lookahead + + def _lane_change(self) -> tuple[bool, int]: + if self.model is None: + return False, 0 + state = int(getattr(self.model.meta.laneChangeState, "raw", self.model.meta.laneChangeState)) + direction = int(getattr(self.model.meta.laneChangeDirection, "raw", self.model.meta.laneChangeDirection)) + return state in (1, 2, 3), direction + + def _high_speed_lookahead_extra(self, v_ego: float, steering_pressed: bool, lane_change: bool) -> float: + if (self.CP.carFingerprint != CAR.FORD_MUSTANG_MACH_E_MK1 or not self.CP.flags & FordFlags.CANFD or + steering_pressed or lane_change): + return 0.0 + return MACH_E_HIGH_SPEED_LOOKAHEAD_EXTRA * float(np.interp( + v_ego, [MACH_E_HIGH_SPEED_LOOKAHEAD_START_SPEED, MACH_E_HIGH_SPEED_LOOKAHEAD_FULL_SPEED], [0.0, 1.0])) + + @staticmethod + def _current_curvature(CS) -> float: + return -CS.out.yawRate / max(CS.out.vEgoRaw, 0.1) + + def _driver_assisting_curve(self, CS, desired: float) -> bool: + v_ego = float(CS.out.vEgoRaw) + if (self.CP.carFingerprint != CAR.FORD_MUSTANG_MACH_E_MK1 or not self.CP.flags & FordFlags.CANFD or + not CS.out.steeringPressed or not MACH_E_DRIVER_ASSIST_MIN_SPEED <= v_ego < MACH_E_DRIVER_ASSIST_MAX_SPEED or + self._lane_change()[0] or abs(desired) < MACH_E_TURN_IN_MIN_CURVATURE or + desired * CS.out.steeringTorque >= 0.0 or abs(CS.out.steeringTorque) > MACH_E_DRIVER_ASSIST_MAX_TORQUE): + return False + current = self._current_curvature(CS) + preview = self._predicted_curvature(v_ego, self._curvature_lookahead() + MACH_E_TURN_IN_LOOKAHEAD_EXTRA) + return bool(desired * current > 0.0 and desired * preview > 0.0 and + abs(preview) >= MACH_E_TURN_IN_FULL_CURVATURE and + np.sign(desired) * (current - desired) <= CarControllerParams.CURVATURE_ERROR) + + def _curvature_error_limit(self, requested: float, desired: float, current: float, v_ego: float, + steering_pressed: bool, lane_change: bool, predicted: float = 0.0) -> float: + base = CarControllerParams.CURVATURE_ERROR + if (self.CP.carFingerprint != CAR.FORD_MUSTANG_MACH_E_MK1 or not self.CP.flags & FordFlags.CANFD or + steering_pressed or lane_change): + return base + speed_weight = float(np.interp(v_ego, [8.0, 9.0, 14.0, 16.0], [0.0, 1.0, 1.0, 0.0])) + deficit_weight = 0.0 + planned_curve = abs(desired) >= 0.003 or (abs(requested) >= 0.003 and requested * predicted > 0.0) + if requested * desired > 0.0 and planned_curve: + deficit = np.sign(desired) * (requested - current) + deficit_weight = float(np.interp( + deficit, [MACH_E_UNDERSTEER_ERROR_MIN_DEFICIT, MACH_E_UNDERSTEER_ERROR_FULL_DEFICIT], [0.0, 1.0])) + if current * desired < 0.0: + predicted = self._predicted_curvature(v_ego, self._curvature_lookahead() + MACH_E_TURN_IN_LOOKAHEAD_EXTRA) + reversal_weight = 0.0 + if current * predicted < 0.0 and current * (requested - current) < 0.0: + reversal_weight = float(np.interp( + abs(predicted), + [MACH_E_DIRECTION_CHANGE_MIN_PREVIEW_CURVATURE, MACH_E_DIRECTION_CHANGE_FULL_PREVIEW_CURVATURE], + [0.0, 1.0], + )) + unwind_weight = 0.0 + if (self.model is not None and len(self.model.orientationRate.z) >= 17 and + requested * current >= 0.0 and desired * current >= 0.0 and abs(desired) < abs(current)): + unwind_deficit = np.sign(current) * (current - requested) + preview_deficit = np.sign(current) * (current - predicted) + unwind_weight = float(np.interp( + min(unwind_deficit, preview_deficit), + [MACH_E_UNDERSTEER_ERROR_MIN_DEFICIT, MACH_E_UNDERSTEER_ERROR_FULL_DEFICIT], + [0.0, 1.0], + )) + return base + (MACH_E_CURVATURE_ERROR_MAX - base) * speed_weight * max(deficit_weight, reversal_weight, unwind_weight) + + def _path_angle_assist(self, requested: float, desired: float, applied: float, current: float, v_ego: float, + steering_pressed: bool, lane_change: bool) -> float: + if steering_pressed: + self.path_angle_driver_cooldown = MACH_E_PATH_ANGLE_DRIVER_COOLDOWN + else: + self.path_angle_driver_cooldown = max(0.0, self.path_angle_driver_cooldown - STEER_DT) + target = 0.0 + if (self.CP.carFingerprint == CAR.FORD_MUSTANG_MACH_E_MK1 and self.CP.flags & FordFlags.CANFD and + not steering_pressed and self.path_angle_driver_cooldown == 0.0 and not lane_change and + 3.0 <= v_ego < MACH_E_PATH_ANGLE_MAX_SPEED and + requested * desired > 0.0 and requested * applied > 0.0 and + abs(requested) > 0.0198 and abs(desired) > MACH_E_TURN_IN_FULL_CURVATURE and abs(applied) >= 0.0195 and + np.sign(desired) * (desired - current) > 0.002): + max_curvature = MAX_LATERAL_ACCEL / v_ego ** 2 + residual = max(0.0, min(max(abs(requested), abs(desired)), max_curvature) - abs(applied)) + tracking_deficit = max(0.0, np.sign(applied) * (applied - current)) + acceleration_headroom = max(0.0, (max_curvature - abs(applied)) * v_ego) + speed_weight = float(np.interp( + v_ego, [MACH_E_PATH_ANGLE_FADE_START_SPEED, MACH_E_PATH_ANGLE_MAX_SPEED], [1.0, 0.0])) + target = float(np.sign(applied) * min( + (residual + MACH_E_PATH_ANGLE_TRACKING_FACTOR * tracking_deficit) * v_ego, + acceleration_headroom, MACH_E_PATH_ANGLE_MAX) * speed_weight) + if target == 0.0 or target * self.path_angle_last < 0.0: + self.path_angle_last = 0.0 + else: + self.path_angle_last = float(np.clip( + target, self.path_angle_last - MACH_E_PATH_ANGLE_STEP, self.path_angle_last + MACH_E_PATH_ANGLE_STEP)) + return self.path_angle_last + + def _blend_and_scale(self, desired: float, predicted: float, v_ego: float, current: float = 0.0, + allow_opposite_preview: bool = False) -> tuple[float, int]: + blend = float(np.interp(abs(desired), [0.0, 0.001], [self.curvature_blend_low, self.curvature_blend_high])) + if self.CP.carFingerprint in FORD_CONSERVATIVE_PREVIEW_CARS: + if desired * predicted <= 0.0 and not allow_opposite_preview: + blend = 0.0 + elif current * predicted > 0.0 and abs(current) > abs(desired) and abs(predicted) > abs(desired): + blend *= abs(desired) / abs(predicted) + requested = predicted * blend + desired * (1.0 - blend) + lane_change, direction = self._lane_change() + precision = 1 + if lane_change: + factor = float(np.interp(v_ego, [4.4, 40.23], [0.95, self.curvature_lane_change_factor])) + if (direction == 1 and requested < 0.0) or (direction == 2 and requested > 0.0): + requested *= factor + precision = 0 + return requested, precision + + def _unwind_preview(self, desired: float, predicted: float, current: float, v_ego: float, + allow_plateau: bool = False) -> float: + if self.CP.carFingerprint != CAR.FORD_MUSTANG_MACH_E_MK1: + return predicted + if desired * current <= 0.0 or desired * predicted <= 0.0 or desired * self.desired_curvature_last <= 0.0: + return predicted + if abs(desired) >= abs(self.desired_curvature_last) and not allow_plateau: + return predicted + preview = self._predicted_curvature(v_ego, self._curvature_lookahead() + MACH_E_UNWIND_LOOKAHEAD_EXTRA) + if desired * preview <= 0.0 or abs(preview) >= min(abs(desired), abs(predicted), abs(current)): + return predicted + speed_weight = float(np.interp(v_ego, [5.0, 7.0, 12.0, 15.0], [0.0, 1.0, 1.0, 0.0])) + curvature_weight = float(np.interp(abs(desired), [0.002, 0.008], [0.0, 1.0])) + lag_weight = float(np.interp(abs(current) - abs(desired), [0.0, MACH_E_UNWIND_FULL_LAG_CURVATURE], [0.0, 1.0])) + preview_lag_weight = float(np.interp( + abs(current) - abs(preview), [0.0, MACH_E_UNWIND_PREVIEW_LAG_CURVATURE], [0.0, 1.0])) + lag_weight = max(lag_weight, preview_lag_weight) + return predicted + speed_weight * curvature_weight * lag_weight * (preview - predicted) + + def _turn_in_preview_plateau(self, desired: float, current: float, v_ego: float, + steering_pressed: bool, lane_change: bool) -> float: + if (self.CP.carFingerprint != CAR.FORD_MUSTANG_MACH_E_MK1 or not self.CP.flags & FordFlags.CANFD or + not MACH_E_LOW_SPEED_TURN_IN_START_SPEED <= v_ego < MACH_E_LOW_SPEED_TURN_IN_FADE_SPEED or + steering_pressed or lane_change or desired * self.desired_curvature_last < 0.0 or + abs(desired) < abs(self.desired_curvature_last)): + self.turn_in_preview_hold_timer = 0.0 + return 0.0 + if abs(desired) > abs(self.desired_curvature_last): + self.turn_in_preview_hold_timer = MACH_E_TURN_IN_PREVIEW_HOLD_SECONDS + return 0.0 + self.turn_in_preview_hold_timer = max(0.0, self.turn_in_preview_hold_timer - STEER_DT) + if (self.turn_in_preview_hold_timer <= 1e-9 or + np.sign(desired) * (desired - current) <= MACH_E_TURN_IN_PREVIEW_HOLD_MIN_LAG): + return 0.0 + return float(np.interp(v_ego, [2.0, 3.0, 14.0, 15.0], [0.0, 1.0, 1.0, 0.0])) + + def _unwind_preview_plateau(self, desired: float, v_ego: float, steering_pressed: bool, lane_change: bool) -> bool: + if (self.CP.carFingerprint != CAR.FORD_MUSTANG_MACH_E_MK1 or not self.CP.flags & FordFlags.CANFD or + not 5.0 < v_ego < 15.0 or steering_pressed or lane_change or + desired * self.desired_curvature_last <= 0.0 or + abs(desired) - abs(self.desired_curvature_last) > MACH_E_UNWIND_PREVIEW_RISE_TOLERANCE): + self.unwind_preview_hold_timer = 0.0 + return False + if abs(desired) < abs(self.desired_curvature_last): + self.unwind_preview_hold_timer = MACH_E_UNWIND_PREVIEW_HOLD_SECONDS + return False + self.unwind_preview_hold_timer = max(0.0, self.unwind_preview_hold_timer - STEER_DT) + return self.unwind_preview_hold_timer > 1e-9 + + def _unwind_request(self, desired: float, predicted: float, command_predicted: float, requested: float) -> float: + delta = command_predicted - predicted + if (self.CP.carFingerprint != CAR.FORD_MUSTANG_MACH_E_MK1 or not self.CP.flags & FordFlags.CANFD or + not np.isfinite([desired, predicted, command_predicted, requested]).all() or + desired * command_predicted <= 0.0 or desired * delta >= 0.0): + return requested + release_weight = float(np.interp(abs(delta), [0.002, 0.006], [0.0, 1.0])) + blend = float(np.interp(abs(desired), [0.0, 0.001], [self.curvature_blend_low, self.curvature_blend_high])) + preview_authority = float(np.clip(blend / 0.4, 0.0, 1.0)) + return float(np.clip(requested + MACH_E_UNWIND_RELEASE_GAIN * preview_authority * release_weight * delta, + min(desired, command_predicted), max(desired, command_predicted))) + + def _reversal_followthrough_preview(self, desired: float, predicted: float, current: float, v_ego: float, + steering_pressed: bool, lane_change: bool) -> float: + if (self.CP.carFingerprint != CAR.FORD_MUSTANG_MACH_E_MK1 or not self.CP.flags & FordFlags.CANFD or + steering_pressed or lane_change or desired * current >= 0.0): + return predicted + speed_weight = float(np.interp(v_ego, [8.0, 9.0, 14.0, 16.0], [0.0, 1.0, 1.0, 0.0])) + if speed_weight == 0.0: + return predicted + preview = self._predicted_curvature(v_ego, self._curvature_lookahead() + MACH_E_TURN_IN_LOOKAHEAD_EXTRA) + if not np.isfinite(preview) or desired * preview <= 0.0 or np.sign(desired) * (preview - predicted) <= 0.0: + return predicted + preview_weight = float(np.interp( + abs(preview), [MACH_E_DIRECTION_CHANGE_MIN_PREVIEW_CURVATURE, MACH_E_DIRECTION_CHANGE_FULL_PREVIEW_CURVATURE], + [0.0, 1.0])) + lag_weight = float(np.interp( + abs(current), [MACH_E_DIRECTION_CHANGE_MIN_LAG_CURVATURE, MACH_E_DIRECTION_CHANGE_FULL_LAG_CURVATURE], + [0.0, 1.0])) + return predicted + speed_weight * preview_weight * lag_weight * (preview - predicted) + + def _turn_in_preview_weight(self, desired: float, preview: float, current: float, + allow_plateau: float = 0.0) -> float: + if self.CP.carFingerprint not in FORD_CONSERVATIVE_PREVIEW_CARS: + return 0.0 + if desired * preview <= 0.0 or desired * self.desired_curvature_last < 0.0: + return 0.0 + if (abs(desired) < abs(self.desired_curvature_last) or + (abs(desired) == abs(self.desired_curvature_last) and not allow_plateau)): + return 0.0 + + target = max(abs(desired), abs(preview)) + curvature_weight = float(np.interp( + target, + [MACH_E_TURN_IN_MIN_CURVATURE, MACH_E_TURN_IN_FULL_CURVATURE], + [0.0, 1.0], + )) + direction = float(np.sign(desired)) + lag_weight = float(np.clip( + (target - direction * current) / MACH_E_TURN_IN_LAG_CURVATURE, + 0.0, 1.0, + )) + plateau_weight = allow_plateau if abs(desired) == abs(self.desired_curvature_last) else 1.0 + return curvature_weight * lag_weight * plateau_weight + + def _turn_in_curvature_rate(self, desired: float, current: float, curvature_rate: float, + v_ego: float, lookahead: float, steering_pressed: bool, lane_change: bool) -> float: + if (self.CP.carFingerprint != CAR.FORD_MUSTANG_MACH_E_MK1 or not self.CP.flags & FordFlags.CANFD or + not MACH_E_TURN_IN_RATE_MIN_SPEED <= v_ego < MACH_E_LOW_SPEED_TURN_IN_FADE_SPEED or + steering_pressed or lane_change or desired * self.desired_curvature_last <= 0.0 or + abs(desired) < abs(self.desired_curvature_last) or desired * curvature_rate >= 0.0 or + np.sign(desired) * (desired - current) <= MACH_E_TURN_IN_RATE_MIN_DEFICIT): + return curvature_rate + preview = self._predicted_curvature(v_ego, lookahead + MACH_E_TURN_IN_LOOKAHEAD_EXTRA) + if (desired * preview > 0.0 and abs(preview) >= abs(desired) and + np.sign(desired) * (preview - current) > MACH_E_TURN_IN_RATE_MIN_DEFICIT): + return 0.0 + return curvature_rate + + @staticmethod + def _turn_in_lookahead_extra(v_ego: float) -> float: + return float(np.interp( + v_ego, + [MACH_E_LOW_SPEED_TURN_IN_START_SPEED, MACH_E_LOW_SPEED_TURN_IN_FULL_SPEED, + MACH_E_LOW_SPEED_TURN_IN_MAX_SPEED, MACH_E_LOW_SPEED_TURN_IN_FADE_SPEED], + [MACH_E_TURN_IN_LOOKAHEAD_EXTRA, MACH_E_LOW_SPEED_TURN_IN_LOOKAHEAD_EXTRA, + MACH_E_LOW_SPEED_TURN_IN_LOOKAHEAD_EXTRA, MACH_E_TURN_IN_LOOKAHEAD_EXTRA], + )) + + @staticmethod + def _direction_change_lookahead_extra(v_ego: float) -> float: + return float(np.interp( + v_ego, + [MACH_E_DIRECTION_CHANGE_MIN_SPEED, MACH_E_DIRECTION_CHANGE_LOOKAHEAD_RAMP_SPEED, + MACH_E_DIRECTION_CHANGE_LOOKAHEAD_FULL_SPEED, MACH_E_DIRECTION_CHANGE_LOOKAHEAD_FADE_SPEED], + [MACH_E_TURN_IN_LOOKAHEAD_EXTRA, MACH_E_DIRECTION_CHANGE_LOOKAHEAD_EXTRA, + MACH_E_DIRECTION_CHANGE_LOOKAHEAD_EXTRA, MACH_E_TURN_IN_LOOKAHEAD_EXTRA], + )) + + def _direction_change_preview_weight(self, desired: float, preview: float, current: float, + allow_rising_desired: bool = False, early_handoff_weight: float = 0.0, + sharp_handoff: bool = False) -> float: + if self.CP.carFingerprint not in FORD_CONSERVATIVE_PREVIEW_CARS: + return 0.0 + if desired * preview >= 0.0 or desired * self.desired_curvature_last <= 0.0 or desired * current <= 0.0: + return 0.0 + early_handoff_weight = float(np.clip(early_handoff_weight, 0.0, 1.0)) + lag = abs(current) - abs(desired) + if sharp_handoff: + lag_min = MACH_E_SHARP_DIRECTION_CHANGE_MIN_LAG_CURVATURE + lag_full = MACH_E_SHARP_DIRECTION_CHANGE_FULL_LAG_CURVATURE + else: + lag_min = float(np.interp( + early_handoff_weight, [0.0, 1.0], + [MACH_E_DIRECTION_CHANGE_MIN_LAG_CURVATURE, MACH_E_DIRECTION_CHANGE_EARLY_MIN_LAG_CURVATURE], + )) + lag_full = float(np.interp( + early_handoff_weight, [0.0, 1.0], + [MACH_E_DIRECTION_CHANGE_FULL_LAG_CURVATURE, MACH_E_DIRECTION_CHANGE_EARLY_FULL_LAG_CURVATURE], + )) + desired_rising = abs(desired) >= abs(self.desired_curvature_last) + rising_handoff = (allow_rising_desired and abs(desired) > abs(self.desired_curvature_last) and + abs(desired) <= MACH_E_LOW_SPEED_DIRECTION_CHANGE_MAX_CURVATURE) + early_rising_handoff = early_handoff_weight > 0.0 and lag > lag_min + if desired_rising and not rising_handoff and not early_rising_handoff: + return 0.0 + + preview_weight = float(np.interp( + abs(preview), + [MACH_E_DIRECTION_CHANGE_MIN_PREVIEW_CURVATURE, MACH_E_DIRECTION_CHANGE_FULL_PREVIEW_CURVATURE], + [0.0, 1.0], + )) + if sharp_handoff: + preview_weight *= float(np.interp( + abs(preview), + [MACH_E_SHARP_DIRECTION_CHANGE_MIN_PREVIEW_CURVATURE, MACH_E_SHARP_DIRECTION_CHANGE_FULL_PREVIEW_CURVATURE], + [0.0, 1.0], + )) + lag_weight = float(np.interp( + lag, + [lag_min, lag_full], + [0.0, 1.0], + )) + return preview_weight * lag_weight + + @staticmethod + def _low_speed_direction_change_weight(v_ego: float, desired: float) -> float: + speed_weight = float(np.interp( + v_ego, + [MACH_E_LOW_SPEED_DIRECTION_CHANGE_START_SPEED, MACH_E_LOW_SPEED_DIRECTION_CHANGE_FULL_SPEED, + MACH_E_LOW_SPEED_DIRECTION_CHANGE_HOLD_SPEED, MACH_E_LOW_SPEED_DIRECTION_CHANGE_FADE_SPEED], + [0.0, 1.0, 1.0, 0.0], + )) + curvature_weight = float(np.interp( + abs(desired), + [MACH_E_LOW_SPEED_DIRECTION_CHANGE_MIN_CURVATURE, MACH_E_LOW_SPEED_DIRECTION_CHANGE_FULL_CURVATURE], + [0.0, 1.0], + )) + return speed_weight * curvature_weight + + @staticmethod + def _sharp_direction_change_weight(v_ego: float, a_ego: float, desired: float, preview: float) -> float: + speed_weight = float(np.interp( + v_ego, + [MACH_E_SHARP_DIRECTION_CHANGE_START_SPEED, MACH_E_SHARP_DIRECTION_CHANGE_FULL_SPEED, + MACH_E_SHARP_DIRECTION_CHANGE_HOLD_SPEED, MACH_E_SHARP_DIRECTION_CHANGE_FADE_SPEED], + [0.0, 1.0, 1.0, 0.0], + )) + curvature_weight = float(np.interp( + abs(desired), + [MACH_E_SHARP_DIRECTION_CHANGE_MIN_CURVATURE, MACH_E_SHARP_DIRECTION_CHANGE_FULL_CURVATURE], + [0.0, 1.0], + )) + preview_weight = float(np.interp( + abs(preview), + [MACH_E_SHARP_DIRECTION_CHANGE_MIN_PREVIEW_CURVATURE, MACH_E_SHARP_DIRECTION_CHANGE_FULL_PREVIEW_CURVATURE], + [0.0, 1.0], + )) + acceleration_weight = float(np.interp( + a_ego, + [MACH_E_SHARP_DIRECTION_CHANGE_MIN_ACCEL, MACH_E_SHARP_DIRECTION_CHANGE_FULL_ACCEL], + [0.0, 1.0], + )) + return speed_weight * curvature_weight * preview_weight * acceleration_weight + + def _manual_turn(self, CC, CS, desired: float, driver_assisting: bool = False) -> bool: + if not CC.latActive: + self.human_turn.reset() + self.manual_turn_latched = False + self.manual_turn_recovery_timer = 0.0 + self.manual_turn_direction = 0.0 + return False + detected = self.human_turn.update( + self.human_turn_enabled and not driver_assisting, CS.out.steeringPressed, CS.out.steeringAngleDeg) + if self.CP.carFingerprint not in FORD_MANUAL_TURN_LATCH_CARS: + return detected + + if not self.human_turn_enabled: + self.manual_turn_latched = False + self.manual_turn_recovery_timer = 0.0 + self.manual_turn_direction = 0.0 + return False + + blinker_direction = float(CS.out.rightBlinker) - float(CS.out.leftBlinker) + driver_turning_with_signal = ( + CS.out.steeringPressed and not driver_assisting and abs(CS.out.steeringAngleDeg) >= MANUAL_TURN_ENTRY_ANGLE_DEG and + blinker_direction != 0.0 and not self._lane_change()[0] and + CS.out.steeringTorque * blinker_direction < 0.0 + ) + if self.model is not None and (detected or driver_turning_with_signal): + self.manual_turn_latched = True + if blinker_direction != 0.0: + self.manual_turn_direction = blinker_direction + elif self.manual_turn_direction == 0.0: + self.manual_turn_direction = -float(np.sign(CS.out.steeringAngleDeg)) + + if not self.manual_turn_latched: + self.manual_turn_recovery_timer = 0.0 + self.manual_turn_direction = 0.0 + return False + + following_next_curve = ( + driver_assisting and not CS.out.leftBlinker and not CS.out.rightBlinker and + CS.out.vEgoRaw >= MACH_E_DIRECTION_CHANGE_MIN_SPEED and self.manual_turn_direction * desired < 0.0 + ) + if not following_next_curve and (CS.out.steeringPressed or blinker_direction != 0.0 or + abs(CS.out.steeringAngleDeg) > MANUAL_TURN_RELEASE_ANGLE_DEG): + self.manual_turn_recovery_timer = 0.0 + else: + self.manual_turn_recovery_timer += STEER_DT + if self.manual_turn_recovery_timer + 1e-9 >= MANUAL_TURN_RECOVERY_SECONDS: + current = self._current_curvature(CS) + if (self.manual_turn_direction * desired > 0.0 and + self.manual_turn_direction * (desired - current) > CarControllerParams.CURVATURE_ERROR): + self.manual_turn_recovery_timer = MANUAL_TURN_RECOVERY_SECONDS + else: + self.manual_turn_latched = False + self.manual_turn_recovery_timer = 0.0 + self.manual_turn_direction = 0.0 + + return self.manual_turn_latched + + def update(self, CC, CS, actuators) -> FordLateralResult: + current = self._current_curvature(CS) + if not CC.latActive: + self.human_turn.reset() + self.manual_turn_latched = False + self.manual_turn_recovery_timer = 0.0 + self.manual_turn_direction = 0.0 + self.curvature_samples.clear() + self.curvature_last = 0.0 + self.path_angle_last = 0.0 + self.path_angle_driver_cooldown = 0.0 + self.desired_curvature_last = 0.0 + self.turn_in_preview_hold_timer = 0.0 + self.unwind_preview_hold_timer = 0.0 + return FordLateralResult() + + desired = float(actuators.curvature) + driver_assisting = self._driver_assisting_curve(CS, desired) + driver_override = bool(CS.out.steeringPressed) and not driver_assisting + manual_turn = self._manual_turn(CC, CS, desired, driver_assisting) + if manual_turn or CS.out.vEgoRaw < 0.1: + if CS.out.steeringPressed: + self.path_angle_driver_cooldown = MACH_E_PATH_ANGLE_DRIVER_COOLDOWN + self.curvature_samples.clear() + self.curvature_last = 0.0 + self.path_angle_last = 0.0 + self.desired_curvature_last = 0.0 + self.turn_in_preview_hold_timer = 0.0 + self.unwind_preview_hold_timer = 0.0 + return FordLateralResult(active=not ( + manual_turn and self.CP.carFingerprint in FORD_MANUAL_TURN_LATCH_CARS)) + + v_ego = float(CS.out.vEgoRaw) + lookahead = self._curvature_lookahead() + lookahead += self._high_speed_lookahead_extra(v_ego, bool(CS.out.steeringPressed), self._lane_change()[0]) + predicted = self._predicted_curvature(v_ego, lookahead) + allow_opposite_preview = False + if self.CP.carFingerprint in FORD_CONSERVATIVE_PREVIEW_CARS: + turn_in_plateau = self._turn_in_preview_plateau( + desired, current, v_ego, bool(CS.out.steeringPressed), self._lane_change()[0]) + turn_in_predicted = self._predicted_curvature(v_ego, lookahead + MACH_E_TURN_IN_LOOKAHEAD_EXTRA) + direction_change_predicted = turn_in_predicted + direction_change_weight = 0.0 + sharp_direction_change_weight = 0.0 + direction_change_speed_weight = float(v_ego > MACH_E_DIRECTION_CHANGE_MIN_SPEED) + low_speed_direction_change = direction_change_speed_weight == 0.0 + if direction_change_speed_weight == 0.0: + direction_change_speed_weight = self._low_speed_direction_change_weight(v_ego, desired) + if self.CP.carFingerprint in FORD_SHARP_DIRECTION_CHANGE_CARS: + sharp_direction_change_weight = self._sharp_direction_change_weight( + v_ego, float(CS.out.aEgo), desired, turn_in_predicted) + direction_change_speed_weight = max(direction_change_speed_weight, sharp_direction_change_weight) + if direction_change_speed_weight > 0.0 and not CS.out.steeringPressed and not self._lane_change()[0]: + direction_change_lookahead_extra = self._direction_change_lookahead_extra(v_ego) + early_handoff_weight = float(np.interp( + direction_change_lookahead_extra, + [MACH_E_TURN_IN_LOOKAHEAD_EXTRA, MACH_E_DIRECTION_CHANGE_LOOKAHEAD_EXTRA], + [0.0, 1.0], + )) + early_handoff_weight *= float(np.interp( + abs(desired), + [MACH_E_DIRECTION_CHANGE_EARLY_MIN_CURVATURE, MACH_E_DIRECTION_CHANGE_EARLY_FULL_CURVATURE], + [0.0, 1.0], + )) + if direction_change_lookahead_extra > MACH_E_TURN_IN_LOOKAHEAD_EXTRA: + direction_change_predicted = self._predicted_curvature(v_ego, lookahead + direction_change_lookahead_extra) + direction_change_weight = self._direction_change_preview_weight( + desired, direction_change_predicted, current, allow_rising_desired=low_speed_direction_change, + early_handoff_weight=early_handoff_weight, sharp_handoff=sharp_direction_change_weight > 0.0) + direction_change_weight *= direction_change_speed_weight + if direction_change_weight > 0.0: + predicted = float(np.interp(direction_change_weight, [0.0, 1.0], [predicted, direction_change_predicted])) + allow_opposite_preview = True + else: + turn_in_lookahead_extra = self._turn_in_lookahead_extra(v_ego) + if (turn_in_lookahead_extra > MACH_E_TURN_IN_LOOKAHEAD_EXTRA and + desired * self.desired_curvature_last >= 0.0 and + (abs(desired) > abs(self.desired_curvature_last) or turn_in_plateau)): + low_speed_turn_in_predicted = self._predicted_curvature(v_ego, lookahead + turn_in_lookahead_extra) + if (desired * low_speed_turn_in_predicted > 0.0 and + abs(low_speed_turn_in_predicted) > abs(turn_in_predicted)): + turn_in_predicted = low_speed_turn_in_predicted + turn_in_weight = self._turn_in_preview_weight(desired, turn_in_predicted, current, turn_in_plateau) + if turn_in_weight > 0.0: + turn_in_target = float(np.copysign(max(abs(desired), abs(turn_in_predicted)), desired)) + predicted = float(np.interp(turn_in_weight, [0.0, 1.0], [predicted, turn_in_target])) + unwind_plateau = self._unwind_preview_plateau( + desired, v_ego, bool(CS.out.steeringPressed), self._lane_change()[0]) + command_predicted = predicted + canfd_mach_e = self.CP.carFingerprint == CAR.FORD_MUSTANG_MACH_E_MK1 and self.CP.flags & FordFlags.CANFD + if (not allow_opposite_preview or canfd_mach_e) and not CS.out.steeringPressed and not self._lane_change()[0]: + command_predicted = self._unwind_preview(desired, predicted, current, v_ego, unwind_plateau) + unwind_selected = command_predicted != predicted + command_predicted = self._reversal_followthrough_preview( + desired, command_predicted, current, v_ego, bool(CS.out.steeringPressed), self._lane_change()[0]) + requested, precision = self._blend_and_scale(desired, command_predicted, v_ego, current, allow_opposite_preview) + if unwind_selected: + requested = self._unwind_request(desired, predicted, command_predicted, requested) + + if v_ego > 9.0: + error_limit = self._curvature_error_limit( + requested, desired, current, v_ego, driver_override, self._lane_change()[0], command_predicted) + requested = float(np.clip(requested, current - error_limit, current + error_limit)) + applied = float(apply_std_steer_angle_limits( + requested, self.curvature_last, v_ego, CS.out.steeringAngleDeg, True, FORD_CURVATURE_LIMITS)) + if self.CP.flags & FordFlags.CANFD: + max_curvature = MAX_LATERAL_ACCEL / max(v_ego, 1.0) ** 2 + applied = float(np.clip(applied, -max_curvature, max_curvature)) + path_angle = self._path_angle_assist( + requested, desired, applied, current, v_ego, driver_override, self._lane_change()[0]) + if path_angle != 0.0 and not self._path_angle_assist_permitted(CC, CS): + self.path_angle_last = 0.0 + path_angle = 0.0 + + self.curvature_samples.append(predicted) + curvature_rate = 0.0 + if len(self.curvature_samples) > 1: + sample_time = (len(self.curvature_samples) - 1) * STEER_DT + curvature_rate = (self.curvature_samples[-1] - self.curvature_samples[0]) / max(sample_time * v_ego, 0.01) + curvature_rate *= float(np.interp(abs(predicted), [0.0, 0.008, 0.01], [0.0, 0.0, 1.0])) + curvature_rate *= float(np.interp(v_ego, [0.0, 14.5, 15.5], [1.0, 1.0, 0.0])) + if self._lane_change()[0]: + curvature_rate = 0.0 + + if (self.CP.carFingerprint == CAR.FORD_MUSTANG_MACH_E_MK1 and self.CP.flags & FordFlags.CANFD and + unwind_selected and command_predicted * curvature_rate > 0.0): + curvature_rate = 0.0 + + curvature_rate = self._turn_in_curvature_rate( + desired, current, curvature_rate, v_ego, lookahead, bool(CS.out.steeringPressed), self._lane_change()[0]) + self.desired_curvature_last = desired + + self.curvature_last = float(np.clip(applied, -0.02, 0.02)) + min_curvature_rate = -0.001024 + if self.CP.carFingerprint == CAR.FORD_MUSTANG_MACH_E_MK1 and self.CP.flags & FordFlags.CANFD: + min_curvature_rate = -0.001023 + curvature_rate = float(np.clip(curvature_rate, min_curvature_rate, 0.001023)) + return FordLateralResult( + curvature=self.curvature_last, + curvature_rate=curvature_rate, + path_angle=path_angle, + ramp_type=2, + precision_type=precision, + active=True, + ) diff --git a/opendbc_repo/opendbc/car/ford/mache_can.py b/opendbc_repo/opendbc/car/ford/mache_can.py new file mode 100644 index 0000000000..be451d801c --- /dev/null +++ b/opendbc_repo/opendbc/car/ford/mache_can.py @@ -0,0 +1,50 @@ +"""Ford extended-lateral CAN constructors. + +Adapted from BluePilot's ``fordcan_ext.py`` and extended-lateral protocol at bp-7.0 commit +e1d051d7ba270261b4455068bd68f1a58db15a4a, including panda integration developed principally by +Alan Polk. See CREDITS.md and THIRD_PARTY_NOTICES.md for detailed provenance and terms. +""" + +from opendbc.car.ford.fordcan import CanBus + + +def calculate_lat_ctl2_checksum(mode: int, counter: int, dat: bytearray) -> int: + curvature = (dat[2] << 3) | ((dat[3]) >> 5) + curvature_rate = (dat[6] << 3) | ((dat[7]) >> 5) + path_angle = ((dat[3] & 0x1F) << 6) | ((dat[4]) >> 2) + path_offset = ((dat[4] & 0x3) << 8) | dat[5] + + checksum = mode + counter + for sig_val in (curvature, curvature_rate, path_angle, path_offset): + checksum += sig_val + (sig_val >> 8) + + return 0xFF - (checksum & 0xFF) + + + +def create_lka_msg(packer, CAN: CanBus): + addr, dat, bus = packer.make_can_msg("Lane_Assist_Data1", CAN.main, {}) + dat = bytearray(dat) + dat[4] |= 0x2 + return addr, bytes(dat), bus + + + + +def create_lat_ctl2_msg(packer, CAN: CanBus, mode: int, ramp_type: int, precision_type: int, + curvature: float, curvature_rate: float, counter: int, path_angle: float = 0.0): + values = { + "LatCtl_D2_Rq": mode, + "LatCtlRampType_D_Rq": ramp_type, + "LatCtlPrecision_D_Rq": precision_type, + "LatCtlPathOffst_L_Actl": 0.0, + "LatCtlPath_An_Actl": path_angle, + "LatCtlCurv_No_Actl": curvature, + "LatCtlCrv_NoRate2_Actl": curvature_rate, + "HandsOffCnfm_B_Rq": 0, + "LatCtlPath_No_Cnt": counter, + "LatCtlPath_No_Cs": 0, + } + dat = packer.make_can_msg("LateralMotionControl2", 0, values)[1] + values["LatCtlPath_No_Cs"] = calculate_lat_ctl2_checksum(mode, counter, dat) + return packer.make_can_msg("LateralMotionControl2", CAN.main, values) diff --git a/opendbc_repo/opendbc/car/ford/mache_lateral.py b/opendbc_repo/opendbc/car/ford/mache_lateral.py new file mode 100644 index 0000000000..6159de95e0 --- /dev/null +++ b/opendbc_repo/opendbc/car/ford/mache_lateral.py @@ -0,0 +1,147 @@ +"""Ford lateral-control extensions. + +The extended curvature strategy, manual-turn detector, and related safety protocol are substantially +adapted from BluePilot's Ford work, principally by Alan Polk and additional contributors. The audited +bp-7.0 reference is e1d051d7ba270261b4455068bd68f1a58db15a4a; source attribution is retained in +CREDITS.md and THIRD_PARTY_NOTICES.md. StarPilot reorganized that work for its own architecture and has since +changed its tuning and lookahead behavior. + +See CREDITS.md for feature-level authorship and upstream commits, and THIRD_PARTY_NOTICES.md for the +published upstream license notices. Upstream contributors do not maintain this adaptation. + +Mach-E admission and modern command envelope; pure strategy is shared separately. +""" + +from dataclasses import replace + +import numpy as np + +from opendbc.car import structs +from opendbc.car.ford.values import CAR, FordFlags, FordSafetyFlags +from opendbc.car.lateral import MAX_LATERAL_JERK +from opendbc.car.ford.lateral_strategy import ( + FordLateralController, + FORD_CURVATURE_LIMITS as FORD_CURVATURE_LIMITS, + MAX_LATERAL_ACCEL as MAX_LATERAL_ACCEL, + STEER_DT as STEER_DT, + CURVATURE_LOOKAHEAD_MIN as CURVATURE_LOOKAHEAD_MIN, + CURVATURE_LOOKAHEAD_MAX as CURVATURE_LOOKAHEAD_MAX, + MACH_E_TURN_IN_LOOKAHEAD_EXTRA as MACH_E_TURN_IN_LOOKAHEAD_EXTRA, + MACH_E_LOW_SPEED_TURN_IN_LOOKAHEAD_EXTRA as MACH_E_LOW_SPEED_TURN_IN_LOOKAHEAD_EXTRA, + MACH_E_LOW_SPEED_TURN_IN_START_SPEED as MACH_E_LOW_SPEED_TURN_IN_START_SPEED, + MACH_E_LOW_SPEED_TURN_IN_FULL_SPEED as MACH_E_LOW_SPEED_TURN_IN_FULL_SPEED, + MACH_E_LOW_SPEED_TURN_IN_MAX_SPEED as MACH_E_LOW_SPEED_TURN_IN_MAX_SPEED, + MACH_E_LOW_SPEED_TURN_IN_FADE_SPEED as MACH_E_LOW_SPEED_TURN_IN_FADE_SPEED, + MACH_E_TURN_IN_MIN_CURVATURE as MACH_E_TURN_IN_MIN_CURVATURE, + MACH_E_TURN_IN_FULL_CURVATURE as MACH_E_TURN_IN_FULL_CURVATURE, + MACH_E_TURN_IN_LAG_CURVATURE as MACH_E_TURN_IN_LAG_CURVATURE, + MACH_E_UNWIND_LOOKAHEAD_EXTRA as MACH_E_UNWIND_LOOKAHEAD_EXTRA, + MACH_E_UNWIND_FULL_LAG_CURVATURE as MACH_E_UNWIND_FULL_LAG_CURVATURE, + MACH_E_UNWIND_PREVIEW_LAG_CURVATURE as MACH_E_UNWIND_PREVIEW_LAG_CURVATURE, + MACH_E_DIRECTION_CHANGE_MIN_SPEED as MACH_E_DIRECTION_CHANGE_MIN_SPEED, + MACH_E_DIRECTION_CHANGE_LOOKAHEAD_RAMP_SPEED as MACH_E_DIRECTION_CHANGE_LOOKAHEAD_RAMP_SPEED, + MACH_E_DIRECTION_CHANGE_LOOKAHEAD_FULL_SPEED as MACH_E_DIRECTION_CHANGE_LOOKAHEAD_FULL_SPEED, + MACH_E_DIRECTION_CHANGE_LOOKAHEAD_FADE_SPEED as MACH_E_DIRECTION_CHANGE_LOOKAHEAD_FADE_SPEED, + MACH_E_DIRECTION_CHANGE_LOOKAHEAD_EXTRA as MACH_E_DIRECTION_CHANGE_LOOKAHEAD_EXTRA, + MACH_E_DIRECTION_CHANGE_MIN_PREVIEW_CURVATURE as MACH_E_DIRECTION_CHANGE_MIN_PREVIEW_CURVATURE, + MACH_E_DIRECTION_CHANGE_FULL_PREVIEW_CURVATURE as MACH_E_DIRECTION_CHANGE_FULL_PREVIEW_CURVATURE, + MACH_E_DIRECTION_CHANGE_MIN_LAG_CURVATURE as MACH_E_DIRECTION_CHANGE_MIN_LAG_CURVATURE, + MACH_E_DIRECTION_CHANGE_FULL_LAG_CURVATURE as MACH_E_DIRECTION_CHANGE_FULL_LAG_CURVATURE, + MACH_E_DIRECTION_CHANGE_EARLY_MIN_LAG_CURVATURE as MACH_E_DIRECTION_CHANGE_EARLY_MIN_LAG_CURVATURE, + MACH_E_DIRECTION_CHANGE_EARLY_FULL_LAG_CURVATURE as MACH_E_DIRECTION_CHANGE_EARLY_FULL_LAG_CURVATURE, + MACH_E_DIRECTION_CHANGE_EARLY_MIN_CURVATURE as MACH_E_DIRECTION_CHANGE_EARLY_MIN_CURVATURE, + MACH_E_DIRECTION_CHANGE_EARLY_FULL_CURVATURE as MACH_E_DIRECTION_CHANGE_EARLY_FULL_CURVATURE, + MACH_E_LOW_SPEED_DIRECTION_CHANGE_START_SPEED as MACH_E_LOW_SPEED_DIRECTION_CHANGE_START_SPEED, + MACH_E_LOW_SPEED_DIRECTION_CHANGE_FULL_SPEED as MACH_E_LOW_SPEED_DIRECTION_CHANGE_FULL_SPEED, + MACH_E_LOW_SPEED_DIRECTION_CHANGE_HOLD_SPEED as MACH_E_LOW_SPEED_DIRECTION_CHANGE_HOLD_SPEED, + MACH_E_LOW_SPEED_DIRECTION_CHANGE_FADE_SPEED as MACH_E_LOW_SPEED_DIRECTION_CHANGE_FADE_SPEED, + MACH_E_LOW_SPEED_DIRECTION_CHANGE_MIN_CURVATURE as MACH_E_LOW_SPEED_DIRECTION_CHANGE_MIN_CURVATURE, + MACH_E_LOW_SPEED_DIRECTION_CHANGE_FULL_CURVATURE as MACH_E_LOW_SPEED_DIRECTION_CHANGE_FULL_CURVATURE, + MACH_E_LOW_SPEED_DIRECTION_CHANGE_MAX_CURVATURE as MACH_E_LOW_SPEED_DIRECTION_CHANGE_MAX_CURVATURE, + MACH_E_SHARP_DIRECTION_CHANGE_START_SPEED as MACH_E_SHARP_DIRECTION_CHANGE_START_SPEED, + MACH_E_SHARP_DIRECTION_CHANGE_FULL_SPEED as MACH_E_SHARP_DIRECTION_CHANGE_FULL_SPEED, + MACH_E_SHARP_DIRECTION_CHANGE_HOLD_SPEED as MACH_E_SHARP_DIRECTION_CHANGE_HOLD_SPEED, + MACH_E_SHARP_DIRECTION_CHANGE_FADE_SPEED as MACH_E_SHARP_DIRECTION_CHANGE_FADE_SPEED, + MACH_E_SHARP_DIRECTION_CHANGE_MIN_CURVATURE as MACH_E_SHARP_DIRECTION_CHANGE_MIN_CURVATURE, + MACH_E_SHARP_DIRECTION_CHANGE_FULL_CURVATURE as MACH_E_SHARP_DIRECTION_CHANGE_FULL_CURVATURE, + MACH_E_SHARP_DIRECTION_CHANGE_MIN_PREVIEW_CURVATURE as MACH_E_SHARP_DIRECTION_CHANGE_MIN_PREVIEW_CURVATURE, + MACH_E_SHARP_DIRECTION_CHANGE_FULL_PREVIEW_CURVATURE as MACH_E_SHARP_DIRECTION_CHANGE_FULL_PREVIEW_CURVATURE, + MACH_E_SHARP_DIRECTION_CHANGE_MIN_ACCEL as MACH_E_SHARP_DIRECTION_CHANGE_MIN_ACCEL, + MACH_E_SHARP_DIRECTION_CHANGE_FULL_ACCEL as MACH_E_SHARP_DIRECTION_CHANGE_FULL_ACCEL, + MACH_E_SHARP_DIRECTION_CHANGE_MIN_LAG_CURVATURE as MACH_E_SHARP_DIRECTION_CHANGE_MIN_LAG_CURVATURE, + MACH_E_SHARP_DIRECTION_CHANGE_FULL_LAG_CURVATURE as MACH_E_SHARP_DIRECTION_CHANGE_FULL_LAG_CURVATURE, + MACH_E_CURVATURE_ERROR_MAX as MACH_E_CURVATURE_ERROR_MAX, + MACH_E_UNDERSTEER_ERROR_MIN_DEFICIT as MACH_E_UNDERSTEER_ERROR_MIN_DEFICIT, + MACH_E_UNDERSTEER_ERROR_FULL_DEFICIT as MACH_E_UNDERSTEER_ERROR_FULL_DEFICIT, + MACH_E_PATH_ANGLE_MAX as MACH_E_PATH_ANGLE_MAX, + MACH_E_PATH_ANGLE_STEP as MACH_E_PATH_ANGLE_STEP, + MACH_E_PATH_ANGLE_FADE_START_SPEED as MACH_E_PATH_ANGLE_FADE_START_SPEED, + MACH_E_PATH_ANGLE_MAX_SPEED as MACH_E_PATH_ANGLE_MAX_SPEED, + MACH_E_PATH_ANGLE_TRACKING_FACTOR as MACH_E_PATH_ANGLE_TRACKING_FACTOR, + MACH_E_PATH_ANGLE_DRIVER_COOLDOWN as MACH_E_PATH_ANGLE_DRIVER_COOLDOWN, + MACH_E_DRIVER_ASSIST_MIN_SPEED as MACH_E_DRIVER_ASSIST_MIN_SPEED, + MACH_E_DRIVER_ASSIST_MAX_SPEED as MACH_E_DRIVER_ASSIST_MAX_SPEED, + MACH_E_DRIVER_ASSIST_MAX_TORQUE as MACH_E_DRIVER_ASSIST_MAX_TORQUE, + FORD_CURVATURE_LOOKAHEAD as FORD_CURVATURE_LOOKAHEAD, + FORD_CONSERVATIVE_PREVIEW_CARS as FORD_CONSERVATIVE_PREVIEW_CARS, + FORD_SHARP_DIRECTION_CHANGE_CARS as FORD_SHARP_DIRECTION_CHANGE_CARS, + FORD_MANUAL_TURN_LATCH_CARS as FORD_MANUAL_TURN_LATCH_CARS, + MANUAL_TURN_ENTRY_ANGLE_DEG as MANUAL_TURN_ENTRY_ANGLE_DEG, + MANUAL_TURN_RELEASE_ANGLE_DEG as MANUAL_TURN_RELEASE_ANGLE_DEG, + MANUAL_TURN_RECOVERY_SECONDS as MANUAL_TURN_RECOVERY_SECONDS, + FordLateralResult as FordLateralResult, + HumanTurnDetector as HumanTurnDetector, +) + + +class MachELateralController(FordLateralController): + """Compatibility owner for the exact admitted Mach-E profile.""" + + +def qualified(CP) -> bool: + if CP.alternativeExperience == 32 and len(CP.safetyConfigs) != 1: + return False + if (CP.brand != "ford" or CP.carFingerprint != CAR.FORD_MUSTANG_MACH_E_MK1 or + not CP.flags & FordFlags.CANFD or CP.flags & ~int(FordFlags.CANFD | FordFlags.HAS_BSM) or + CP.passive or CP.dashcamOnly or CP.notCar or CP.alternativeExperience not in (0, 32) or + len(CP.safetyConfigs) not in (1, 2)): + return False + if len(CP.safetyConfigs) == 2 and (CP.safetyConfigs[0].safetyModel != structs.CarParams.SafetyModel.noOutput or + CP.safetyConfigs[0].safetyParam != 0): + return False + safety = CP.safetyConfigs[-1] + return (safety.safetyModel == structs.CarParams.SafetyModel.ford and + safety.safetyParam == int(FordSafetyFlags.CANFD | FordSafetyFlags.MACH_E_EXTENDED | + (FordSafetyFlags.LONG_CONTROL if CP.openpilotLongitudinalControl else 0))) + + +def bounded_command(owner: MachELateralController, demanded: FordLateralResult, previous: float, speed: float, + previous_path_angle: float = 0.0) -> FordLateralResult: + """Intersect original demand with modern transient limits and old absolute cap. + + A discontinuous speed change may leave no legal active interval. Withdraw the + request then, rather than clipping outside the jerk interval. Histories always + follow emitted fields; the original demand remains observable separately. + """ + cap = min(0.02, MAX_LATERAL_ACCEL / max(speed, 1.0) ** 2) + jerk_delta = MAX_LATERAL_JERK / max(speed, 1.0) ** 2 * STEER_DT + low, high = max(-cap, previous - jerk_delta), min(cap, previous + jerk_delta) + if not demanded.active or low > high: + command = FordLateralResult() + else: + curvature = float(np.clip(demanded.curvature, low, high)) + path_angle = 0.0 + if (3.0 <= speed < MACH_E_PATH_ANGLE_MAX_SPEED and abs(curvature) >= 0.0195 and + curvature * demanded.path_angle > 0.0): + headroom = max(0.0, (MAX_LATERAL_ACCEL / speed ** 2 - abs(curvature)) * speed) + path_cap = min(MACH_E_PATH_ANGLE_MAX, headroom) + path_low = max(-path_cap, previous_path_angle - MACH_E_PATH_ANGLE_STEP) + path_high = min(path_cap, previous_path_angle + MACH_E_PATH_ANGLE_STEP) + if path_low <= path_high: + path_angle = float(np.clip(demanded.path_angle, path_low, path_high)) + if path_angle * curvature <= 0.0: + path_angle = 0.0 + command = replace(demanded, curvature=curvature, path_angle=path_angle) + owner.curvature_last = command.curvature + owner.path_angle_last = command.path_angle + return command diff --git a/opendbc_repo/opendbc/car/ford/manual_turn.py b/opendbc_repo/opendbc/car/ford/manual_turn.py new file mode 100644 index 0000000000..3380c79212 --- /dev/null +++ b/opendbc_repo/opendbc/car/ford/manual_turn.py @@ -0,0 +1,101 @@ +import numpy as np + +from opendbc.car import DT_CTRL +from opendbc.car.ford.values import CarControllerParams + +STEER_DT = CarControllerParams.STEER_STEP * DT_CTRL +MANUAL_TURN_ENTRY_ANGLE_DEG = 12.0 +MANUAL_TURN_RELEASE_ANGLE_DEG = 12.0 +MANUAL_TURN_RECOVERY_SECONDS = 0.25 + + +class HumanTurnDetector: + ANGLE_DEG = 45.0 + HOLD_SECONDS = 1.5 + PRETURNED_HOLD_SECONDS = 3.0 + + def __init__(self): + self.timer = 0.0 + self.active = False + self._pressed_last = False + self._press_started_preturned = False + + def update(self, enabled: bool, steering_pressed: bool, steering_angle_deg: float) -> bool: + if steering_pressed and not self._pressed_last: + self._press_started_preturned = abs(steering_angle_deg) > self.ANGLE_DEG + self._pressed_last = steering_pressed + + if enabled and steering_pressed and abs(steering_angle_deg) > self.ANGLE_DEG: + self.timer += STEER_DT + else: + self.timer = 0.0 + + hold_time = self.PRETURNED_HOLD_SECONDS if self._press_started_preturned else self.HOLD_SECONDS + self.active = self.timer + 1e-9 >= hold_time + return self.active + + def reset(self): + self.timer = 0.0 + self.active = False + self._pressed_last = False + self._press_started_preturned = False + + +class ManualTurnLatch: + def __init__(self): + self.human_turn = HumanTurnDetector() + self.manual_turn_latched = False + self.manual_turn_recovery_timer = 0.0 + self.manual_turn_direction = 0.0 + self.human_turn_enabled = True + + def update(self, CC, CS, desired: float, enabled: bool, lane_change: bool, entry_allowed: bool = True) -> bool: + if not CC.latActive: + self.human_turn.reset() + self.manual_turn_latched = False + self.manual_turn_recovery_timer = 0.0 + self.manual_turn_direction = 0.0 + return False + self.human_turn_enabled = enabled + detected = self.human_turn.update( + self.human_turn_enabled, CS.out.steeringPressed, CS.out.steeringAngleDeg) + if not self.human_turn_enabled: + self.manual_turn_latched = False + self.manual_turn_recovery_timer = 0.0 + self.manual_turn_direction = 0.0 + return False + + blinker_direction = float(CS.out.rightBlinker) - float(CS.out.leftBlinker) + driver_turning_with_signal = ( + CS.out.steeringPressed and abs(CS.out.steeringAngleDeg) >= MANUAL_TURN_ENTRY_ANGLE_DEG and + blinker_direction != 0.0 and not lane_change and + CS.out.steeringTorque * blinker_direction < 0.0 + ) + if entry_allowed and (detected or driver_turning_with_signal): + self.manual_turn_latched = True + if blinker_direction != 0.0: + self.manual_turn_direction = blinker_direction + elif self.manual_turn_direction == 0.0: + self.manual_turn_direction = -float(np.sign(CS.out.steeringAngleDeg)) + + if not self.manual_turn_latched: + self.manual_turn_recovery_timer = 0.0 + self.manual_turn_direction = 0.0 + return False + + if (CS.out.steeringPressed or blinker_direction != 0.0 or + abs(CS.out.steeringAngleDeg) > MANUAL_TURN_RELEASE_ANGLE_DEG): + self.manual_turn_recovery_timer = 0.0 + else: + self.manual_turn_recovery_timer += STEER_DT + if self.manual_turn_recovery_timer + 1e-9 >= MANUAL_TURN_RECOVERY_SECONDS: + current = -CS.out.yawRate / max(CS.out.vEgoRaw, 0.1) + if (self.manual_turn_direction * desired > 0.0 and + self.manual_turn_direction * (desired - current) > CarControllerParams.CURVATURE_ERROR): + self.manual_turn_recovery_timer = MANUAL_TURN_RECOVERY_SECONDS + else: + self.manual_turn_latched = False + self.manual_turn_recovery_timer = 0.0 + self.manual_turn_direction = 0.0 + + return self.manual_turn_latched diff --git a/opendbc_repo/opendbc/car/ford/new_port_curvature.py b/opendbc_repo/opendbc/car/ford/new_port_curvature.py new file mode 100644 index 0000000000..a7d6f7c6b0 --- /dev/null +++ b/opendbc_repo/opendbc/car/ford/new_port_curvature.py @@ -0,0 +1,69 @@ +"""Reuse the current Ford curvature strategy for exact Edge/Mondeo callers. + +Only scalar curvature crosses the existing native boundary; no protocol extension. +The reused strategy retains its required provenance and notices in lateral_strategy.py. +""" +from dataclasses import replace +import math + +from opendbc.car import structs +from opendbc.car.ford.explorer_lateral import bounded_command as shared_bound +from opendbc.car.ford.lateral_strategy import FordLateralController, FordLateralResult +from opendbc.car.ford.values import CAR, FordFlags + +PROFILES = { + CAR.FORD_EDGE_MK2: (int(FordFlags.NEW_PORT | FordFlags.ALT_STEER_ANGLE), 8), + CAR.FORD_MONDEO_MK5: (int(FordFlags.NEW_PORT | FordFlags.CANFD), 10), +} + + +def qualified(cp): + profile = PROFILES.get(cp.carFingerprint) + if (profile is None or cp.brand != "ford" or cp.passive or cp.dashcamOnly or cp.notCar or + cp.alternativeExperience not in (0, 32) or not cp.pcmCruise or + cp.steerControlType != structs.CarParams.SteerControlType.angle or + len(cp.safetyConfigs) not in (1, 2) or (cp.alternativeExperience == 32 and len(cp.safetyConfigs) != 1)): + return False + flags, word = profile + if (int(cp.flags) & ~int(FordFlags.HAS_BSM)) != flags: + return False + if len(cp.safetyConfigs) == 2 and (cp.safetyConfigs[0].safetyModel != structs.CarParams.SafetyModel.noOutput or + cp.safetyConfigs[0].safetyParam != 0): + return False + safety = cp.safetyConfigs[-1] + return safety.safetyModel == structs.CarParams.SafetyModel.ford and safety.safetyParam == word + int(cp.openpilotLongitudinalControl) + + +class NewPortCurvatureController(FordLateralController): + def __init__(self, cp): + if not qualified(cp): + raise ValueError("Edge/Mondeo curvature requires its exact current native profile") + super().__init__(cp) + self.manual_turn_detected = False + + def _manual_turn(self, CC, CS, desired: float, driver_assisting: bool = False) -> bool: + self.manual_turn_detected = super()._manual_turn(CC, CS, desired, driver_assisting) + return self.manual_turn_detected + + def update(self, CC, CS, actuators): + out = CS.out + if (not CC.latActive or not out.canValid or out.canTimeout or out.steerFaultTemporary or + out.steerFaultPermanent or out.vehicleSensorsInvalid or + not all(math.isfinite(value) for value in (out.vEgoRaw, out.yawRate, out.steeringAngleDeg, actuators.curvature))): + self.human_turn.reset() + self.curvature_samples.clear() + self.curvature_last = self.path_angle_last = 0.0 + self.manual_turn_detected = False + return FordLateralResult() + return super().update(CC, CS, actuators) + + +def create_controller(cp): + return NewPortCurvatureController(cp) if qualified(cp) else None + + +def bounded_command(owner, demanded, previous, speed, measured): + cap = (3.0 - 9.81 * .06) / max(speed, 1.) ** 2 if owner.CP.flags & FordFlags.CANFD else None + command = shared_bound(owner, demanded, previous, speed, measured, absolute_cap=cap) + # These profiles keep their current curvature-only native/codec contract. + return replace(command, curvature_rate=0.0, path_angle=0.0, ramp_type=0, precision_type=1) diff --git a/opendbc_repo/opendbc/car/ford/radar_interface.py b/opendbc_repo/opendbc/car/ford/radar_interface.py index 32cbce4529..c87ea86d0c 100644 --- a/opendbc_repo/opendbc/car/ford/radar_interface.py +++ b/opendbc_repo/opendbc/car/ford/radar_interface.py @@ -1,6 +1,6 @@ import numpy as np from typing import cast -from collections import defaultdict +from collections import defaultdict, deque from math import cos, sin from dataclasses import dataclass from opendbc.can import CANParser @@ -8,6 +8,8 @@ from opendbc.car import Bus, structs from opendbc.car.common.conversions import Conversions as CV from opendbc.car.ford.fordcan import CanBus from opendbc.car.ford.values import DBC, RADAR +from opendbc.car.ford.generic_canfd_lateral import qualified as generic_canfd_qualified +from opendbc.car.ford.mache_lateral import qualified as mache_qualified from opendbc.car.interfaces import RadarInterfaceBase DELPHI_ESR_RADAR_MSGS = list(range(0x500, 0x540)) @@ -19,6 +21,7 @@ DELPHI_MRR_RADAR_MSG_COUNT = 64 DELPHI_MRR_RADAR_RANGE_COVERAGE = {0: 42, 1: 164, 2: 45, 3: 175} # scan index to detection range (m) DELPHI_MRR_MIN_LONG_RANGE_DIST = 30 # meters DELPHI_MRR_CLUSTER_THRESHOLD = 5 # meters, lateral distance and relative velocity are weighted +STEER_ASSIST_DATA_ADDR = 0x3D7 @dataclass @@ -89,12 +92,18 @@ def _create_delphi_mrr_radar_can_parser(CP) -> CANParser: return CANParser(RADAR.DELPHI_MRR, messages, CanBus(CP).radar) +def _create_steer_assist_radar_can_parser(CP) -> CANParser: + return CANParser(RADAR.STEER_ASSIST_DATA, [("Steer_Assist_Data", 20)], CanBus(CP).camera) + + class RadarInterface(RadarInterfaceBase): def __init__(self, CP): super().__init__(CP) self.points: list[list[float]] = [] self.clusters: list[Cluster] = [] + self.generic_canfd_lead = generic_canfd_qualified(CP) or mache_qualified(CP) + self.v_rel_history = deque(maxlen=20) self.updated_messages = set() self.radar = DBC[CP.carFingerprint].get(Bus.radar) @@ -110,6 +119,9 @@ class RadarInterface(RadarInterfaceBase): elif self.radar == RADAR.DELPHI_MRR: self.rcp = _create_delphi_mrr_radar_can_parser(CP) self.trigger_msg = DELPHI_MRR_RADAR_HEADER_ADDR + elif self.radar == RADAR.STEER_ASSIST_DATA: + self.rcp = _create_steer_assist_radar_can_parser(CP) + self.trigger_msg = STEER_ASSIST_DATA_ADDR else: raise ValueError(f"Unsupported radar: {self.radar}") @@ -134,10 +146,55 @@ class RadarInterface(RadarInterfaceBase): _update = self._update_delphi_mrr(ret) if not _update: return None + elif self.radar == RADAR.STEER_ASSIST_DATA: + self._update_steer_assist() ret.points = list(self.pts.values()) return ret + def _update_steer_assist(self): + if self.generic_canfd_lead: + self._update_generic_steer_assist() + return + msg = self.rcp.vl["Steer_Assist_Data"] + if not self.rcp.can_valid or msg["CmbbObjConfdnc_D_Stat"] <= 0 or msg["CmbbObjDistLong_L_Actl"] <= 0: + self.pts.pop(0, None) + return + if 0 not in self.pts: + self.pts[0] = structs.RadarData.RadarPoint() + self.pts[0].trackId = self.track_id + self.track_id += 1 + self.pts[0].dRel = msg["CmbbObjDistLong_L_Actl"] + self.pts[0].yRel = 0. + self.pts[0].vRel = msg["CmbbObjRelLong_V_Actl"] + + def _update_generic_steer_assist(self): + # Preserve source-owned camera leads with current health and distance gates. + msg = self.rcp.vl["Steer_Assist_Data"] + if not self.rcp.can_valid or msg["CmbbObjConfdnc_D_Stat"] <= 0 or msg["CmbbObjDistLong_L_Actl"] <= 0: + self.pts.pop(0, None) + self.v_rel_history.clear() + return + distance = msg["CmbbObjDistLong_L_Actl"] + velocity = msg["CmbbObjRelLong_V_Actl"] + new_track = 0 not in self.pts + if new_track: + self.pts[0] = structs.RadarData.RadarPoint() + self.pts[0].trackId = self.track_id + self.track_id += 1 + elif abs(velocity) < 1e-2: + self.v_rel_history.append(distance - self.pts[0].dRel) + velocity = sum(self.v_rel_history) + else: + self.v_rel_history.clear() + if not new_track and (abs(self.pts[0].vRel - velocity) > 2.0 or abs(self.pts[0].dRel - distance) > 5.0): + self.pts[0].trackId = self.track_id + self.track_id += 1 + self.v_rel_history.clear() + self.pts[0].dRel = distance + self.pts[0].yRel = msg["CmbbObjDistLat_L_Actl"] + self.pts[0].vRel = velocity + def _update_delphi_esr(self): for ii in sorted(self.updated_messages): cpt = self.rcp.vl[ii] diff --git a/opendbc_repo/opendbc/car/ford/stock_cruise.py b/opendbc_repo/opendbc/car/ford/stock_cruise.py new file mode 100644 index 0000000000..f2456eff7b --- /dev/null +++ b/opendbc_repo/opendbc/car/ford/stock_cruise.py @@ -0,0 +1,57 @@ +"""Ford physical cancel/resume switch context; no new cruise authority.""" + +from opendbc.car import structs +from opendbc.car.ford.values import CAR, FordFlags, FordSafetyFlags +from opendbc.car.ford.classic_lateral import CLASSIC_EXTENDED_CARS +from opendbc.car.ford.generic_canfd_lateral import qualified as generic_canfd_qualified + + +class FordStockCruiseButton: + """Resolve Ford's context-sensitive cancel/resume switch for stock ACC.""" + + def __init__(self): + self.pressed = False + self.cancel = False + self.resume = False + + def update(self, pressed: bool, cruise_available: bool, cruise_enabled: bool) -> tuple[bool, bool]: + if pressed and not self.pressed: + self.cancel = cruise_available and cruise_enabled + self.resume = cruise_available and not cruise_enabled + elif not pressed: + self.cancel = False + self.resume = False + + self.pressed = pressed + return self.cancel, self.resume + + +def qualified(CP) -> bool: + from opendbc.bluepilot_lateral.hosts.starpilot import qualified as angle_qualified + if angle_qualified(CP): + return not CP.openpilotLongitudinalControl + if CP.alternativeExperience == 32 and len(CP.safetyConfigs) != 1: + return False + """Existing stock profiles with the paired physical-driver button contract.""" + if (CP.brand != "ford" or CP.carFingerprint not in tuple(CAR) or CP.openpilotLongitudinalControl or CP.alternativeExperience not in (0, 32) or + CP.passive or CP.dashcamOnly or CP.notCar or len(CP.safetyConfigs) not in (1, 2) or + CP.flags & ~int(FordFlags.CANFD | FordFlags.HAS_BSM | FordFlags.ALT_STEER_ANGLE | FordFlags.NEW_PORT | FordFlags.LKA_STEERING)): + return False + if len(CP.safetyConfigs) == 2 and (CP.safetyConfigs[0].safetyModel != structs.CarParams.SafetyModel.noOutput or + CP.safetyConfigs[0].safetyParam != 0): + return False + safety = CP.safetyConfigs[-1] + if safety.safetyModel != structs.CarParams.SafetyModel.ford or safety.safetyParam not in (2, 8, 10, 12, 18, 32, 66): + return False + if safety.safetyModel == structs.CarParams.SafetyModel.ford and safety.safetyParam == 32: + return CP.carFingerprint in CLASSIC_EXTENDED_CARS and not CP.flags & ~int(FordFlags.HAS_BSM) + if safety.safetyParam == 66: + return generic_canfd_qualified(CP) + expected = (int(FordSafetyFlags.CANFD) if CP.flags & FordFlags.CANFD else 0) + expected |= int(FordSafetyFlags.NEW_PORT) if CP.flags & FordFlags.NEW_PORT else 0 + expected |= int(FordSafetyFlags.LKA_STEERING) if CP.flags & FordFlags.LKA_STEERING else 0 + if safety.safetyParam == 18: + if CP.carFingerprint != CAR.FORD_MUSTANG_MACH_E_MK1 or expected != int(FordSafetyFlags.CANFD): + return False + expected |= int(FordSafetyFlags.MACH_E_EXTENDED) + return safety.safetyParam == expected diff --git a/opendbc_repo/opendbc/car/ford/tests/test_added_firmware_identity.py b/opendbc_repo/opendbc/car/ford/tests/test_added_firmware_identity.py new file mode 100644 index 0000000000..0e89992b52 --- /dev/null +++ b/opendbc_repo/opendbc/car/ford/tests/test_added_firmware_identity.py @@ -0,0 +1,148 @@ +import unittest + +from opendbc.car import structs +from opendbc.car.ford.values import CAR +from opendbc.car.fw_versions import match_fw_to_car + +Ecu = structs.CarParams.Ecu + +SOURCE_BASELINES = { + CAR.FORD_BRONCO_SPORT_MK1: { + (Ecu.eps, 1840, None): b'LX6C-14D003-AH\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', + (Ecu.abs, 1888, None): b'LX6C-2D053-KF\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', + (Ecu.fwdRadar, 1892, None): b'LB5T-14D049-AB\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', + (Ecu.fwdCamera, 1798, None): b'M1PT-14F397-AC\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', + }, + CAR.FORD_ESCAPE_MK4_5: { + (Ecu.eps, 1840, None): b'PZ11-14D003-AB\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', + (Ecu.abs, 1888, None): b'PZ1C-2D053-EJ\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', + (Ecu.fwdRadar, 1892, None): b'ML3T-14D049-AL\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', + (Ecu.fwdCamera, 1798, None): b'PJ6T-14H102-ABE\x00\x00\x00\x00\x00\x00\x00\x00\x00', + }, + CAR.FORD_EXPEDITION_MK4: { + (Ecu.eps, 1840, None): b'NL14-14D003-AE\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', + (Ecu.abs, 1888, None): b'RL14-2D053-AA\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', + (Ecu.fwdRadar, 1892, None): b'ML3T-14D049-AL\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', + (Ecu.fwdCamera, 1798, None): b'ML3T-14H102-ABT\x00\x00\x00\x00\x00\x00\x00\x00\x00', + }, + CAR.FORD_EXPLORER_MK6: { + (Ecu.eps, 1840, None): b'R1MC-14D003-AE\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', + (Ecu.abs, 1888, None): b'L1MC-2D053-AJ\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', + (Ecu.fwdRadar, 1892, None): b'LB5T-14D049-AB\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', + (Ecu.fwdCamera, 1798, None): b'LB5T-14F397-AD\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', + }, + CAR.FORD_FOCUS_MK4: { + (Ecu.eps, 1840, None): b'JX6C-14D003-AH\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', + (Ecu.abs, 1888, None): b'JX61-2D053-CJ\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', + (Ecu.fwdRadar, 1892, None): b'JX7T-14D049-AC\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', + (Ecu.fwdCamera, 1798, None): b'JX7T-14F397-AH\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', + }, + CAR.FORD_F_150_LIGHTNING_MK1: { + (Ecu.abs, 1888, None): b'NL38-2D053-AF\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', + (Ecu.fwdCamera, 1798, None): b'ML3T-14H102-ABT\x00\x00\x00\x00\x00\x00\x00\x00\x00', + (Ecu.fwdRadar, 1892, None): b'ML3T-14D049-AH\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', + (Ecu.eps, 1840, None): b'NL38-14D003-AA\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', + }, + CAR.FORD_F_150_MK14: { + (Ecu.eps, 1840, None): b'MB3C-14D003-AA\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', + (Ecu.abs, 1888, None): b'ML34-2D053-AJ\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', + (Ecu.fwdRadar, 1892, None): b'ML3T-14D049-AH\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', + (Ecu.fwdCamera, 1798, None): b'ML3T-14H102-ABR\x00\x00\x00\x00\x00\x00\x00\x00\x00', + }, + CAR.FORD_MUSTANG_MACH_E_MK1: { + (Ecu.eps, 1840, None): b'LJ9C-14D003-AM\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', + (Ecu.abs, 1888, None): b'LK9C-2D053-CK\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', + (Ecu.fwdRadar, 1892, None): b'ML3T-14D049-AH\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', + (Ecu.fwdCamera, 1798, None): b'ML3T-14H102-ABS\x00\x00\x00\x00\x00\x00\x00\x00\x00', + }, + CAR.FORD_RANGER_MK2: { + (Ecu.eps, 1840, None): b'JR3C-14D003-AA\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', + (Ecu.abs, 1888, None): b'MB3C-2D053-AE\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', + (Ecu.fwdRadar, 1892, None): b'JX7T-14D049-AD\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', + (Ecu.fwdCamera, 1798, None): b'PJ6T-14H102-ABJ\x00\x00\x00\x00\x00\x00\x00\x00\x00', + }, + CAR.FORD_TRANSIT_MK5: { + (Ecu.eps, 1840, None): b'KK21-14D003-AM\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', + (Ecu.abs, 1888, None): b'NK41-2D053-DF\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', + (Ecu.fwdRadar, 1892, None): b'PC4T-14D049-AA\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', + (Ecu.fwdCamera, 1798, None): b'NK3T-14F397-AB\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', + }, +} + +ADDED_VERSIONS = ( + (CAR.FORD_BRONCO_SPORT_MK1, (Ecu.abs, 1888, None), b'LX6C-2D053-KF\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'), + (CAR.FORD_BRONCO_SPORT_MK1, (Ecu.abs, 1888, None), b'LX6C-2D053-KG\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'), + (CAR.FORD_ESCAPE_MK4_5, (Ecu.eps, 1840, None), b'PZ11-14D003-AB\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'), + (CAR.FORD_ESCAPE_MK4_5, (Ecu.eps, 1840, None), b'PZ11-14D003-FA\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'), + (CAR.FORD_ESCAPE_MK4_5, (Ecu.fwdCamera, 1798, None), b'PJ6T-14H102-ABE\x00\x00\x00\x00\x00\x00\x00\x00\x00'), + (CAR.FORD_ESCAPE_MK4_5, (Ecu.fwdCamera, 1798, None), b'PJ6T-14H102-MDC\x00\x00\x00\x00\x00\x00\x00\x00\x00'), + (CAR.FORD_ESCAPE_MK4_5, (Ecu.fwdCamera, 1798, None), b'PJ6T-14H102-MDF\x00\x00\x00\x00\x00\x00\x00\x00\x00'), + (CAR.FORD_ESCAPE_MK4_5, (Ecu.fwdCamera, 1798, None), b'PJ6T-14H102-SCD\x00\x00\x00\x00\x00\x00\x00\x00\x00'), + (CAR.FORD_ESCAPE_MK4_5, (Ecu.fwdCamera, 1798, None), b'PJ6T-14H102-SCG\x00\x00\x00\x00\x00\x00\x00\x00\x00'), + (CAR.FORD_EXPLORER_MK6, (Ecu.eps, 1840, None), b'R1MC-14D003-AE\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'), + (CAR.FORD_EXPLORER_MK6, (Ecu.eps, 1840, None), b'R1MC-14D003-AF\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'), + (CAR.FORD_EXPLORER_MK6, (Ecu.eps, 1840, None), b'R1MC-14D003-AG\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'), + (CAR.FORD_EXPLORER_MK6, (Ecu.eps, 1840, None), b'R1MC-14D003-AH\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'), + (CAR.FORD_EXPEDITION_MK4, (Ecu.abs, 1888, None), b'PL14-2D053-AB\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'), + (CAR.FORD_F_150_MK14, (Ecu.eps, 1840, None), b'MB3C-14D003-AA\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'), + (CAR.FORD_F_150_LIGHTNING_MK1, (Ecu.abs, 1888, None), b'NL38-2D053-AF\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'), + (CAR.FORD_F_150_LIGHTNING_MK1, (Ecu.abs, 1888, None), b'RL38-2D053-BC\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'), + (CAR.FORD_F_150_LIGHTNING_MK1, (Ecu.abs, 1888, None), b'TL38-2D053-AD\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'), + (CAR.FORD_F_150_LIGHTNING_MK1, (Ecu.fwdRadar, 1892, None), b'ML3T-14D049-AH\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'), + (CAR.FORD_F_150_LIGHTNING_MK1, (Ecu.fwdRadar, 1892, None), b'RB5T-14D049-AB\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'), + (CAR.FORD_F_150_LIGHTNING_MK1, (Ecu.eps, 1840, None), b'NL38-14D003-AA\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'), + (CAR.FORD_F_150_LIGHTNING_MK1, (Ecu.eps, 1840, None), b'NL38-14D003-AC\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'), + (CAR.FORD_MUSTANG_MACH_E_MK1, (Ecu.fwdRadar, 1892, None), b'ML3T-14D049-AH\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'), + (CAR.FORD_MUSTANG_MACH_E_MK1, (Ecu.fwdRadar, 1892, None), b'ML3T-14D049-AK\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'), + (CAR.FORD_FOCUS_MK4, (Ecu.eps, 1840, None), b'JX6C-14D003-AL\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'), + (CAR.FORD_FOCUS_MK4, (Ecu.eps, 1840, None), b'JX6C-14D003-BB\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'), + (CAR.FORD_FOCUS_MK4, (Ecu.abs, 1888, None), b'NX61-2D053-MD\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'), + (CAR.FORD_RANGER_MK2, (Ecu.eps, 1840, None), b'JR3C-14D003-AA\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'), + (CAR.FORD_RANGER_MK2, (Ecu.eps, 1840, None), b'NL14-14D003-AC\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'), + (CAR.FORD_RANGER_MK2, (Ecu.abs, 1888, None), b'MB3C-2D053-AE\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'), + (CAR.FORD_RANGER_MK2, (Ecu.abs, 1888, None), b'MB3C-2D053-ZJ\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'), + (CAR.FORD_RANGER_MK2, (Ecu.abs, 1888, None), b'PB3C-2D053-ZB\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'), + (CAR.FORD_RANGER_MK2, (Ecu.abs, 1888, None), b'PB3C-2D053-ZC\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'), + (CAR.FORD_RANGER_MK2, (Ecu.abs, 1888, None), b'PB9C-2D053-ZG\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'), + (CAR.FORD_RANGER_MK2, (Ecu.fwdRadar, 1892, None), b'JX7T-14D049-AD\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'), + (CAR.FORD_TRANSIT_MK5, (Ecu.fwdCamera, 1798, None), b'NK3T-14F397-AB\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'), +) + + +class TestAddedFordFirmwareIdentity(unittest.TestCase): + def test_original_literal_versions_match_joint_production_inventory(self): + for candidate, ecu_key, version in ADDED_VERSIONS: + cohort = dict(SOURCE_BASELINES[candidate]) + cohort[ecu_key] = version + firmware = [ + structs.CarParams.CarFw(ecu=ecu, address=address, subAddress=0 if sub is None else sub, fwVersion=value, brand="ford") + for (ecu, address, sub), value in cohort.items() + ] + for allow_exact in (True, False): + with self.subTest(candidate=candidate, ecu=ecu_key, version=version, allow_exact=allow_exact): + self.assertEqual(match_fw_to_car(firmware, "", allow_exact=allow_exact, log=False)[1], {candidate}) + + def test_missing_required_ecu_never_falls_back_to_vin(self): + for candidate, cohort in SOURCE_BASELINES.items(): + for omitted in cohort: + firmware = [ + structs.CarParams.CarFw(ecu=ecu, address=address, subAddress=0 if sub is None else sub, fwVersion=value, brand="ford") + for (ecu, address, sub), value in cohort.items() + if (ecu, address, sub) != omitted + ] + for allow_exact in (True, False): + with self.subTest(candidate=candidate, omitted=omitted, allow_exact=allow_exact): + self.assertEqual(match_fw_to_car(firmware, "WF0XXXXXX00000000", allow_exact=allow_exact, log=False)[1], set()) + + def test_unknown_required_firmware_pair_is_rejected(self): + for candidate, cohort in SOURCE_BASELINES.items(): + for changed in cohort: + firmware = [ + structs.CarParams.CarFw( + ecu=ecu, address=address, subAddress=0 if sub is None else sub, fwVersion=b"UNRECOGNIZED" if (ecu, address, sub) == changed else value, brand="ford" + ) + for (ecu, address, sub), value in cohort.items() + ] + for allow_exact in (True, False): + with self.subTest(candidate=candidate, changed=changed, allow_exact=allow_exact): + self.assertEqual(match_fw_to_car(firmware, "", allow_exact=allow_exact, log=False)[1], set()) diff --git a/opendbc_repo/opendbc/car/ford/tests/test_creep_compensation.py b/opendbc_repo/opendbc/car/ford/tests/test_creep_compensation.py new file mode 100644 index 0000000000..3fb3a1764e --- /dev/null +++ b/opendbc_repo/opendbc/car/ford/tests/test_creep_compensation.py @@ -0,0 +1,72 @@ +import unittest + +from opendbc.can import CANParser +from opendbc.car import Bus, gen_empty_fingerprint, structs +from opendbc.car.ford.carcontroller import CarController, apply_creep_compensation +from opendbc.car.ford.carstate import CarState +from opendbc.car.ford.interface import CarInterface +from opendbc.car.ford.values import CAR, DBC + + +class TestCreepCompensation(unittest.TestCase): + def test_mach_e_only_compensates_while_holding_a_stop(self): + for standstill, stopping in ((False, False), (True, False), (False, True)): + for accel in (-1., -.1, 0., .1, .2, 1.): + for speed in (0., .5, 1., 2., 3., 10.): + self.assertEqual(apply_creep_compensation(accel, speed, CAR.FORD_MUSTANG_MACH_E_MK1, + standstill=standstill, stopping=stopping), accel) + for candidate in CAR: + for standstill, stopping in ((False, False), (True, False), (False, True), (True, True)): + if candidate == CAR.FORD_MUSTANG_MACH_E_MK1 and not (standstill and stopping): + continue + self.assertAlmostEqual(apply_creep_compensation(0., .5, candidate, + standstill=standstill, stopping=stopping), -.6) + self.assertAlmostEqual(apply_creep_compensation(.1, 2., candidate, + standstill=standstill, stopping=stopping), -.05) + self.assertAlmostEqual(apply_creep_compensation(.2, 3., candidate, + standstill=standstill, stopping=stopping), .2) + + def test_controller_brake_hold_release_and_inactive_commands(self): + for candidate in (CAR.FORD_MUSTANG_MACH_E_MK1, CAR.FORD_F_150_MK14): + fingerprint = gen_empty_fingerprint() + fingerprint[0][0x5A] = 8 + fingerprint[2].update({0x3D6: 8, 0x186: 8}) + cp = CarInterface.get_params(candidate, fingerprint, [], True, False, False) + self.assertTrue(cp.openpilotLongitudinalControl) + state = CarState(cp) + state.update(state.get_can_parsers(cp)) + controller = CarController(DBC[candidate], cp) + controller.accel = -.6 + parser = CANParser(DBC[candidate][Bus.pt], [('ACCDATA', 50)], controller.CAN.main) + command = structs.CarControl() + command.longActive = True + output = structs.CarState() + for index, (standstill, stopping, active, target, expected, brake_request) in enumerate(( + (True, True, True, 0., -.6, True), + (False, False, True, 0., 0. if candidate == CAR.FORD_MUSTANG_MACH_E_MK1 else -.6, True), + (True, False, True, 0., 0. if candidate == CAR.FORD_MUSTANG_MACH_E_MK1 else -.6, True), + (False, False, True, .4, .4, False), + (True, True, False, 0., 0., False), + )): + controller.frame = 2 * index + command.longActive = active + command.actuators.accel = target + command.actuators.longControlState = 'stopping' if stopping else 'pid' + output.standstill = standstill + output.vEgo = output.vEgoRaw = 0. if standstill else .5 + state.out = output.as_reader() + applied, messages = controller.update(command.as_reader(), state, (index + 1) * 20_000_000) + acc = [message for message in messages if message[0] == 0x186] + self.assertEqual(len(acc), 1) + self.assertEqual(acc[0][2], controller.CAN.main) + parser.update([((index + 1) * 20_000_000, acc)]) + decoded = parser.vl['ACCDATA'] + self.assertAlmostEqual(decoded['AccBrkTot_A_Rq'], expected, delta=.0039) + self.assertAlmostEqual(applied.accel, expected, places=5) + self.assertEqual(decoded['Cmbb_B_Enbl'], int(active)) + self.assertEqual(decoded['AccStopStat_B_Rq'], int(stopping)) + self.assertEqual(decoded['AccBrkDecel_B_Rq'], int(brake_request)) + + +if __name__ == '__main__': + unittest.main() diff --git a/opendbc_repo/opendbc/car/ford/tests/test_curvature_preview.py b/opendbc_repo/opendbc/car/ford/tests/test_curvature_preview.py new file mode 100644 index 0000000000..2c72081d94 --- /dev/null +++ b/opendbc_repo/opendbc/car/ford/tests/test_curvature_preview.py @@ -0,0 +1,69 @@ +import unittest +from types import SimpleNamespace + +from opendbc.can import CANParser +from opendbc.car import Bus, structs +from opendbc.car.ford.curvature_preview import blend_curvature +from opendbc.car.ford.carcontroller import CarController +from opendbc.car.ford.carstate import CarState +from opendbc.car.ford.tests.test_three_ports import params +from opendbc.car.ford.values import CAR, DBC + + +class TestCurvaturePreview(unittest.TestCase): + def test_original_default_signed_preview_and_conservative_overshoot(self): + for sign in (-1, 1): + self.assertAlmostEqual(blend_curvature(sign * .001, sign * .002, 0.), sign * .0014) + self.assertAlmostEqual(blend_curvature(sign * .001, sign * .002, sign * .003), sign * .0012) + self.assertEqual(blend_curvature(sign * .001, -sign * .002, 0.), sign * .001) + self.assertEqual(blend_curvature(0., sign * .002, 0.), 0.) + for bad in (float('nan'), float('inf'), -float('inf')): + self.assertEqual(blend_curvature(.001, bad, 0.), .001) + + def test_actual_controller_blends_before_unchanged_envelope_and_yields(self): + cp = params(CAR.FORD_MUSTANG_MACH_E_MK1) + cp.safetyConfigs[0].safetyParam = 3 if cp.openpilotLongitudinalControl else 2 + controller = CarController(DBC[cp.carFingerprint], cp) + state = CarState(cp) + state.update(state.get_can_parsers(cp)) + out = structs.CarState() + out.vEgoRaw = 20. + state.out = out.as_reader() + command = structs.CarControl() + command.latActive = True + command.actuators.curvature = .001 + preview = SimpleNamespace(update=lambda: (True, False, True), preview_curvature=lambda speed: .002) + controller.manual_turn_inputs = preview + controller.apply_curvature_last = .0014 + from opendbc.car.ford.values import CarControllerParams + expected = CarControllerParams.CURVATURE_LIMITS.apply_limits(.0014, .0014, 20., 0., True, CarControllerParams.STEER_STEP) + actual, frames = controller.update(command.as_reader(), state, 0) + self.assertAlmostEqual(actual.curvature, expected) + parser = CANParser(DBC[cp.carFingerprint][Bus.pt], [('LateralMotionControl2', 20)], controller.CAN.main) + parser.update([(50_000_000, frames)]) + self.assertAlmostEqual(parser.vl['LateralMotionControl2']['LatCtlCurv_No_Actl'], -.0014, places=5) + self.assertEqual(parser.vl['LateralMotionControl2']['LatCtl_D2_Rq'], 1) + controller.frame = 5 + out.steeringPressed = True + out.steeringAngleDeg = -12. + out.steeringTorque = -1. + out.rightBlinker = True + state.out = out.as_reader() + actual, _ = controller.update(command.as_reader(), state, 50_000_000) + self.assertEqual(actual.curvature, 0.) + + def test_neighbor_controller_does_not_query_preview(self): + cp = params(CAR.FORD_F_150_MK14) + controller = CarController(DBC[cp.carFingerprint], cp) + state = CarState(cp) + state.update(state.get_can_parsers(cp)) + state.out = structs.CarState(vEgoRaw=20.).as_reader() + command = structs.CarControl(latActive=True) + command.actuators.curvature = .001 + + def unexpected(speed): + raise AssertionError('neighbor queried Mach-E preview') + controller.manual_turn_inputs = SimpleNamespace(update=lambda: None, apply_blend_settings=lambda owner: None, + lateral_snapshot=lambda speed: None, enabled=True, + preview_curvature=unexpected) + controller.update(command.as_reader(), state, 0) diff --git a/opendbc_repo/opendbc/car/ford/tests/test_flag_source_identity.py b/opendbc_repo/opendbc/car/ford/tests/test_flag_source_identity.py new file mode 100644 index 0000000000..526e4f76ab --- /dev/null +++ b/opendbc_repo/opendbc/car/ford/tests/test_flag_source_identity.py @@ -0,0 +1,54 @@ +"""Ford detected BSM must not change the physical steering decoder.""" +from opendbc.car import Bus, gen_empty_fingerprint +from opendbc.car.ford.values import CAR, FordFlags +from opendbc.car.ford.interface import CarInterface +from opendbc.car.ford.carstate import CarState + + +def params(candidate, bsm): + fingerprint = gen_empty_fingerprint() + fingerprint[0][0x5A] = 8 + fingerprint[2][0x3D6] = 8 + fingerprint[2][0x186] = 8 + if bsm: + fingerprint[0][0x3A6] = fingerprint[0][0x3A7] = 8 + return CarInterface.get_params(candidate, fingerprint, [], False, False, False) + + +def test_edge_alternate_decoder_does_not_create_bsm_subscriptions(): + cp = params(CAR.FORD_EDGE_MK2, False) + assert cp.flags & FordFlags.ALT_STEER_ANGLE + assert not cp.flags & FordFlags.HAS_BSM + state = CarState(cp) + parsers = state.get_can_parsers(cp) + result = state.update(parsers) # actual lazy decoder discovery, no fake health + names = {message.name for message in parsers[Bus.pt].message_states.values()} + assert {'ParkAid_Data', 'SteeringPinion_Data_Alt', 'TransGearData'} <= names + assert 'Side_Detect_L_Stat' not in names and 'Side_Detect_R_Stat' not in names + assert not result.leftBlindspot and not result.rightBlindspot + + +def test_detected_bsm_does_not_select_alternate_steering_on_mach_e(): + cp = params(CAR.FORD_MUSTANG_MACH_E_MK1, True) + assert cp.flags & FordFlags.HAS_BSM + assert not cp.flags & FordFlags.ALT_STEER_ANGLE + state = CarState(cp) + parsers = state.get_can_parsers(cp) + state.update(parsers) + pt = {message.name for message in parsers[Bus.pt].message_states.values()} + camera = {message.name for message in parsers[Bus.cam].message_states.values()} + assert 'SteeringPinion_Data' in pt + assert 'ParkAid_Data' not in pt and 'SteeringPinion_Data_Alt' not in pt + assert {'Side_Detect_L_Stat', 'Side_Detect_R_Stat'} <= camera + + +def test_edge_bsm_and_alternate_decoder_coexist_with_separate_bits(): + cp = params(CAR.FORD_EDGE_MK2, True) + assert FordFlags.HAS_BSM & FordFlags.ALT_STEER_ANGLE == 0 + assert cp.flags & FordFlags.HAS_BSM and cp.flags & FordFlags.ALT_STEER_ANGLE + state = CarState(cp) + parsers = state.get_can_parsers(cp) + state.update(parsers) + names = {message.name for message in parsers[Bus.pt].message_states.values()} + assert {'ParkAid_Data', 'SteeringPinion_Data_Alt', 'TransGearData', + 'Side_Detect_L_Stat', 'Side_Detect_R_Stat'} <= names diff --git a/opendbc_repo/opendbc/car/ford/tests/test_ford.py b/opendbc_repo/opendbc/car/ford/tests/test_ford.py index e4051592f1..4ad1a65a96 100644 --- a/opendbc_repo/opendbc/car/ford/tests/test_ford.py +++ b/opendbc_repo/opendbc/car/ford/tests/test_ford.py @@ -53,7 +53,8 @@ class TestFordFW(unittest.TestCase): assert subaddr is None, "Unexpected ECU subaddress" for fw in fws: - assert len(fw) == 24, "Expected ECU response to be 24 bytes" + expected_lengths = (23, 24) if car_model == CAR.FORD_TRANSIT_MK5 and ecu == Ecu.fwdCamera else (24,) + assert len(fw) in expected_lengths, "Unexpected ECU response length" match = FW_PATTERN.match(fw) assert match is not None, f"Unable to parse FW: {fw!r}" diff --git a/opendbc_repo/opendbc/car/ford/tests/test_mach_e_profile.py b/opendbc_repo/opendbc/car/ford/tests/test_mach_e_profile.py new file mode 100644 index 0000000000..88f9be2a23 --- /dev/null +++ b/opendbc_repo/opendbc/car/ford/tests/test_mach_e_profile.py @@ -0,0 +1,52 @@ +import unittest + +from opendbc.car import gen_empty_fingerprint, structs +from opendbc.car.ford.interface import CarInterface +from opendbc.car.ford.values import CAR, FordSafetyFlags + + +def fingerprint(offset=0, secoc=False): + fp = gen_empty_fingerprint() + fp[offset][0x5A] = 8 + fp[offset + 2][0x3D6] = 16 if secoc else 8 + fp[offset + 2][0x186] = 16 if secoc else 8 + return fp + + +class TestMachEProfile(unittest.TestCase): + def test_actual_params_stock_debug_long_and_release_stock(self): + for alpha, release, word in ((False, False, 18), (True, False, 19), (False, True, 18), (True, True, 18)): + with self.subTest(alpha=alpha, release=release): + cp = CarInterface.get_params(CAR.FORD_MUSTANG_MACH_E_MK1, fingerprint(), [], alpha, release, False) + self.assertEqual(cp.safetyConfigs[-1].safetyParam, word) + self.assertEqual(cp.openpilotLongitudinalControl, word == 19) + self.assertEqual(cp.alternativeExperience, 0) + if release: + self.assertFalse(cp.alphaLongitudinalAvailable) + + def test_secoc_unrelated_flags_and_ae_do_not_select_extension(self): + cp = CarInterface.get_params(CAR.FORD_MUSTANG_MACH_E_MK1, fingerprint(secoc=True), [], False, False, False) + self.assertTrue(cp.dashcamOnly) + self.assertFalse(cp.safetyConfigs[-1].safetyParam & FordSafetyFlags.MACH_E_EXTENDED) + for added_flag, ae in ((4, 0), (8, 0), (16, 0), (0, 32)): + with self.subTest(added_flag=added_flag, ae=ae): + cp = CarInterface.get_params(CAR.FORD_MUSTANG_MACH_E_MK1, fingerprint(), [], False, False, False) + cp.flags |= added_flag + cp.alternativeExperience = ae + cp = CarInterface._get_params(cp, CAR.FORD_MUSTANG_MACH_E_MK1, fingerprint(), [], False, False, False) + self.assertFalse(cp.safetyConfigs[-1].safetyParam & FordSafetyFlags.MACH_E_EXTENDED) + + def test_sibling_canfd_uses_separate_generic_profile(self): + for candidate in (CAR.FORD_F_150_MK14, CAR.FORD_ESCAPE_MK4_5, CAR.FORD_F_150_LIGHTNING_MK1): + for alpha, word in ((False, 66), (True, 67)): + with self.subTest(candidate=candidate, alpha=alpha): + cp = CarInterface.get_params(candidate, fingerprint(), [], alpha, False, False) + self.assertEqual(cp.safetyConfigs[-1].safetyParam, word) + self.assertFalse(cp.safetyConfigs[-1].safetyParam & FordSafetyFlags.MACH_E_EXTENDED) + + def test_bus_offset_keeps_no_output_first(self): + cp = CarInterface.get_params(CAR.FORD_MUSTANG_MACH_E_MK1, fingerprint(offset=4), [], False, False, False) + self.assertEqual(len(cp.safetyConfigs), 2) + self.assertEqual(cp.safetyConfigs[0].safetyModel, structs.CarParams.SafetyModel.noOutput) + self.assertEqual(cp.safetyConfigs[0].safetyParam, 0) + self.assertEqual(cp.safetyConfigs[1].safetyParam, 18) diff --git a/opendbc_repo/opendbc/car/ford/tests/test_manual_turn.py b/opendbc_repo/opendbc/car/ford/tests/test_manual_turn.py new file mode 100644 index 0000000000..5ddc95aaf6 --- /dev/null +++ b/opendbc_repo/opendbc/car/ford/tests/test_manual_turn.py @@ -0,0 +1,144 @@ +import unittest +from types import SimpleNamespace + +from opendbc.can import CANParser +from opendbc.car import Bus, structs +from opendbc.car.ford import fordcan +from opendbc.car.ford.carcontroller import CarController +from opendbc.car.ford.carstate import CarState +from opendbc.car.ford.manual_turn import HumanTurnDetector, ManualTurnLatch +from opendbc.car.ford.tests.test_three_ports import params as _params +from opendbc.car.ford.values import CAR, DBC + + +def turn_state(direction=1): + return SimpleNamespace(out=SimpleNamespace(steeringPressed=True, steeringAngleDeg=-direction * 12., + steeringTorque=-direction, rightBlinker=direction == 1, + leftBlinker=direction == -1, yawRate=0., vEgoRaw=20.)) + + +def params(candidate): + cp = _params(candidate) + if candidate == CAR.FORD_MUSTANG_MACH_E_MK1: + cp.safetyConfigs[0].safetyParam = 3 if cp.openpilotLongitudinalControl else 2 + return cp + + +class TestManualTurn(unittest.TestCase): + def test_detector_preturned_and_new_turn_hold(self): + for preturned, frames in ((True, 60), (False, 30)): + detector = HumanTurnDetector() + if not preturned: + self.assertFalse(detector.update(True, True, 0.)) + for _ in range(frames - 1): + self.assertFalse(detector.update(True, True, 46.)) + self.assertTrue(detector.update(True, True, 46.)) + self.assertFalse(detector.update(True, False, 46.)) + self.assertFalse(detector.update(False, True, 46.)) + + def test_signed_directional_recovery_and_resets(self): + command = SimpleNamespace(latActive=True) + for direction in (-1, 1): + for desired, current, release in ((.006, .003, False), (.005, .003, True), (0., .003, True), (-.006, .003, True)): + with self.subTest(direction=direction, desired=desired): + latch = ManualTurnLatch() + state = turn_state(direction) + self.assertTrue(latch.update(command, state, direction * desired, True, False)) + state.out.steeringPressed = False + state.out.steeringAngleDeg = 0. + state.out.rightBlinker = state.out.leftBlinker = False + state.out.yawRate = -direction * current * 20. + for _ in range(4): + self.assertTrue(latch.update(command, state, direction * desired, True, False)) + self.assertEqual(latch.update(command, state, direction * desired, True, False), not release) + self.assertFalse(latch.update(command, state, direction * desired, False, False)) + self.assertEqual(latch.manual_turn_direction, 0.) + state = turn_state(direction) + self.assertFalse(latch.update(command, state, .006, True, True)) + self.assertTrue(latch.update(command, state, .006, True, False)) + command.latActive = False + self.assertFalse(latch.update(command, state, .006, True, False)) + command.latActive = True + + def test_no_signal_direction_and_recovery_interruptions(self): + latch = ManualTurnLatch() + command = SimpleNamespace(latActive=True) + state = turn_state(-1) + state.out.leftBlinker = False + state.out.steeringAngleDeg = 46. + for _ in range(60): + latched = latch.update(command, state, -.006, True, False) + self.assertTrue(latched) + self.assertEqual(latch.manual_turn_direction, -1.) + for attribute, value in (('steeringPressed', True), ('rightBlinker', True), ('steeringAngleDeg', 13.)): + state.out.steeringPressed = False + state.out.rightBlinker = False + state.out.steeringAngleDeg = 0. + latch.update(command, state, -.006, True, False) + setattr(state.out, attribute, value) + self.assertTrue(latch.update(command, state, -.006, True, False)) + self.assertEqual(latch.manual_turn_recovery_timer, 0.) + + def test_missing_model_blocks_entry_but_preserves_recovery(self): + command = SimpleNamespace(latActive=True) + state = turn_state() + latch = ManualTurnLatch() + self.assertFalse(latch.update(command, state, .006, True, False, False)) + self.assertTrue(latch.update(command, state, .006, True, False, True)) + state.out.steeringPressed = False + state.out.rightBlinker = False + state.out.steeringAngleDeg = 0. + for _ in range(4): + self.assertTrue(latch.update(command, state, 0., True, False, False)) + self.assertFalse(latch.update(command, state, 0., True, False, False)) + + def test_controller_real_can_yield_counter_and_recovery(self): + candidate = CAR.FORD_MUSTANG_MACH_E_MK1 + cp = params(candidate) + state = CarState(cp) + state.update(state.get_can_parsers(cp)) + out = structs.CarState() + out.vEgoRaw = 20. + out.steeringPressed = True + out.steeringAngleDeg = -12. + out.steeringTorque = -1. + out.rightBlinker = True + state.out = out.as_reader() + command = structs.CarControl() + command.latActive = True + command.actuators.curvature = .006 + controller = CarController(DBC[candidate], cp) + controller.manual_turn_inputs = SimpleNamespace(update=lambda: (True, False, True)) + parser = CANParser(DBC[candidate][Bus.pt], [('LateralMotionControl2', 20)], controller.CAN.main) + for index in range(10): + controller.frame = index * 5 + if index == 1: + out.steeringPressed = False + out.steeringAngleDeg = 0. + out.rightBlinker = False + if index == 7: + command.actuators.curvature = -.001 + state.out = out.as_reader() + _, messages = controller.update(command.as_reader(), state, (index + 1) * 50_000_000) + wire = next(message for message in messages if message[0] == 0x3D6) + expected = fordcan.create_lat_ctl2_msg(controller.packer, controller.CAN, int(index >= 7), 0., 0., + -controller.apply_curvature_last, 0., index) + self.assertEqual(wire, expected) + parser.update([((index + 1) * 50_000_000, messages)]) + values = parser.vl['LateralMotionControl2'] + self.assertEqual(values['LatCtlPath_No_Cnt'], index) + self.assertEqual(values['LatCtl_D2_Rq'], int(index >= 7)) + if index < 7: + self.assertAlmostEqual(values['LatCtlCurv_No_Actl'], 0., places=5) + self.assertEqual(controller.apply_curvature_last, 0.) + self.assertTrue(parser.can_valid) + + def test_other_platform_and_lka_do_not_create_inputs(self): + for candidate in (CAR.FORD_BRONCO_SPORT_MK1, CAR.FORD_TRANSIT_MK5): + cp = params(candidate) + controller = CarController(DBC[candidate], cp) + self.assertIsNone(controller.manual_turn) + state = CarState(cp) + state.update(state.get_can_parsers(cp)) + state.out = structs.CarState().as_reader() + controller.update(structs.CarControl().as_reader(), state, 0) diff --git a/opendbc_repo/opendbc/car/ford/tests/test_required_source_health.py b/opendbc_repo/opendbc/car/ford/tests/test_required_source_health.py new file mode 100644 index 0000000000..fce2cc60e2 --- /dev/null +++ b/opendbc_repo/opendbc/car/ford/tests/test_required_source_health.py @@ -0,0 +1,96 @@ +import pytest + +from opendbc.can import CANPacker +from opendbc.car import structs +from opendbc.car.ford.interface import CarInterface +from opendbc.car.ford.tests.test_three_ports import params +from opendbc.car.ford.values import CAR, FordFlags + + +BASE_PT = ( + ("BrakeSysFeatures", 50), + ("Yaw_Data_FD1", 100), + ("DesiredTorqBrk", 50), + ("EngVehicleSpThrottle", 100), + ("EngBrakeData", 10), + ("EPAS_INFO", 50), + ("Cluster_Info1_FD1", 10), + ("Steering_Data_FD1", 10), + ("BodyInfo_3_FD1", 2), + ("RCMStatusMessage2_FD1", 10), +) +BASE_CAMERA = (("ACCDATA", 50), ("ACCDATA_2", 50), ("ACCDATA_3", 5), ("IPMA_Data", 1)) +SOURCE_CASES = ( + (CAR.FORD_EDGE_MK2, "TransGearData", "GearLvrPos_D_Actl", "SteeringPinion_Data_Alt"), + (CAR.FORD_MONDEO_MK5, "Gear_Shift_by_Wire_FD1", "TrnRng_D_RqGsm", "SteeringPinion_Data"), + (CAR.FORD_TRANSIT_MK5, "PowertrainData_10", "TrnRng_D_Rq", "SteeringPinion_Data"), +) + + +def inventory(candidate): + cp = params(candidate) + gear, gear_signal, steering = next(row[1:] for row in SOURCE_CASES if row[0] == candidate) + pt = list(BASE_PT) + [(gear, 10), (steering, 100)] + camera = list(BASE_CAMERA) + if candidate == CAR.FORD_EDGE_MK2: + pt.extend((("ParkAid_Data", 50), ("INSTRUMENT_PANEL", 1))) + elif candidate == CAR.FORD_MONDEO_MK5: + pt.append(("Lane_Assist_Data3_FD1", 30)) + else: + pt.extend((("INSTRUMENT_PANEL", 1), ("Lane_Assist_Data3_FD1", 30))) + camera.append(("LateralMotionControl", 20)) + return cp, gear, gear_signal, steering, [(name, 0, rate) for name, rate in pt] + [(name, 2, rate) for name, rate in camera] + + +def stream(packer, entries, tick, gear, gear_signal, *, omitted=None, wrong_bus=None): + fields = { + "BrakeSysFeatures": {"Veh_V_ActlBrk": 72, "VehVActlBrk_D_Qf": 3}, + "Yaw_Data_FD1": {"VehYawWActl_D_Qf": 3}, + "EngBrakeData": {"BpedDrvAppl_D_Actl": 1, "CcStat_D_Actl": 3}, + "SteeringPinion_Data": {"StePinCompAnEst_D_Qf": 3}, + "SteeringPinion_Data_Alt": {"StePinRelInit_An_Sns": 5}, + "ParkAid_Data": {"ExtSteeringAngleReq2": 5}, + "Lane_Assist_Data3_FD1": {"LatCtlSte_D_Stat": 1, "LaActAvail_D_Actl": 3}, + gear: {gear_signal: 3}, + } + frames = [] + for name, bus, rate in entries: + if name == omitted or (tick > 0 and (tick * rate) // 100 == ((tick - 1) * rate) // 100): + continue + values = fields.get(name, {}) + assert set(values) <= set(packer.dbc.name_to_msg[name].sigs) + frames.append(packer.make_can_msg(name, 1 if name == wrong_bus else bus, values)) + return frames + + +@pytest.mark.parametrize('candidate,gear,gear_signal,steering', SOURCE_CASES) +@pytest.mark.parametrize('lost_kind', ('speed', 'brake', 'gear', 'steering', 'wrong-bus-speed')) +def test_actual_whole_parser_critical_source_loss_and_recovery(candidate, gear, gear_signal, steering, lost_kind): + cp, selected_gear, selected_signal, selected_steering, entries = inventory(candidate) + assert (selected_gear, selected_signal, selected_steering) == (gear, gear_signal, steering) + assert cp.transmissionType == structs.CarParams.TransmissionType.automatic + assert cp.flags & FordFlags.NEW_PORT + ci = CarInterface(cp) + ci.update([]) + packer = CANPacker('ford_lincoln_base_pt') + for tick in range(200): + out = ci.update([(1_000_000_000 + tick * 10_000_000, stream(packer, entries, tick, gear, gear_signal))]) + assert out.canValid + assert out.gearShifter == structs.CarState.GearShifter.drive + assert not out.vehicleSensorsInvalid + lost = {'speed': 'BrakeSysFeatures', 'brake': 'EngBrakeData', 'gear': gear, 'steering': steering, 'wrong-bus-speed': 'BrakeSysFeatures'}[lost_kind] + for tick in range(200, 500): + frames = stream( + packer, + entries, + tick, + gear, + gear_signal, + omitted=None if lost_kind == 'wrong-bus-speed' else lost, + wrong_bus=lost if lost_kind == 'wrong-bus-speed' else None, + ) + out = ci.update([(1_000_000_000 + tick * 10_000_000, frames)]) + assert not out.canValid + for tick in range(500, 700): + out = ci.update([(1_000_000_000 + tick * 10_000_000, stream(packer, entries, tick, gear, gear_signal))]) + assert out.canValid diff --git a/opendbc_repo/opendbc/car/ford/tests/test_stock_cruise.py b/opendbc_repo/opendbc/car/ford/tests/test_stock_cruise.py new file mode 100644 index 0000000000..3586057329 --- /dev/null +++ b/opendbc_repo/opendbc/car/ford/tests/test_stock_cruise.py @@ -0,0 +1,103 @@ +"""Original switch context, state event and reached controller regressions.""" +from opendbc.can import CANPacker +from opendbc.car import Bus, structs, gen_empty_fingerprint +from opendbc.car.ford.interface import CarInterface +from opendbc.car.ford.stock_cruise import FordStockCruiseButton, qualified +from opendbc.car.ford.carstate import CarState +from opendbc.car.ford.carcontroller import CarController +from opendbc.car.ford.values import CAR, DBC +from opendbc.car.ford.tests.test_three_ports import params + + +def test_original_press_context_is_held_until_release_and_master_off_denies(): + owner = FordStockCruiseButton() + assert owner.update(True, True, True) == (True, False) + assert owner.update(True, True, False) == (True, False) + assert owner.update(False, True, False) == (False, False) + assert owner.update(True, True, False) == (False, True) + assert owner.update(True, True, True) == (False, True) + assert owner.update(False, True, True) == (False, False) + assert owner.update(True, False, False) == (False, False) + assert owner.update(True, True, True) == (False, False) + + +def test_actual_parser_cancel_edges_are_op_long_only_and_contextual(): + for op_long in (False, True): + cp = params(CAR.FORD_MUSTANG_MACH_E_MK1, alpha=op_long) + state = CarState(cp) + parsers = state.get_can_parsers(cp) + packer = CANPacker(DBC[cp.carFingerprint][Bus.pt]) + for i, (pressed, enabled, expected) in enumerate(((0, True, []), (1, True, [True]), + (1, False, []), (0, False, [False]), + (1, False, []), (1, True, []))): + rx = [packer.make_can_msg('Steering_Data_FD1', 0, {'CcAslButtnCnclResPress': pressed}), + packer.make_can_msg('EngBrakeData', 0, {'CcStat_D_Actl': 5 if enabled else 3}), + packer.make_can_msg('Cluster_Info1_FD1', 0, {'AccEnbl_B_RqDrv': 1})] + parsers[Bus.pt].update([(1_000_000_000+i*10_000_000, rx)]) + out = state.update(parsers) + cancel = [event.pressed for event in out.buttonEvents if event.type == structs.CarState.ButtonEvent.Type.cancel] + assert cancel == (expected if op_long else []) + + +def test_reached_controller_preserves_precedence_cadence_and_stock_bits(): + cp = params(CAR.FORD_MUSTANG_MACH_E_MK1, alpha=False) + controller = CarController(DBC[cp.carFingerprint], cp) + state = CarState(cp) + state.update(state.get_can_parsers(cp)) + out = structs.CarState(vEgoRaw=10.) + out.cruiseState.available = True + state.out = out.as_reader() + state.buttons_stock_values['CcAslButtnCnclResPress'] = 1 + state.buttons_stock_values['TurnLghtSwtch_D_Stat'] = 2 + state.acc_tja_status_stock_values['Tja_D_Stat'] = 0 + command = structs.CarControl() + for frame in range(11): + controller.frame = frame + _, packets = controller.update(command.as_reader(), state, frame*10_000_000) + buttons = [(bus, data) for address, data, bus in packets if address == 0x83] + assert len(buttons) == (2 if frame % 5 == 0 else 0) + if buttons: + assert [bus for bus, _ in buttons] == [controller.CAN.camera, controller.CAN.main] + assert all(data[3] & 2 for _, data in buttons) + command.cruiseControl.cancel = True + controller.frame = 11 + _, packets = controller.update(command.as_reader(), state, 110_000_000) + buttons = [data for address, data, _ in packets if address == 0x83] + assert len(buttons) == 2 and all(data[1] & 1 for data in buttons) + assert not any(data[3] & 2 for data in buttons) + + +def test_unknown_ae_longitudinal_and_unpaired_profiles_deny_translation(): + # Actual factory results, not fabricated safety words. Classic stock0 is unreached. + fingerprint = gen_empty_fingerprint() + fingerprint[0][0x5a] = 8 + fingerprint[2][0x3d6] = fingerprint[2][0x186] = 8 + matrix = ((CAR.FORD_F_150_MK14, 66), (CAR.FORD_EDGE_MK2, 8), + (CAR.FORD_MONDEO_MK5, 10), (CAR.FORD_TRANSIT_MK5, 12), + (CAR.FORD_MUSTANG_MACH_E_MK1, 18)) + for vehicle, word in matrix: + actual = CarInterface.get_params(vehicle, fingerprint, [], False, False, False) + assert actual.safetyConfigs[-1].safetyParam == word, vehicle + assert not actual.openpilotLongitudinalControl and qualified(actual), vehicle + unknown = params(CAR.FORD_MUSTANG_MACH_E_MK1, alpha=False) + unknown.carFingerprint = "unrecognized Ford" + assert not qualified(unknown) + cp = params(CAR.FORD_MUSTANG_MACH_E_MK1, alpha=False) + assert qualified(cp) + cp.alternativeExperience = 32 + assert qualified(cp) + cp.safetyConfigs = [cp.safetyConfigs[0], cp.safetyConfigs[0]] + assert not qualified(cp) + cp.safetyConfigs = [cp.safetyConfigs[0]] + for experience in (1, 64, 96): + cp.alternativeExperience = experience + assert not qualified(cp) + cp.alternativeExperience = 0 + cp.openpilotLongitudinalControl = True + assert not qualified(cp) + cp.openpilotLongitudinalControl = False + cp.safetyConfigs[-1].safetyParam = 19 + assert not qualified(cp) + for word in (0, 4, 34): + cp.safetyConfigs[-1].safetyParam = word + assert not qualified(cp) diff --git a/opendbc_repo/opendbc/car/ford/tests/test_three_ports.py b/opendbc_repo/opendbc/car/ford/tests/test_three_ports.py new file mode 100644 index 0000000000..ff9305ce1c --- /dev/null +++ b/opendbc_repo/opendbc/car/ford/tests/test_three_ports.py @@ -0,0 +1,195 @@ +import unittest + +from opendbc.can import CANPacker +from opendbc.car import Bus, gen_empty_fingerprint, structs +from opendbc.car.ford.carcontroller import CarController +from opendbc.car.ford.carstate import CarState +from opendbc.car.ford.interface import CarInterface +from opendbc.car.ford.values import CAR, DBC, FordFlags, FordSafetyFlags +from opendbc.car.ford.fingerprints import FW_VERSIONS +from opendbc.car.ford.radar_interface import RadarInterface +from opendbc.car.fw_versions import match_fw_to_car +from opendbc.safety.tests.libsafety import libsafety_py + + +PORTS = (CAR.FORD_EDGE_MK2, CAR.FORD_MONDEO_MK5, CAR.FORD_TRANSIT_MK5) + + +def params(candidate, alpha=False, release=False): + fingerprint = gen_empty_fingerprint() + fingerprint[0][0x5A] = 8 + fingerprint[2][0x3D6] = 8 + fingerprint[2][0x186] = 8 + return CarInterface.get_params(candidate, fingerprint, [], alpha, release, False) + + +class TestFordThreePorts(unittest.TestCase): + @staticmethod + def firmware(candidate): + return [structs.CarParams.CarFw(ecu=ecu, address=addr, subAddress=0 if sub is None else sub, + fwVersion=versions[0], brand="ford") + for (ecu, addr, sub), versions in FW_VERSIONS[candidate].items()] + + def test_production_firmware_requires_four_platform_sources(self): + required = (structs.CarParams.Ecu.eps, structs.CarParams.Ecu.abs, + structs.CarParams.Ecu.fwdRadar, structs.CarParams.Ecu.fwdCamera) + for candidate in PORTS: + full = self.firmware(candidate) + for allow_exact in (True, False): + with self.subTest(candidate=candidate, allow_exact=allow_exact, case="complete"): + self.assertEqual(match_fw_to_car(full, "", allow_exact=allow_exact, log=False)[1], {candidate}) + for omitted in required: + with self.subTest(candidate=candidate, allow_exact=allow_exact, omitted=omitted): + partial = [fw for fw in full if fw.ecu != omitted] + for vin in ("", "WF0XXXXXX00000000"): + self.assertEqual(match_fw_to_car(partial, vin, allow_exact=allow_exact, log=False)[1], set()) + mixed = self.firmware(CAR.FORD_EDGE_MK2) + self.firmware(CAR.FORD_MONDEO_MK5) + for allow_exact in (True, False): + self.assertEqual(match_fw_to_car(mixed, "", allow_exact=allow_exact, log=False)[1], + {CAR.FORD_EDGE_MK2, CAR.FORD_MONDEO_MK5}) + self.assertEqual(match_fw_to_car(self.firmware(CAR.FORD_FOCUS_MK4), "", allow_exact=False, log=False)[1], + {CAR.FORD_FOCUS_MK4}) + + def test_new_platform_ownership_and_classic_long_selection(self): + for candidate in PORTS: + with self.subTest(candidate=candidate): + stock = params(candidate) + self.assertFalse(stock.openpilotLongitudinalControl) + self.assertAlmostEqual(stock.steerActuatorDelay, 0.05 if candidate == CAR.FORD_TRANSIT_MK5 else 0.22, places=7) + self.assertTrue(stock.safetyConfigs[-1].safetyParam & FordSafetyFlags.NEW_PORT) + self.assertFalse(stock.safetyConfigs[-1].safetyParam & FordSafetyFlags.LONG_CONTROL) + requested = params(candidate, alpha=True) + self.assertTrue(requested.openpilotLongitudinalControl) + self.assertTrue(requested.safetyConfigs[-1].safetyParam & FordSafetyFlags.LONG_CONTROL) + if candidate == CAR.FORD_MONDEO_MK5: + self.assertFalse(params(candidate, alpha=True, release=True).openpilotLongitudinalControl) + self.assertAlmostEqual(params(CAR.FORD_MUSTANG_MACH_E_MK1).steerActuatorDelay, 0.22, places=7) + self.assertFalse(params(CAR.FORD_BRONCO_SPORT_MK1).openpilotLongitudinalControl) + self.assertTrue(params(CAR.FORD_BRONCO_SPORT_MK1, alpha=True).openpilotLongitudinalControl) + + def test_real_edge_angle_and_mondeo_gear_parsers(self): + cases: tuple[tuple[CAR, str, dict[str, float]], ...] = ( + (CAR.FORD_EDGE_MK2, "TransGearData", {"GearLvrPos_D_Actl": 4}), + (CAR.FORD_MONDEO_MK5, "Gear_Shift_by_Wire_FD1", {"TrnRng_D_RqGsm": 4}), + ) + for candidate, source_name, source_values in cases: + with self.subTest(candidate=candidate): + cp = params(candidate) + self.assertEqual(cp.transmissionType, structs.CarParams.TransmissionType.automatic) + state = CarState(cp) + parsers = state.get_can_parsers(cp) + packer = CANPacker(DBC[candidate][Bus.pt]) + messages = [packer.make_can_msg(source_name, 0, source_values)] + if candidate == CAR.FORD_EDGE_MK2: + messages += [packer.make_can_msg("SteeringPinion_Data_Alt", 0, {"StePinRelInit_An_Sns": 10.}), + packer.make_can_msg("ParkAid_Data", 0, {"ExtSteeringAngleReq2": 12., + "EPASExtAngleStatReq": 0, "ApaSys_D_Stat": 0})] + parsers[Bus.pt].update([(1_000_000_000, messages)]) + out = state.update(parsers) + self.assertEqual(out.gearShifter, structs.CarState.GearShifter.sport) + if candidate == CAR.FORD_EDGE_MK2: + self.assertFalse(out.vehicleSensorsInvalid) + self.assertAlmostEqual(out.steeringAngleDeg, 12., places=1) + + # The existing CAN FD family still reads the powertrain gear, even when a + # conflicting shift-by-wire frame is present on the same bus. + candidate = CAR.FORD_MUSTANG_MACH_E_MK1 + cp = params(candidate) + state = CarState(cp) + parsers = state.get_can_parsers(cp) + state.update(parsers) + packer = CANPacker(DBC[candidate][Bus.pt]) + parsers[Bus.pt].update([(1_000_000_000, [packer.make_can_msg("PowertrainData_10", 0, {"TrnRng_D_Rq": 3}), + packer.make_can_msg("Gear_Shift_by_Wire_FD1", 0, {"TrnRng_D_RqGsm": 4})])]) + self.assertEqual(state.update(parsers).gearShifter, structs.CarState.GearShifter.drive) + + def test_mondeo_camera_radar_needs_current_confident_object(self): + cp = params(CAR.FORD_MONDEO_MK5) + radar = RadarInterface(cp) + packer = CANPacker(DBC[CAR.FORD_MONDEO_MK5][Bus.pt]) + observed = packer.make_can_msg("Steer_Assist_Data", 2, + {"CmbbObjConfdnc_D_Stat": 2, "CmbbObjDistLong_L_Actl": 24., + "CmbbObjRelLong_V_Actl": -2.}) + first = radar.update([(1_000_000_000, [observed])]) + self.assertEqual(len(first.points), 1) + self.assertAlmostEqual(first.points[0].dRel, 24.) + self.assertAlmostEqual(first.points[0].vRel, -2.) + self.assertIsNone(radar.update([(1_100_000_000, [])])) + lost = packer.make_can_msg("Steer_Assist_Data", 2, {"CmbbObjConfdnc_D_Stat": 0}) + self.assertEqual(len(radar.update([(1_150_000_000, [lost])]).points), 0) + + def check_transit_source_gates_real_controller_messages(self, yaw_rate): + cp = params(CAR.FORD_TRANSIT_MK5) + self.assertTrue(cp.flags & FordFlags.LKA_STEERING) + state = CarState(cp) + parsers = state.get_can_parsers(cp) + packer = CANPacker(DBC[CAR.FORD_TRANSIT_MK5][Bus.pt]) + source = packer.make_can_msg("Lane_Assist_Data3_FD1", 0, {"LaActAvail_D_Actl": 3}) + received = [] + for count in range(1, 7): + messages = [ + packer.make_can_msg("BrakeSysFeatures", 0, + {"Veh_V_ActlBrk": 108., "VehVActlBrk_D_Qf": 3, "VehVActlBrk_No_Cnt": count}), + packer.make_can_msg("EngVehicleSpThrottle2", 0, {"Veh_V_ActlEng": 108., "VehVActlEng_D_Qf": 3}), + packer.make_can_msg("Yaw_Data_FD1", 0, {"VehYaw_W_Actl": yaw_rate, + "VehYawWActl_D_Qf": 3, "VehRollYaw_No_Cnt": count}), + packer.make_can_msg("EngBrakeData", 0, {"BpedDrvAppl_D_Actl": 1, "CcStat_D_Actl": 5}), + packer.make_can_msg("EngVehicleSpThrottle", 0, {"ApedPos_Pc_ActlArb": 0}), + packer.make_can_msg("DesiredTorqBrk", 0, {"VehStop_D_Stat": 0}), + ] + if count == 6: + messages += [source, packer.make_can_msg("SteeringPinion_Data", 0, + {"StePinCompAnEst_D_Qf": 3})] + received += messages + parsers[Bus.pt].update([(940_000_000 + count * 10_000_000, messages)]) + parsers[Bus.cam].update([(1_000_000_000, [packer.make_can_msg("LateralMotionControl", 2, {})])]) + out = state.update(parsers) + self.assertTrue(state.lkas_available) + self.assertAlmostEqual(out.vEgoRaw, 30., places=1) + self.assertTrue(out.cruiseState.enabled) + control = structs.CarControl() + control.latActive = True + control.actuators.steeringAngleDeg = out.steeringAngleDeg + 1. + control.actuators.curvature = -yaw_rate / 30. if yaw_rate else 0.01023 + state.out = out.as_reader() + controller = CarController(DBC[CAR.FORD_TRANSIT_MK5], cp) + _, messages = controller.update(control.as_reader(), state, 1_000_000_000) + self.assertIn(0x3D3, [msg[0] for msg in messages]) + self.assertIn(0x3CA, [msg[0] for msg in messages]) + self.assertEqual(next(msg for msg in messages if msg[0] == 0x3CA)[1][0] >> 5, 2) + self.assertLess(abs(controller.apply_lka_curvature_last), 0.00013) + if yaw_rate: + self.assertGreater(controller.apply_lka_curvature_last * yaw_rate, 0.) + safety = libsafety_py.libsafety + self.assertEqual(safety.set_safety_hooks(structs.CarParams.SafetyModel.ford, + int(cp.safetyConfigs[-1].safetyParam)), 0) + safety.init_tests() + safety.set_controls_allowed(True) + for msg in received: + self.assertTrue(safety.safety_rx_hook(libsafety_py.make_CANPacket(msg[0], msg[2], msg[1]))) + for address in (0x3D3, 0x3CA): + msg = next(msg for msg in messages if msg[0] == address) + self.assertTrue(safety.safety_tx_hook(libsafety_py.make_CANPacket(msg[0], msg[2], msg[1]))) + + # The next 33 Hz command must retain the measured-yaw coordinate in both + # host limiting and the native curvature/error checks. + controller.frame = 3 + _, repeated = controller.update(control.as_reader(), state, 1_030_000_000) + if yaw_rate: + self.assertGreater(controller.apply_lka_curvature_last * yaw_rate, 0.) + repeated_lka = next(msg for msg in repeated if msg[0] == 0x3CA) + self.assertTrue(safety.safety_tx_hook(libsafety_py.make_CANPacket(repeated_lka[0], repeated_lka[2], repeated_lka[1]))) + + controller.frame = 6 + _, stale_messages = controller.update(control.as_reader(), state, 1_200_000_000) + self.assertEqual(next(msg for msg in stale_messages if msg[0] == 0x3CA)[1][0] >> 5, 0) + denied = packer.make_can_msg("Lane_Assist_Data3_FD1", 0, + {"LaActAvail_D_Actl": 3, "LaActDeny_B_Actl": 1}) + parsers[Bus.pt].update([(1_230_000_000, [denied])]) + state.update(parsers) + self.assertFalse(state.lkas_available) + + def test_transit_source_gates_real_controller_messages(self): + for yaw_rate in (0., -0.03, 0.03): + with self.subTest(yaw_rate=yaw_rate): + self.check_transit_source_gates_real_controller_messages(yaw_rate) diff --git a/opendbc_repo/opendbc/car/ford/values.py b/opendbc_repo/opendbc/car/ford/values.py index b28f45ff65..9b18c74b25 100644 --- a/opendbc_repo/opendbc/car/ford/values.py +++ b/opendbc_repo/opendbc/car/ford/values.py @@ -28,6 +28,7 @@ class CarControllerParams: # ~0.009 m^-1/sec at 7 m/s, ~0.002 m^-1/sec at 35 m/s # We observed no windup so we allow higher than EPS CURVATURE_LIMITS: CurvatureSteeringLimits = CurvatureSteeringLimits(0.02) # Max curvature for steering command, m^-1 + LKA_CURVATURE_LIMITS: CurvatureSteeringLimits = CurvatureSteeringLimits(0.01023) # Transit 0x3CA, m^-1 CURVATURE_ERROR = 0.002 # ~6 degrees at 10 m/s, ~10 degrees at 35 m/s ACCEL_MAX = 2.0 # m/s^2 max acceleration @@ -42,6 +43,13 @@ class CarControllerParams: class FordSafetyFlags(IntFlag): LONG_CONTROL = 1 CANFD = 2 + LKA_STEERING = 4 + NEW_PORT = 8 + MACH_E_EXTENDED = 16 + CLASSIC_EXTENDED = 32 + EXPLORER_EXTENDED = CLASSIC_EXTENDED # Existing public profile spelling. + BLUEPILOT_ANGLE = 128 + GENERIC_CANFD_EXTENDED = 64 class FordFlags(IntFlag): @@ -50,11 +58,15 @@ class FordFlags(IntFlag): # Static flags CANFD = 1 + ALT_STEER_ANGLE = 16 # static alternate EPS source; distinct from detected HAS_BSM + LKA_STEERING = 4 + NEW_PORT = 8 class RADAR: DELPHI_ESR = 'ford_fusion_2018_adas' DELPHI_MRR = 'FORD_CADS' + STEER_ASSIST_DATA = 'ford_lincoln_base_pt' class Footnote(Enum): @@ -110,6 +122,13 @@ class FordCANFDPlatformConfig(FordPlatformConfig): self.flags |= FordFlags.CANFD +@dataclass +class FordLKASteeringPlatformConfig(FordPlatformConfig): + def init(self): + super().init() + self.flags |= FordFlags.LKA_STEERING + + @dataclass class FordF150LightningPlatform(FordCANFDPlatformConfig): def init(self): @@ -124,6 +143,11 @@ class CAR(Platforms): [FordCarDocs("Ford Bronco Sport 2021-24")], CarSpecs(mass=1625, wheelbase=2.67, steerRatio=17.7), ) + FORD_EDGE_MK2 = FordPlatformConfig( + [FordCarDocs("Ford Edge 2022")], + CarSpecs(mass=1933, wheelbase=2.824, steerRatio=15.3), + flags=FordFlags.ALT_STEER_ANGLE | FordFlags.NEW_PORT, + ) FORD_ESCAPE_MK4 = FordPlatformConfig( [ FordCarDocs("Ford Escape 2020-22", hybrid=True, plug_in_hybrid=True), @@ -138,6 +162,7 @@ class CAR(Platforms): FordCarDocs("Ford Kuga Plug-in Hybrid 2024", "All"), ], CarSpecs(mass=1750, wheelbase=2.71, steerRatio=16.7), + dbc_dict={Bus.pt: 'ford_lincoln_base_pt', Bus.radar: RADAR.STEER_ASSIST_DATA}, ) FORD_EXPLORER_MK6 = FordPlatformConfig( [ @@ -149,19 +174,28 @@ class CAR(Platforms): FORD_EXPEDITION_MK4 = FordCANFDPlatformConfig( [FordCarDocs("Ford Expedition 2022-24", "Co-Pilot360 Assist 2.0", hybrid=False)], CarSpecs(mass=2000, wheelbase=3.69, steerRatio=17.0), + dbc_dict={Bus.pt: 'ford_lincoln_base_pt', Bus.radar: RADAR.STEER_ASSIST_DATA}, ) FORD_F_150_MK14 = FordCANFDPlatformConfig( [FordCarDocs("Ford F-150 2021-23", "Co-Pilot360 Assist 2.0", hybrid=True)], - CarSpecs(mass=2000, wheelbase=3.69, steerRatio=17.0), + CarSpecs(mass=3334, wheelbase=3.99, steerRatio=17.0), + dbc_dict={Bus.pt: 'ford_lincoln_base_pt', Bus.radar: RADAR.STEER_ASSIST_DATA}, ) FORD_F_150_LIGHTNING_MK1 = FordF150LightningPlatform( [FordCarDocs("Ford F-150 Lightning 2022-23", "Co-Pilot360 Assist 2.0")], CarSpecs(mass=2948, wheelbase=3.70, steerRatio=16.9), + dbc_dict={Bus.pt: 'ford_lincoln_base_pt', Bus.radar: RADAR.STEER_ASSIST_DATA}, ) FORD_FOCUS_MK4 = FordPlatformConfig( [FordCarDocs("Ford Focus 2018-22", "Adaptive Cruise Control with Lane Centering", footnotes=[Footnote.FOCUS], hybrid=True)], # mHEV only CarSpecs(mass=1350, wheelbase=2.7, steerRatio=15.0), ) + FORD_MONDEO_MK5 = FordCANFDPlatformConfig( + [FordCarDocs("Ford Mondeo 2014-22", "Adaptive Cruise Control with Lane Centering")], + CarSpecs(mass=1550, wheelbase=2.85, steerRatio=14.8), + flags=FordFlags.NEW_PORT, + dbc_dict={Bus.pt: 'ford_lincoln_base_pt', Bus.radar: RADAR.STEER_ASSIST_DATA}, + ) FORD_MAVERICK_MK1 = FordPlatformConfig( [ FordCarDocs("Ford Maverick 2022", "LARIAT Luxury", hybrid=True), @@ -172,10 +206,17 @@ class CAR(Platforms): FORD_MUSTANG_MACH_E_MK1 = FordCANFDPlatformConfig( [FordCarDocs("Ford Mustang Mach-E 2021-24", "All", setup_video="https://www.youtube.com/watch?v=AR4_eTF3b_A")], CarSpecs(mass=2200, wheelbase=2.984, steerRatio=17.0), # TODO: check steer ratio + dbc_dict={Bus.pt: 'ford_lincoln_base_pt', Bus.radar: RADAR.STEER_ASSIST_DATA}, ) FORD_RANGER_MK2 = FordCANFDPlatformConfig( [FordCarDocs("Ford Ranger 2024", "Adaptive Cruise Control with Lane Centering", setup_video="https://www.youtube.com/watch?v=2oJlXCKYOy0")], CarSpecs(mass=2000, wheelbase=3.27, steerRatio=17.0), + dbc_dict={Bus.pt: 'ford_lincoln_base_pt', Bus.radar: RADAR.STEER_ASSIST_DATA}, + ) + FORD_TRANSIT_MK5 = FordLKASteeringPlatformConfig( + [FordCarDocs("Ford Transit 2025", "Co-Pilot360 Assist+")], + CarSpecs(mass=2068, wheelbase=3.302, steerRatio=16.7), + flags=FordFlags.NEW_PORT, ) diff --git a/opendbc_repo/opendbc/car/fw_versions.py b/opendbc_repo/opendbc/car/fw_versions.py index c6dfd38238..0d01799b52 100644 --- a/opendbc_repo/opendbc/car/fw_versions.py +++ b/opendbc_repo/opendbc/car/fw_versions.py @@ -171,6 +171,10 @@ def match_fw_to_car(fw_versions: list[CarParams.CarFw], vin: str, allow_exact: b if not exact_match and not len(matches) and config.match_fw_to_car_fuzzy is not None: matches |= config.match_fw_to_car_fuzzy(fw_versions_dict, vin, VERSIONS[brand]) + if config.validate_fw_match is not None: + matches = {candidate for candidate in matches if MODEL_TO_BRAND[candidate] != brand or + config.validate_fw_match(candidate, fw_versions_dict, VERSIONS[brand])} + if exact_match and allow_fuzzy and len(matches) > 1 and is_valid_vin(vin): # A shared ECU firmware version may identify a family but not a chassis. # Refine only within one brand's exact candidates; a VIN can narrow an diff --git a/opendbc_repo/opendbc/safety/modes/ford.h b/opendbc_repo/opendbc/safety/modes/ford.h index 4b1d7d9699..4a0b4f06fc 100644 --- a/opendbc_repo/opendbc/safety/modes/ford.h +++ b/opendbc_repo/opendbc/safety/modes/ford.h @@ -1,6 +1,14 @@ #pragma once #include "opendbc/safety/declarations.h" +#include "opendbc/safety/modes/ford_aol.h" +#include "opendbc/bluepilot_lateral/safety/ford_bp.h" + +// StarPilot's extended Ford curvature enforcement below is substantially adapted from +// BluePilot bp-7.0 panda work, principally Alan Polk's 8f8d6d15f0a590f42b78de964ffb0d0af7f5d63d +// See /CREDITS.md and /THIRD_PARTY_NOTICES.md. This comment does not attribute the surrounding +// upstream openpilot code. + // Safety-relevant CAN messages for Ford vehicles. #define FORD_EngBrakeData 0x165U // RX from PCM, for driver brake pedal and cruise state @@ -13,6 +21,7 @@ #define FORD_ACCDATA 0x186U // TX by OP, ACC controls #define FORD_ACCDATA_3 0x18AU // TX by OP, ACC/TJA user interface #define FORD_Lane_Assist_Data1 0x3CAU // TX by OP, Lane Keep Assist +#define FORD_Lane_Assist_Data3 0x3CCU // RX from PSCM, LKA availability #define FORD_LateralMotionControl 0x3D3U // TX by OP, Lateral Control message #define FORD_LateralMotionControl2 0x3D6U // TX by OP, alternate Lateral Control message #define FORD_IPMA_Data 0x3D8U // TX by OP, IPMA and LKAS user interface @@ -96,7 +105,52 @@ static const CurvatureSteeringLimits FORD_STEERING_LIMITS = { .max_steer_power = 0, // disabled, Ford has no steed power signal }; +// Transit 0x3CA has 0.000005 rad/m per raw step and runs at 33 Hz. Keep its +// command history separate from the inactive 0x3D3 heartbeat at 20 Hz. +static const CurvatureSteeringLimits FORD_LKA_STEERING_LIMITS = { + .max_curvature = 2046, + .curvature_to_can = 200000, + .frequency = 33, + .max_curvature_error = 400, + .curvature_error_min_speed = 10.0, + .max_steer_power = 0, +}; + +static bool ford_cancel_resume_button = false; + +static bool ford_generic_canfd_extended = false; +static bool ford_generic_canfd_announced = false; + +static bool ford_explorer_extended = false; +static bool ford_explorer_announced = false; + +static bool ford_mach_e_extended = false; +static bool ford_mach_e_announced = false; +static int ford_mach_e_path_angle_last = 0; + +static bool ford_lka_steering = false; +static bool ford_lka_available = false; +static uint32_t ford_lka_last_us = 0U; +static uint32_t ford_lka_speed_last_us = 0U; +static uint32_t ford_lka_speed2_last_us = 0U; +static uint32_t ford_lka_yaw_last_us = 0U; +static bool ford_lka_speed_seen = false; +static bool ford_lka_speed2_seen = false; +static bool ford_lka_yaw_seen = false; +static CurvatureSteeringState ford_lka_curvature_state; +static int ford_lka_angle_last = 2048; + +static bool ford_lka_curvature_checks(int desired_curvature, bool active) { + CurvatureSteeringState previous = curvature_state; + curvature_state = ford_lka_curvature_state; + bool violation = steer_curvature_cmd_checks(desired_curvature, 0, active, FORD_LKA_STEERING_LIMITS); + ford_lka_curvature_state = curvature_state; + curvature_state = previous; + return violation; +} + static void ford_rx_hook(const CANPacket_t *msg) { + ford_aol_rx(msg); // Update in motion state from standstill signal if (msg_matches(msg, FORD_DesiredTorqBrk, FORD_MAIN_BUS)) { // Signal: VehStop_D_Stat @@ -107,6 +161,11 @@ static void ford_rx_hook(const CANPacket_t *msg) { if (msg_matches(msg, FORD_BrakeSysFeatures, FORD_MAIN_BUS)) { // Signal: Veh_V_ActlBrk UPDATE_VEHICLE_SPEED(((msg->data[0] << 8) | msg->data[1]) * 0.01 * KPH_TO_MS); + if (ford_lka_steering) { ford_lka_speed_seen = true; ford_lka_speed_last_us = microsecond_timer_get(); } + } + if (msg_matches(msg, FORD_Lane_Assist_Data3, FORD_MAIN_BUS) && ford_lka_steering) { + ford_lka_available = (((msg->data[0] >> 4) & 0x3U) == 3U) && ((msg->data[0] & 0x40U) == 0U); + ford_lka_last_us = microsecond_timer_get(); } // Check vehicle speed against a second source @@ -115,6 +174,7 @@ static void ford_rx_hook(const CANPacket_t *msg) { // Signal: Veh_V_ActlEng float filtered_pcm_speed = ((msg->data[6] << 8) | msg->data[7]) * 0.01 * KPH_TO_MS; UPDATE_VEHICLE_SPEED_2(filtered_pcm_speed); + if (ford_lka_steering) { ford_lka_speed2_seen = true; ford_lka_speed2_last_us = microsecond_timer_get(); } } // Update vehicle yaw rate @@ -126,6 +186,11 @@ static void ford_rx_hook(const CANPacket_t *msg) { float current_curvature = ford_yaw_rate / SAFETY_MAX(vehicle_speed.values[0] / VEHICLE_SPEED_FACTOR, 0.1); // convert current curvature into units on CAN for comparison with desired curvature update_sample(&curvature_state.meas, ROUND(current_curvature * FORD_STEERING_LIMITS.curvature_to_can)); + if (ford_lka_steering) { + update_sample(&ford_lka_curvature_state.meas, ROUND(current_curvature * FORD_LKA_STEERING_LIMITS.curvature_to_can)); + ford_lka_yaw_seen = true; + ford_lka_yaw_last_us = microsecond_timer_get(); + } } // Update gas pedal @@ -144,7 +209,15 @@ static void ford_rx_hook(const CANPacket_t *msg) { unsigned int cruise_state = msg->data[1] & 0x07U; bool cruise_engaged = (cruise_state == 4U) || (cruise_state == 5U); pcm_cruise_check(cruise_engaged); + if (ford_stock_switch) { + acc_main_on = (cruise_state == 3U) || cruise_engaged; + } } + if (ford_stock_switch && msg_matches(msg, FORD_Steering_Data_FD1, FORD_MAIN_BUS)) { + // Physical combined cancel/resume switch, not the outgoing resume signal. + ford_cancel_resume_button = (msg->data[2] & 0x20U) != 0U; + } + ford_bp_rx(msg); } static bool ford_tx_hook(const CANPacket_t *msg) { @@ -201,7 +274,10 @@ static bool ford_tx_hook(const CANPacket_t *msg) { // if cancel button is pressed when cruise isn't engaged. bool violation = false; violation |= ((msg->data[1] >> 0) & 1U) && !cruise_engaged_prev; // Signal: CcAslButtnCnclPress (cancel) - violation |= ((msg->data[3] >> 1) & 1U) && !controls_allowed; // Signal: CcAsllButtnResPress (resume) + // Only an actual stock-cruise driver switch can request resume while OP is + // inactive. Required RX health guards the original level-based permission. + const bool stock_resume_from_driver = ford_stock_switch && acc_main_on && ford_cancel_resume_button && aol_rx_healthy(); + violation |= ((msg->data[3] >> 1) & 1U) && !(controls_allowed || stock_resume_from_driver); // Signal: CcAsllButtnResPress (resume) if (violation) { tx = false; @@ -209,19 +285,71 @@ static bool ford_tx_hook(const CANPacket_t *msg) { } // Safety check for Lane_Assist_Data1 action - if (msg->addr == FORD_Lane_Assist_Data1) { + if ((msg->addr == FORD_Lane_Assist_Data1) && !ford_bp_enabled) { + if (ford_mach_e_extended || ford_explorer_extended) { + tx &= (msg->data[4] & 0x1U) == 0U; + } // Do not allow steering using Lane_Assist_Data1 (Lane-Departure Aid). // This message must be sent for Lane Centering to work, and can include // values such as the steering angle or lane curvature for debugging, // but the action (LkaActvStats_D2_Req) must be set to zero. unsigned int action = msg->data[0] >> 5; - if (action != 0U) { + if (ford_lka_steering) { + const int angle = ((msg->data[2] & 0xFU) << 8) | msg->data[3]; + const int curvature = (msg->data[1] << 4) | (msg->data[2] >> 4); + const uint32_t now = microsecond_timer_get(); + const bool source_current = ford_lka_available && ford_lka_speed_seen && ford_lka_speed2_seen && ford_lka_yaw_seen && + (cruise_engaged_prev || (ford_aol_enabled && (ford_aol_permission_mask() != 0U))) && + safety_get_ts_elapsed(now, ford_lka_last_us) <= 100000U && + safety_get_ts_elapsed(now, ford_lka_speed_last_us) <= 100000U && + safety_get_ts_elapsed(now, ford_lka_speed2_last_us) <= 100000U && + safety_get_ts_elapsed(now, ford_lka_yaw_last_us) <= 100000U; + const bool active = (action == 2U) || (action == 4U); + const bool direction_valid = ((action == 2U) && (angle >= 2048)) || ((action == 4U) && (angle < 2048)); + const bool payload_valid = (angle >= 24) && (angle <= 4072) && (curvature >= 2) && (curvature <= 4094) && + (SAFETY_ABS(angle - ford_lka_angle_last) <= 350) && + ((msg->data[4] & 0x60U) == 0U) && ((msg->data[0] & 0x1FU) == 3U); + if (active) { + if (!lateral_controls_allowed() || !source_current || !direction_valid || !payload_valid) { + tx = false; + } else if (ford_lka_curvature_checks(curvature - 2048, true)) { + tx = false; + } else { + // Valid active request keeps its transmit decision. + } + } else if ((action != 0U) || (angle != 2048) || (curvature != 2048)) { + tx = false; + } else { + // Neutral request needs no additional steering check. + } + if (tx) { + ford_lka_angle_last = active ? angle : 2048; + if (!active) { (void)ford_lka_curvature_checks(0, false); } + } else { + ford_lka_angle_last = 2048; + ford_lka_curvature_state.desired_last = 0; + } + } else if (action != 0U) { tx = false; + } else { + // Other Ford profiles retain their neutral status handling. } } + if (ford_mach_e_extended && tx && (msg->addr == FORD_Lane_Assist_Data1)) { + ford_mach_e_announced = (msg->data[4] & 0x2U) != 0U; + } + + if (ford_generic_canfd_extended && tx && (msg->addr == FORD_Lane_Assist_Data1)) { + ford_generic_canfd_announced = (msg->data[4] & 0x2U) != 0U; + } + + if (ford_explorer_extended && tx && (msg->addr == FORD_Lane_Assist_Data1)) { + ford_explorer_announced = (msg->data[4] & 0x2U) != 0U; + } + // Safety check for LateralMotionControl action - if (msg->addr == FORD_LateralMotionControl) { + if ((msg->addr == FORD_LateralMotionControl) && !ford_bp_enabled) { // Signal: LatCtl_D_Rq bool steer_control_enabled = ((msg->data[4] >> 2) & 0x7U) != 0U; unsigned int raw_curvature = (msg->data[0] << 3) | (msg->data[1] >> 5); @@ -229,20 +357,39 @@ static bool ford_tx_hook(const CANPacket_t *msg) { unsigned int raw_path_angle = (msg->data[3] << 3) | (msg->data[4] >> 5); unsigned int raw_path_offset = (msg->data[5] << 2) | (msg->data[6] >> 6); - // These signals are not yet tested with the current safety limits - bool violation = (raw_curvature_rate != FORD_INACTIVE_CURVATURE_RATE) || (raw_path_angle != FORD_INACTIVE_PATH_ANGLE) || (raw_path_offset != FORD_INACTIVE_PATH_OFFSET); - - // Check angle error and steer_control_enabled - int desired_curvature = raw_curvature - FORD_INACTIVE_CURVATURE; // /FORD_STEERING_LIMITS.curvature_to_can to get real curvature + // Explorer restores only the classic source-derived curvature-rate field. + // Every command still intersects the modern common curvature envelope. + bool violation = (raw_path_angle != FORD_INACTIVE_PATH_ANGLE) || + (raw_path_offset != FORD_INACTIVE_PATH_OFFSET); + const unsigned int curvature_bits = raw_curvature; + const int desired_curvature = (int)curvature_bits - 1000; + if (ford_explorer_extended) { + static const struct lookup_t source_rate = {{5.0F, 16.0F, 25.0F}, {0.0025F, 0.0014F, 0.00018F}}; + if (steer_control_enabled && lateral_controls_allowed()) { + const float source_speed = (vehicle_speed.min / VEHICLE_SPEED_FACTOR) - 1.0F; + const float source_delta_float = (safety_interpolate(source_rate, source_speed) * 50000.0F) + 1.0F; + const int source_delta = (int)source_delta_float; + violation |= SAFETY_ABS(desired_curvature - curvature_state.desired_last) > source_delta; + } + violation |= steer_control_enabled && !ford_explorer_announced; + violation |= !steer_control_enabled && ((desired_curvature != 0) || + (raw_curvature_rate != FORD_INACTIVE_CURVATURE_RATE)); + } else { + violation |= raw_curvature_rate != FORD_INACTIVE_CURVATURE_RATE; + } violation |= steer_curvature_cmd_checks(desired_curvature, 0, steer_control_enabled, FORD_STEERING_LIMITS); + violation |= ford_lka_steering && steer_control_enabled; if (violation) { tx = false; + if (ford_explorer_extended) { + curvature_state.desired_last = 0; + } } } // Safety check for LateralMotionControl2 action - if (msg->addr == FORD_LateralMotionControl2) { + if ((msg->addr == FORD_LateralMotionControl2) && !ford_bp_enabled) { // Signal: LatCtl_D2_Rq bool steer_control_enabled = ((msg->data[0] >> 4) & 0x7U) != 0U; unsigned int raw_curvature = (msg->data[2] << 3) | (msg->data[3] >> 5); @@ -250,35 +397,132 @@ static bool ford_tx_hook(const CANPacket_t *msg) { unsigned int raw_path_angle = ((msg->data[3] & 0x1FU) << 6) | (msg->data[4] >> 2); unsigned int raw_path_offset = ((msg->data[4] & 0x3U) << 8) | msg->data[5]; - // These signals are not yet tested with the current safety limits - bool violation = (raw_curvature_rate != FORD_CANFD_INACTIVE_CURVATURE_RATE) || (raw_path_angle != FORD_INACTIVE_PATH_ANGLE) || (raw_path_offset != FORD_INACTIVE_PATH_OFFSET); - - // Check angle error and steer_control_enabled - int desired_curvature = raw_curvature - FORD_INACTIVE_CURVATURE; // /FORD_STEERING_LIMITS.curvature_to_can to get real curvature - violation |= steer_curvature_cmd_checks(desired_curvature, 0, steer_control_enabled, FORD_STEERING_LIMITS); - - if (violation) { - tx = false; + const unsigned int curvature_bits = raw_curvature; + const int desired_curvature = (int)curvature_bits - (int)FORD_INACTIVE_CURVATURE; + const int desired_path_angle = (int)raw_path_angle - (int)FORD_INACTIVE_PATH_ANGLE; + bool violation = raw_path_offset != FORD_INACTIVE_PATH_OFFSET; + if (ford_mach_e_extended) { + // Exact Mach-E extension retains the source envelope and the modern common + // ISO/RT checks. This is an intersection, not generic Ford limit widening. + static const CurvatureSteeringLimits FORD_MACH_E_STEERING_LIMITS = { + .max_curvature = 1000, + .curvature_to_can = 50000, + .frequency = 20, + .max_curvature_error = 300, + .curvature_error_min_speed = 10.0, + .max_steer_power = 0, + }; + const struct lookup_t source_rate = {{5.0F, 16.0F, 25.0F}, {0.0025F, 0.0014F, 0.00018F}}; + const float speed = vehicle_speed.max / VEHICLE_SPEED_FACTOR; + const float speed_min = SAFETY_MAX(vehicle_speed.min / VEHICLE_SPEED_FACTOR, 1.0F); + const int source_delta = (safety_interpolate(source_rate, speed_min - 1.0F) * 50000.0F) + 1.0F; + const float source_max_float = ((3.0F - (9.81F * 0.06F)) / (speed_min * speed_min) * 50000.0F) + 1.0F; + const int source_max = (int)source_max_float; + if (!ford_mach_e_announced) { + violation |= steer_control_enabled || (desired_path_angle != 0) || (raw_curvature_rate != FORD_CANFD_INACTIVE_CURVATURE_RATE); + } + if (steer_control_enabled) { + violation |= SAFETY_ABS(desired_curvature - curvature_state.desired_last) > source_delta; + violation |= SAFETY_ABS(desired_curvature) > source_max; + } else { + violation |= (desired_curvature != 0) || (raw_curvature_rate != FORD_CANFD_INACTIVE_CURVATURE_RATE); + } + if (desired_path_angle != 0) { + const float curvature = SAFETY_ABS(desired_curvature) / 50000.0F; + const float path_angle = SAFETY_ABS(desired_path_angle) / 2000.0F; + const float combined_accel = (curvature + (path_angle / SAFETY_MAX(speed, 1.0F))) * speed * speed; + violation |= !steer_control_enabled || !controls_allowed; + violation |= (speed < 3.0F) || (speed >= 8.8F); + violation |= (SAFETY_ABS(desired_curvature) < 975) || (SAFETY_ABS(desired_path_angle) > 320); + violation |= ((desired_curvature * desired_path_angle) <= 0) || (combined_accel > 2.5F); + violation |= SAFETY_ABS(desired_path_angle - ford_mach_e_path_angle_last) > 110; + } + violation |= steer_curvature_cmd_checks(desired_curvature, 0, steer_control_enabled, FORD_MACH_E_STEERING_LIMITS); + } else if (ford_generic_canfd_extended) { + // One generic CAN FD owner; Mach-E's wider error/path assist stays separate. + static const struct lookup_t source_rate = {{5.0F, 16.0F, 25.0F}, {0.0025F, 0.0014F, 0.00018F}}; + const float source_speed = SAFETY_MAX(vehicle_speed.min / VEHICLE_SPEED_FACTOR, 1.0F); + const float source_delta_float = (safety_interpolate(source_rate, source_speed - 1.0F) * 50000.0F) + 1.0F; + const int source_delta = (int)source_delta_float; + const float source_max_float = ((3.0F - (9.81F * 0.06F)) / (source_speed * source_speed) * 50000.0F) + 1.0F; + const int source_max = (int)source_max_float; + violation |= raw_path_angle != FORD_INACTIVE_PATH_ANGLE; + violation |= steer_control_enabled && !ford_generic_canfd_announced; + if (steer_control_enabled) { + violation |= SAFETY_ABS(desired_curvature - curvature_state.desired_last) > source_delta; + violation |= SAFETY_ABS(desired_curvature) > source_max; + } else { + violation |= (desired_curvature != 0) || (raw_curvature_rate != FORD_CANFD_INACTIVE_CURVATURE_RATE); + } + violation |= steer_curvature_cmd_checks(desired_curvature, 0, steer_control_enabled, FORD_STEERING_LIMITS); + } else { + violation |= (raw_curvature_rate != FORD_CANFD_INACTIVE_CURVATURE_RATE) || (raw_path_angle != FORD_INACTIVE_PATH_ANGLE); + violation |= steer_curvature_cmd_checks(desired_curvature, 0, steer_control_enabled, FORD_STEERING_LIMITS); + } + tx &= !violation; + if (ford_generic_canfd_extended && !tx) { + curvature_state.desired_last = 0; + } + if (ford_mach_e_extended && !tx) { + // External path/announcement checks must not retain a rejected command. + curvature_state.desired_last = 0; + ford_mach_e_path_angle_last = 0; + } + if (ford_mach_e_extended && tx) { + ford_mach_e_path_angle_last = desired_path_angle; } } + if (ford_bp_enabled) { + if (msg->addr == FORD_Lane_Assist_Data1) { tx &= ford_bp_lka(msg); } + if ((msg->addr == FORD_LateralMotionControl) || (msg->addr == FORD_LateralMotionControl2)) { tx &= ford_bp_lateral(msg); } + } + ford_aol_tx(msg, tx); return tx; } +static void ford_aol_bind_tx(safety_config *ret, CanMsg workspace[7]) { + const bool bounded = (ret->tx_msgs != NULL) && (ret->tx_msgs_len > 0) && (ret->tx_msgs_len <= 7); + if (bounded) { + for (int i = 0; i < ret->tx_msgs_len; i++) { + workspace[i] = ret->tx_msgs[i]; + const unsigned int addr = workspace[i].addr; + if ((addr == ford_aol_replacement()) || (addr == 0x3D8U) || (addr == 0x18AU)) { + workspace[i].disable_static_blocking = true; + } + } + ret->tx_msgs = workspace; + } else { + ret->tx_msgs = NULL; + ret->tx_msgs_len = 0; + ford_aol_reset(); + } +} + static safety_config ford_init(uint16_t param) { // warning: quality flags are not yet checked in openpilot's CAN parser, // this may be the cause of blocked messages - static RxCheck ford_rx_checks[] = { - {.msg = {{FORD_BrakeSysFeatures, 0, 8, 50U, .max_counter = 15U}, { 0 }, { 0 }}}, - // FORD_EngVehicleSpThrottle2 has a counter that either randomly skips or by 2, likely ECU bug - // Some hybrid models also experience a bug where this checksum mismatches for one or two frames under heavy acceleration with ACC - // It has been confirmed that the Bronco Sport's camera only disallows ACC for bad quality flags, not counters or checksums, so we match that - {.msg = {{FORD_EngVehicleSpThrottle2, 0, 8, 50U, .ignore_checksum = true, .ignore_counter = true}, { 0 }, { 0 }}}, - {.msg = {{FORD_Yaw_Data_FD1, 0, 8, 100U, .max_counter = 255U}, { 0 }, { 0 }}}, - // These messages have no counter or checksum - {.msg = {{FORD_EngBrakeData, 0, 8, 10U, .ignore_checksum = true, .ignore_counter = true, .ignore_quality_flag = true}, { 0 }, { 0 }}}, - {.msg = {{FORD_EngVehicleSpThrottle, 0, 8, 100U, .ignore_checksum = true, .ignore_counter = true, .ignore_quality_flag = true}, { 0 }, { 0 }}}, + // Shared entries preserve all current checksum/counter/quality contracts. + #define FORD_COMMON_RX_CHECKS \ + {.msg = {{FORD_BrakeSysFeatures, 0, 8, 50U, .max_counter = 15U}, { 0 }, { 0 }}}, \ + {.msg = {{FORD_EngVehicleSpThrottle2, 0, 8, 50U, .ignore_checksum = true, .ignore_counter = true}, { 0 }, { 0 }}}, \ + {.msg = {{FORD_Yaw_Data_FD1, 0, 8, 100U, .max_counter = 255U}, { 0 }, { 0 }}}, \ + {.msg = {{FORD_EngBrakeData, 0, 8, 10U, .ignore_checksum = true, .ignore_counter = true, .ignore_quality_flag = true}, { 0 }, { 0 }}}, \ + {.msg = {{FORD_EngVehicleSpThrottle, 0, 8, 100U, .ignore_checksum = true, .ignore_counter = true, .ignore_quality_flag = true}, { 0 }, { 0 }}}, \ {.msg = {{FORD_DesiredTorqBrk, 0, 8, 50U, .ignore_checksum = true, .ignore_counter = true, .ignore_quality_flag = true}, { 0 }, { 0 }}}, + static RxCheck ford_rx_checks[] = { FORD_COMMON_RX_CHECKS }; + static RxCheck ford_lka_rx_checks[] = { + FORD_COMMON_RX_CHECKS + {.msg = {{FORD_Lane_Assist_Data3, 0, 8, 30U, .ignore_checksum = true, .ignore_counter = true, .ignore_quality_flag = true}, { 0 }, { 0 }}}, + }; + static RxCheck ford_stock_rx_checks[] = { + FORD_COMMON_RX_CHECKS + {.msg = {{FORD_Steering_Data_FD1, 0, 8, 10U, .ignore_checksum = true, .ignore_counter = true, .ignore_quality_flag = true}, { 0 }, { 0 }}}, + }; + static RxCheck ford_stock_lka_rx_checks[] = { + FORD_COMMON_RX_CHECKS + {.msg = {{FORD_Lane_Assist_Data3, 0, 8, 30U, .ignore_checksum = true, .ignore_counter = true, .ignore_quality_flag = true}, { 0 }, { 0 }}}, + {.msg = {{FORD_Steering_Data_FD1, 0, 8, 10U, .ignore_checksum = true, .ignore_counter = true, .ignore_quality_flag = true}, { 0 }, { 0 }}}, }; #define FORD_COMMON_TX_MSGS \ @@ -306,9 +550,55 @@ static safety_config ford_init(uint16_t param) { {FORD_ACCDATA, 0, 8, .check_relay = true}, {FORD_LateralMotionControl, 0, 8, .check_relay = true}, }; + static const CanMsg FORD_STOCK_TX_MSGS[] = { + FORD_COMMON_TX_MSGS + {FORD_LateralMotionControl, 0, 8, .check_relay = true}, + }; const uint16_t FORD_PARAM_CANFD = 2; + const uint16_t FORD_PARAM_LKA_STEERING = 4; + const uint16_t FORD_PARAM_NEW_PORT = 8; + const uint16_t FORD_PARAM_MACH_E_EXTENDED = 16U; + const uint16_t FORD_PARAM_EXPLORER_EXTENDED = 32U; + const uint16_t FORD_PARAM_GENERIC_CANFD_EXTENDED = 64U; + const bool generic_canfd_namespace = GET_FLAG(param, FORD_PARAM_GENERIC_CANFD_EXTENDED); + ford_generic_canfd_extended = (param == 66U) && (((unsigned int)alternative_experience == 0U) || (((unsigned int)alternative_experience == 32U) && ford_aol_param_valid(param))); +#ifdef ALLOW_DEBUG + ford_generic_canfd_extended |= (param == 67U) && (((unsigned int)alternative_experience == 0U) || (((unsigned int)alternative_experience == 32U) && ford_aol_param_valid(param))); +#endif + ford_generic_canfd_announced = false; + const bool explorer_namespace = GET_FLAG(param, FORD_PARAM_EXPLORER_EXTENDED); + ford_explorer_extended = ((param == 32U) || (param == 33U)) && + (((unsigned int)alternative_experience == 0U) || (((unsigned int)alternative_experience == 32U) && ford_aol_param_valid(param))); + ford_explorer_announced = false; + const bool mach_e_namespace = GET_FLAG(param, FORD_PARAM_MACH_E_EXTENDED); + ford_mach_e_extended = (param == 18U) && (((unsigned int)alternative_experience == 0U) || (((unsigned int)alternative_experience == 32U) && ford_aol_param_valid(param))); +#ifdef ALLOW_DEBUG + ford_mach_e_extended |= (param == 19U) && (((unsigned int)alternative_experience == 0U) || (((unsigned int)alternative_experience == 32U) && ford_aol_param_valid(param))); +#endif + const bool bp_config_valid = ford_bp_configure(param); + ford_stock_switch = ((((unsigned int)alternative_experience == 0U) || (((unsigned int)alternative_experience == 32U) && ford_aol_param_valid(param))) && + ((param == 2U) || (param == 8U) || (param == 10U) || (param == 12U) || + ((param == 18U) && ford_mach_e_extended) || + ((param == 32U) && ford_explorer_extended) || + ((param == 66U) && ford_generic_canfd_extended))) || + (ford_bp_enabled && ((param & 1U) == 0U)); + ford_cancel_resume_button = false; + ford_mach_e_path_angle_last = 0; + ford_mach_e_announced = false; const bool ford_canfd = GET_FLAG(param, FORD_PARAM_CANFD); + ford_lka_steering = GET_FLAG(param, FORD_PARAM_LKA_STEERING); + const bool ford_new_port = GET_FLAG(param, FORD_PARAM_NEW_PORT); + ford_lka_available = false; + ford_lka_last_us = 0U; + ford_lka_speed_last_us = 0U; + ford_lka_speed2_last_us = 0U; + ford_lka_yaw_last_us = 0U; + ford_lka_speed_seen = false; + ford_lka_speed2_seen = false; + ford_lka_yaw_seen = false; + ford_lka_curvature_state = (CurvatureSteeringState){0}; + ford_lka_angle_last = 2048; safety_config ret; if (ford_canfd) { @@ -320,12 +610,102 @@ static safety_config ford_init(uint16_t param) { } #endif } else { - ret = BUILD_SAFETY_CFG(ford_rx_checks, FORD_LONG_TX_MSGS); + ret = ford_new_port ? BUILD_SAFETY_CFG(ford_rx_checks, FORD_STOCK_TX_MSGS) : + BUILD_SAFETY_CFG(ford_rx_checks, FORD_LONG_TX_MSGS); + if (ford_lka_steering) { + SET_RX_CHECKS(ford_lka_rx_checks, ret); + } + if (ford_new_port && GET_FLAG(param, 1U)) { + SET_TX_MSGS(FORD_LONG_TX_MSGS, ret); + } + } + if (ford_explorer_extended && (param == 32U)) { + SET_TX_MSGS(FORD_STOCK_TX_MSGS, ret); + } + if (ford_bp_enabled && (param == 128U)) { SET_TX_MSGS(FORD_STOCK_TX_MSGS, ret); } + if (ford_stock_switch) { + if (ford_lka_steering) { + SET_RX_CHECKS(ford_stock_lka_rx_checks, ret); + } else { + SET_RX_CHECKS(ford_stock_rx_checks, ret); + } + } + if (!bp_config_valid || (mach_e_namespace && !ford_mach_e_extended) || + (explorer_namespace && !ford_explorer_extended) || + (generic_canfd_namespace && !ford_generic_canfd_extended)) { + ret.tx_msgs = NULL; + ret.tx_msgs_len = 0; + } + ford_aol_configure(param); + if (ford_aol_enabled) { + static const RxCheck ford_aol_default_rx[] = { + FORD_COMMON_RX_CHECKS + {.msg = {{0x83, 0, 8, 10U, .ignore_checksum = true, .ignore_counter = true, .ignore_quality_flag = true}, {0}, {0}}}, + {.msg = {{0x82, 0, 8, 50U, .ignore_checksum = true, .ignore_counter = true, .ignore_quality_flag = true}, {0}, {0}}}, + {.msg = {{0x176, 0, 8, 10U, .ignore_checksum = true, .ignore_counter = true, .ignore_quality_flag = true}, {0}, {0}}}, + }; + static const RxCheck ford_aol_edge_rx[] = { + FORD_COMMON_RX_CHECKS + {.msg = {{0x83, 0, 8, 10U, .ignore_checksum = true, .ignore_counter = true, .ignore_quality_flag = true}, {0}, {0}}}, + {.msg = {{0x82, 0, 8, 50U, .ignore_checksum = true, .ignore_counter = true, .ignore_quality_flag = true}, {0}, {0}}}, + {.msg = {{0x230, 0, 8, 10U, .ignore_checksum = true, .ignore_counter = true, .ignore_quality_flag = true}, {0}, {0}}}, + }; + static const RxCheck ford_aol_mondeo_rx[] = { + FORD_COMMON_RX_CHECKS + {.msg = {{FORD_Lane_Assist_Data3, 0, 8, 30U, .ignore_checksum = true, .ignore_counter = true, .ignore_quality_flag = true}, {0}, {0}}}, + {.msg = {{0x83, 0, 8, 10U, .ignore_checksum = true, .ignore_counter = true, .ignore_quality_flag = true}, {0}, {0}}}, + {.msg = {{0x82, 0, 8, 50U, .ignore_checksum = true, .ignore_counter = true, .ignore_quality_flag = true}, {0}, {0}}}, + {.msg = {{0x5A, 0, 8, 10U, .ignore_checksum = true, .ignore_counter = true, .ignore_quality_flag = true}, {0}, {0}}}, + }; + static const RxCheck ford_aol_transit_rx[] = { + FORD_COMMON_RX_CHECKS + {.msg = {{0x83, 0, 8, 10U, .ignore_checksum = true, .ignore_counter = true, .ignore_quality_flag = true}, {0}, {0}}}, + {.msg = {{0x82, 0, 8, 50U, .ignore_checksum = true, .ignore_counter = true, .ignore_quality_flag = true}, {0}, {0}}}, + {.msg = {{0x176, 0, 8, 10U, .ignore_checksum = true, .ignore_counter = true, .ignore_quality_flag = true}, {0}, {0}}}, + {.msg = {{FORD_Lane_Assist_Data3, 0, 8, 30U, .ignore_checksum = true, .ignore_counter = true, .ignore_quality_flag = true}, {0}, {0}}}, + }; + static RxCheck ford_aol_rx_workspace[10]; + _Static_assert(sizeof(ford_aol_default_rx) == (9U * sizeof(RxCheck)), "Ford default RX count"); + _Static_assert(sizeof(ford_aol_edge_rx) == (9U * sizeof(RxCheck)), "Ford Edge RX count"); + _Static_assert(sizeof(ford_aol_mondeo_rx) == (10U * sizeof(RxCheck)), "Ford Mondeo RX count"); + _Static_assert(sizeof(ford_aol_transit_rx) == (10U * sizeof(RxCheck)), "Ford Transit RX count"); + const uint16_t base = param & 0xFFFEU; + const RxCheck *selected_rx = ford_aol_default_rx; + int selected_len = 9; + if (base == 8U) { + selected_rx = ford_aol_edge_rx; + } else if (base == 10U) { + selected_rx = ford_aol_mondeo_rx; + selected_len = 10; + } else if ((base == 12U) || (base == 18U) || (base == 66U)) { + selected_rx = ford_aol_transit_rx; + selected_len = 10; + } else { + } + for (int i = 0; i < 10; i++) { + if (i < selected_len) { + ford_aol_rx_workspace[i] = selected_rx[i]; + } else { + ford_aol_rx_workspace[i] = (RxCheck){0}; + } + } + ret.rx_checks = ford_aol_rx_workspace; + ret.rx_checks_len = selected_len; + ret.disable_forwarding = false; + static CanMsg ford_aol_tx_msgs[7]; + _Static_assert(sizeof(FORD_CANFD_STOCK_TX_MSGS) <= sizeof(ford_aol_tx_msgs), "Ford CAN FD stock TX capacity"); + _Static_assert(sizeof(FORD_STOCK_TX_MSGS) <= sizeof(ford_aol_tx_msgs), "Ford stock TX capacity"); + _Static_assert(sizeof(FORD_LONG_TX_MSGS) <= sizeof(ford_aol_tx_msgs), "Ford long TX capacity"); +#ifdef ALLOW_DEBUG + _Static_assert(sizeof(FORD_CANFD_LONG_TX_MSGS) <= sizeof(ford_aol_tx_msgs), "Ford CAN FD long TX capacity"); +#endif + ford_aol_bind_tx(&ret, ford_aol_tx_msgs); } return ret; } const safety_hooks ford_hooks = { + .fwd = ford_aol_fwd, .init = ford_init, .rx = ford_rx_hook, .tx = ford_tx_hook, diff --git a/opendbc_repo/opendbc/safety/modes/ford_aol.h b/opendbc_repo/opendbc/safety/modes/ford_aol.h new file mode 100644 index 0000000000..03d5e961f0 --- /dev/null +++ b/opendbc_repo/opendbc/safety/modes/ford_aol.h @@ -0,0 +1,192 @@ +#pragma once + +static bool ford_aol_enabled = false; +static bool ford_aol_token = false; +static bool ford_aol_main_available = false; +static bool ford_aol_token_claimed = false; +static uint32_t ford_aol_token_ts = 0U; +static bool ford_aol_main_neutral = false; +static bool ford_aol_main_previous = false; +static bool ford_aol_button_neutral = false; +static bool ford_aol_button_previous = false; +static bool ford_aol_session = false; +static bool ford_aol_request_seen = false; +static uint16_t ford_aol_param = 0U; +static bool ford_aol_drive = false; +static uint8_t ford_aol_eps = 0U; +static bool ford_aol_lka_ready = false; +static bool ford_aol_owned = false; +static uint32_t ford_aol_accepted_ts = 0U; + +static void ford_aol_clear(void) { + ford_aol_token = false; + ford_aol_token_claimed = false; + ford_aol_token_ts = 0U; + ford_aol_main_neutral = false; + ford_aol_button_neutral = false; + ford_aol_owned = false; +} + +static void ford_aol_reset(void) { + ford_aol_clear(); + ford_aol_enabled = false; + ford_aol_main_available = false; + ford_aol_main_previous = false; + ford_aol_button_previous = false; + ford_aol_session = false; + ford_aol_request_seen = false; + ford_aol_param = 0U; + ford_aol_drive = false; + ford_aol_eps = 0U; + ford_aol_lka_ready = false; + ford_aol_accepted_ts = 0U; +} + +static void ford_aol_host_request(uint8_t mask) { + ford_aol_request_seen |= mask != 0U; +} + +static uint8_t ford_aol_request_mask(void) { + uint8_t result = 0U; + const bool expired = ford_aol_request_seen && + (safety_get_ts_elapsed(microsecond_timer_get(), aol_host_request_ts) > AOL_HOST_REQUEST_TIMEOUT_US); + const bool token_expired = ford_aol_token && !ford_aol_token_claimed && + (safety_get_ts_elapsed(microsecond_timer_get(), ford_aol_token_ts) > AOL_HOST_REQUEST_TIMEOUT_US); + if (!aol_rx_healthy() || relay_malfunction || expired || token_expired || (ford_aol_session && !heartbeat_engaged)) { + ford_aol_clear(); + } else if (heartbeat_engaged) { + ford_aol_session = true; + result = aol_host_axis_mask & 1U; + if ((result != 0U) && ford_aol_token) { + ford_aol_token_claimed = true; + } + } else { + } + return result; +} + +static uint8_t ford_aol_permission_mask(void) { + uint8_t result = 0U; + if (ford_aol_eps >= 2U) { + ford_aol_clear(); + } + const uint16_t base = ford_aol_param & 0xFFFEU; + const bool needs_lka = (base == 10U) || (base == 12U) || (base == 18U) || (base == 66U); + if ((ford_aol_request_mask() != 0U) && (controls_allowed || ford_aol_token) && + ford_aol_main_available && ford_aol_drive && (ford_aol_eps == 0U) && (!needs_lka || ford_aol_lka_ready)) { + result = 1U; + } + return result; +} + +static void ford_aol_rx(const CANPacket_t *msg) { + if (ford_aol_enabled && (msg->bus == 0U)) { + if (msg_matches(msg, 0x165U, 0U, 8U)) { + const unsigned int state = msg->data[1] & 7U; + const bool main_available = (state == 3U) || (state == 4U) || (state == 5U); + ford_aol_main_available = main_available; + if (!main_available) { + ford_aol_clear(); + ford_aol_main_neutral = true; + } else if (ford_aol_main_neutral && !ford_aol_main_previous && (aol_host_axis_mask == 0U)) { + ford_aol_token = true; + ford_aol_token_claimed = false; + ford_aol_token_ts = microsecond_timer_get(); + } else { + } + ford_aol_main_previous = main_available; + if ((state == 1U) || (state == 2U)) { + ford_aol_clear(); + } + } else if (msg_matches(msg, 0x83U, 0U, 8U)) { + const bool button = GET_BIT(msg, 40U); + if (!button) { + ford_aol_button_neutral = true; + } else if (ford_aol_button_neutral && !ford_aol_button_previous && (aol_host_axis_mask == 0U)) { + ford_aol_token = true; + ford_aol_token_claimed = false; + ford_aol_token_ts = microsecond_timer_get(); + } else { + } + ford_aol_button_previous = button; + if (GET_BIT(msg, 8U) || GET_BIT(msg, 24U)) { + ford_aol_clear(); + } + } else if (msg_matches(msg, 0x82U, 0U, 8U)) { + ford_aol_eps = msg->data[1] & 3U; + if (ford_aol_eps >= 2U) { + ford_aol_clear(); + } + } else if (msg_matches(msg, 0x3CCU, 0U, 8U)) { + const unsigned int state = msg->data[2] & 7U; + ford_aol_lka_ready = ((ford_aol_param & 0xFFFEU) == 12U) ? + ((((msg->data[0] >> 4U) & 3U) == 3U) && ((msg->data[0] & 0x40U) == 0U)) : + ((state == 1U) || (state == 2U) || (state == 3U)); + } else { + const uint16_t base = ford_aol_param & 0xFFFEU; + const uint16_t gear_addr = (base == 8U) ? 0x230U : ((base == 10U) ? 0x5AU : 0x176U); + if (msg_matches(msg, gear_addr, 0U, 8U)) { + const unsigned int gear = (base == 8U) ? ((msg->data[1] >> 1U) & 15U) : + ((base == 10U) ? (msg->data[6] & 15U) : (msg->data[3] & 15U)); + ford_aol_drive = (gear == 3U) || (gear == 4U) || (gear == 5U); + } + } + } +} + +static bool ford_aol_param_valid(uint16_t param) { + bool result = false; + switch (param) { + case 8U: case 9U: case 10U: case 12U: case 13U: case 18U: case 32U: case 33U: case 66U: + result = true; + break; +#ifdef ALLOW_DEBUG + case 11U: case 19U: case 67U: + result = true; + break; +#endif + default: + break; + } + return result; +} + +static void ford_aol_configure(uint16_t param) { + ford_aol_reset(); + ford_aol_enabled = ford_aol_param_valid(param) && ((unsigned int)alternative_experience == 32U); + ford_aol_param = param; + if (ford_aol_enabled) { + static const AolSafetyPolicy policy = { + .reset = ford_aol_reset, + .host_request = ford_aol_host_request, + .request_mask = ford_aol_request_mask, + .permission_mask = ford_aol_permission_mask, + .rx_invalid = ford_aol_clear, + }; + aol_policy = &policy; + } +} + +static unsigned int ford_aol_replacement(void) { + const uint16_t base = ford_aol_param & 0xFFFEU; + return (base == 12U) ? 0x3CAU : (((base == 10U) || (base == 18U) || (base == 66U)) ? 0x3D6U : 0x3D3U); +} + +static void ford_aol_tx(const CANPacket_t *msg, bool accepted) { + if (ford_aol_enabled && (msg->bus == 0U) && (msg->addr == ford_aol_replacement())) { + const bool active = (msg->addr == 0x3CAU) ? (((msg->data[0] >> 5U) == 2U) || ((msg->data[0] >> 5U) == 4U)) : + ((msg->addr == 0x3D3U) ? (((msg->data[4] >> 2U) & 7U) != 0U) : + (((msg->data[0] >> 4U) & 7U) != 0U)); + ford_aol_owned = accepted && active && (ford_aol_permission_mask() != 0U) && !relay_malfunction; + ford_aol_accepted_ts = microsecond_timer_get(); + } +} + +static bool ford_aol_fwd(int bus, int addr) { + bool blocked = false; + if (ford_aol_enabled && (bus == 2) && ford_aol_owned && (ford_aol_permission_mask() != 0U) && + (safety_get_ts_elapsed(microsecond_timer_get(), ford_aol_accepted_ts) <= AOL_HOST_REQUEST_TIMEOUT_US)) { + blocked = (addr == (int)ford_aol_replacement()) || (addr == 0x3D8) || (addr == 0x18A); + } + return blocked; +} diff --git a/opendbc_repo/opendbc/safety/tests/test_ford_aol.py b/opendbc_repo/opendbc/safety/tests/test_ford_aol.py new file mode 100644 index 0000000000..4f73b890d5 --- /dev/null +++ b/opendbc_repo/opendbc/safety/tests/test_ford_aol.py @@ -0,0 +1,262 @@ +import os +import resource +import signal +import time +import unittest + +from opendbc.car import structs +from opendbc.safety.tests.libsafety import libsafety_py + + +class TestFordAolAdmission(unittest.TestCase): + def setUp(self): + self.safety = libsafety_py.libsafety + + def tearDown(self): + self.safety.set_alternative_experience(0) + self.safety.set_safety_hooks(structs.CarParams.SafetyModel.noOutput, 0) + + def test_no_frames_no_lateral_or_longitudinal_authority(self): + for word in (8, 9, 10, 11, 12, 13, 18, 19, 32, 33, 66, 67): + for ae in (0, 32, 33): + with self.subTest(word=word, ae=ae): + self.safety.init_tests() + self.safety.set_alternative_experience(ae) + self.safety.set_safety_hooks(structs.CarParams.SafetyModel.ford, word) + self.safety.set_timer(1_000_000) + self.safety.set_aol_test_heartbeat(True) + for mask in (0, 1, 2, 3): + self.safety.aol_set_host_request(mask) + self.assertEqual(self.safety.aol_get_permission_mask(), 0) + + +class TestFordAolDriverIntent(unittest.TestCase): + PROFILES = (32, 8, 10, 12, 18, 66) + + def setUp(self): + from opendbc.can import CANPacker + self.safety = libsafety_py.libsafety + self.packer = CANPacker('ford_lincoln_base_pt') + + def tearDown(self): + self.safety.set_alternative_experience(0) + self.safety.set_safety_hooks(structs.CarParams.SafetyModel.noOutput, 0) + + def reset(self, word): + self.word = word + self.tick = 0 + self.safety.init_tests() + self.safety.set_alternative_experience(32) + self.assertEqual(self.safety.set_safety_hooks(structs.CarParams.SafetyModel.ford, word), 0) + self.safety.set_aol_test_heartbeat(True) + + def rx(self, name, values): + self.assertLessEqual(set(values), set(self.packer.dbc.name_to_msg[name].sigs)) + address, data, bus = self.packer.make_can_msg(name, 0, values) + self.assertTrue(self.safety.safety_rx_hook(libsafety_py.make_CANPacket(address, bus, data))) + + def pump(self, count, *, main=3, tja=False, gear=3, eps=0, mask=0, heartbeat=True, speed=10., curvature=0.): + gear_name, gear_signal = ('TransGearData', 'GearLvrPos_D_Actl') if self.word == 8 else ( + ('Gear_Shift_by_Wire_FD1', 'TrnRng_D_RqGsm') if self.word == 10 else ('PowertrainData_10', 'TrnRng_D_Rq')) + for _ in range(count): + self.tick += 1 + self.safety.set_timer(1_000_000 + self.tick * 10_000) + self.safety.set_aol_test_heartbeat(heartbeat) + values = ( + ('BrakeSysFeatures', 50, {'Veh_V_ActlBrk': speed * 3.6, 'VehVActlBrk_D_Qf': 3, 'VehVActlBrk_No_Cnt': (self.tick // 2) % 16}), + ('EngVehicleSpThrottle2', 50, {'Veh_V_ActlEng': speed * 3.6, 'VehVActlEng_D_Qf': 3}), + ('Yaw_Data_FD1', 100, {'VehYaw_W_Actl': curvature * speed, 'VehYawWActl_D_Qf': 3, 'VehRollYaw_No_Cnt': self.tick % 256}), + ('EngBrakeData', 10, {'BpedDrvAppl_D_Actl': 1, 'CcStat_D_Actl': main}), + ('EngVehicleSpThrottle', 100, {'ApedPos_Pc_ActlArb': 0}), + ('DesiredTorqBrk', 50, {'VehStop_D_Stat': 0}), + ('Steering_Data_FD1', 10, {'TjaButtnOnOffPress': int(tja)}), + ('EPAS_INFO', 50, {'SteeringColumnTorque': 0, 'EPAS_Failure': eps}), + (gear_name, 10, {gear_signal: gear}), + ) + for name, hz, fields in values: + if self.tick * hz // 100 != (self.tick - 1) * hz // 100: + self.rx(name, fields) + if (self.word & ~1) in (10, 12, 18, 66) and self.tick * 30 // 100 != (self.tick - 1) * 30 // 100: + self.rx('Lane_Assist_Data3_FD1', {'LatCtlSte_D_Stat': 1, 'LaActAvail_D_Actl': 3, 'LaActDeny_B_Actl': 0}) + self.safety.aol_set_host_request(mask) + self.safety.aol_get_permission_mask() + + def arm(self): + self.pump(40, main=0) + self.pump(10) + self.safety.aol_set_host_request(1) + self.assertEqual(self.safety.aol_get_permission_mask(), 1) + self.assertFalse(self.safety.get_controls_allowed()) + + def rearm(self): + self.pump(20) + self.pump(10, tja=True) + self.safety.aol_set_host_request(1) + self.assertEqual(self.safety.aol_get_permission_mask(), 1) + + def test_permanent_eps_then_clean_in_same_batch_revokes(self): + for word in self.PROFILES: + with self.subTest(word=word): + self.reset(word) + self.arm() + self.rx('EPAS_INFO', {'SteeringColumnTorque': 0, 'EPAS_Failure': 2}) + self.rx('EPAS_INFO', {'SteeringColumnTorque': 0, 'EPAS_Failure': 0}) + self.assertEqual(self.safety.aol_get_permission_mask(), 0) + self.pump(30, mask=1) + self.assertEqual(self.safety.aol_get_permission_mask(), 0) + self.rearm() + + def test_reverse_temporary_eps_retain_but_heartbeat_loss_rearms(self): + for word in self.PROFILES: + with self.subTest(word=word): + self.reset(word) + self.arm() + self.pump(30, gear=1) + self.assertEqual(self.safety.aol_get_permission_mask(), 0) + self.pump(20, mask=1) + self.assertEqual(self.safety.aol_get_permission_mask(), 1) + self.pump(30, eps=1) + self.assertEqual(self.safety.aol_get_permission_mask(), 0) + self.pump(20, mask=1) + self.assertEqual(self.safety.aol_get_permission_mask(), 1) + self.pump(30, gear=1, heartbeat=False) + self.pump(20, mask=1) + self.assertEqual(self.safety.aol_get_permission_mask(), 0) + self.rearm() + + def test_profile_switches_require_fresh_complete_selected_rx_inventory(self): + from opendbc.can import CANPacker + + packer = CANPacker("ford_lincoln_base_pt") + self.safety.init_tests() + self.safety.set_alternative_experience(32) + profiles = ((32, "PowertrainData_10", "TrnRng_D_Rq", False), + (8, "TransGearData", "GearLvrPos_D_Actl", False), + (10, "Gear_Shift_by_Wire_FD1", "TrnRng_D_RqGsm", True), + (12, "PowertrainData_10", "TrnRng_D_Rq", True), + (18, "PowertrainData_10", "TrnRng_D_Rq", True), + (66, "PowertrainData_10", "TrnRng_D_Rq", True), + (8, "TransGearData", "GearLvrPos_D_Actl", False), + (32, "PowertrainData_10", "TrnRng_D_Rq", False)) + for epoch, (word, gear_name, gear_signal, needs_lka) in enumerate(profiles): + with self.subTest(word=word, epoch=epoch): + self.assertEqual(self.safety.set_safety_hooks(structs.CarParams.SafetyModel.ford, word), 0) + self.assertFalse(self.safety.safety_config_valid()) + self.assertEqual(self.safety.aol_get_permission_mask(), 0) + for count in range(6): + self.safety.set_timer(1_000_000 + epoch * 100_000 + count * 10_000) + sources = ( + ("BrakeSysFeatures", {"Veh_V_ActlBrk": 36, "VehVActlBrk_D_Qf": 3, "VehVActlBrk_No_Cnt": count}), + ("EngVehicleSpThrottle2", {"Veh_V_ActlEng": 36, "VehVActlEng_D_Qf": 3}), + ("Yaw_Data_FD1", {"VehYaw_W_Actl": 0, "VehYawWActl_D_Qf": 3, "VehRollYaw_No_Cnt": count}), + ("EngBrakeData", {"BpedDrvAppl_D_Actl": 1, "CcStat_D_Actl": 3}), + ("EngVehicleSpThrottle", {"ApedPos_Pc_ActlArb": 0}), + ("DesiredTorqBrk", {"VehStop_D_Stat": 0}), + ("Steering_Data_FD1", {"TjaButtnOnOffPress": 0}), + ("EPAS_INFO", {"SteeringColumnTorque": 0, "EPAS_Failure": 0}), + (gear_name, {gear_signal: 3}), + ) + if needs_lka: + sources += (("Lane_Assist_Data3_FD1", {"LaActAvail_D_Actl": 3, "LaActDeny_B_Actl": 0, "LatCtlSte_D_Stat": 1}),) + for name, values in sources: + frame = packer.make_can_msg(name, 0, values) + self.assertTrue(self.safety.safety_rx_hook(libsafety_py.make_CANPacket(frame[0], frame[2], frame[1])), name) + self.assertTrue(self.safety.safety_config_valid()) + self.assertEqual(self.safety.aol_get_permission_mask(), 0) + + def test_permanent_eps_is_denied_before_any_clean_replacement(self): + for word in self.PROFILES: + with self.subTest(word=word): + self.reset(word) + self.arm() + self.rx('EPAS_INFO', {'SteeringColumnTorque': 0, 'EPAS_Failure': 2}) + self.assertEqual(self.safety.aol_get_permission_mask(), 0) + self.pump(30, mask=1) + self.assertEqual(self.safety.aol_get_permission_mask(), 0) + self.rearm() + + def test_main_cancel_states_and_physical_cancel_buttons_withdraw(self): + for state in (1, 2): + self.reset(32) + self.arm() + self.pump(10, main=state, mask=1) + self.assertEqual(self.safety.aol_get_permission_mask(), 0) + for bit in (8, 24): + self.reset(32) + self.arm() + data = (1 << bit).to_bytes(8, 'little') + self.assertTrue(self.safety.safety_rx_hook(libsafety_py.make_CANPacket(0x83, 0, data))) + self.assertEqual(self.safety.aol_get_permission_mask(), 0) + self.pump(20, mask=1) + self.assertEqual(self.safety.aol_get_permission_mask(), 0) + self.rearm() + + def test_accepted_lateral_owns_only_replacement_until_lease_or_rejection(self): + from opendbc.car.ford.fordcan import CanBus, create_lat_ctl_msg + from opendbc.car.ford.mache_can import create_lka_msg + from opendbc.car import gen_empty_fingerprint + self.reset(32) + self.arm() + bus = CanBus(fingerprint=gen_empty_fingerprint()) + frame = create_lat_ctl_msg(self.packer, bus, True, 0., 0., 0., 0.) + command = libsafety_py.make_CANPacket(frame[0], frame[2], frame[1]) + self.assertEqual(self.safety.safety_fwd_hook(2, 0x3D3), 0) + self.assertFalse(self.safety.safety_tx_hook(command)) + announcement = create_lka_msg(self.packer, bus) + self.assertTrue(self.safety.safety_tx_hook(libsafety_py.make_CANPacket(announcement[0], announcement[2], announcement[1]))) + self.assertEqual(self.safety.safety_fwd_hook(2, 0x3D3), 0) + self.assertTrue(self.safety.safety_tx_hook(command)) + for address in (0x3D3, 0x3D8, 0x18A): + self.assertEqual(self.safety.safety_fwd_hook(2, address), -1) + self.assertEqual(self.safety.safety_fwd_hook(2, 0x321), 0) + self.pump(31, mask=1) + self.assertEqual(self.safety.aol_get_permission_mask(), 1) + for address in (0x3D3, 0x3D8, 0x18A): + self.assertEqual(self.safety.safety_fwd_hook(2, address), 0) + + def test_native_bounded_catalog_copy_denies_invalid_and_restores_registered_table(self): + for length, null_catalog in ((0, False), (1, False), (7, False), (8, False), (1, True)): + with self.subTest(length=length, null_catalog=null_catalog): + self.reset(32) + self.assertTrue(self.bounded_catalog_contract(length, null_catalog)) + self.assertFalse(self.safety.get_controls_allowed()) + self.assertEqual(self.safety.aol_get_permission_mask(), 0) + self.arm() + + def bounded_catalog_contract(self, length, null_catalog): + # Coverage uses the direct callback. Mutants use the identical native inputs + # in a child so a broken pointer/bounds guard becomes a unittest assertion. + if not hasattr(self.safety, 'mutation_set_active_mutant'): + return self.safety.safety_test_ford_aol_tx_bounds(length, null_catalog) + reader, writer = os.pipe() + child = os.fork() + if child == 0: + os.close(reader) + resource.setrlimit(resource.RLIMIT_CORE, (0, 0)) + try: + result = self.safety.safety_test_ford_aol_tx_bounds(length, null_catalog) + os.write(writer, bytes([int(bool(result))])) + os._exit(0) + except BaseException: + os._exit(2) + os.close(writer) + reaped = False + try: + deadline = time.monotonic() + 5. + while time.monotonic() < deadline: + finished, status = os.waitpid(child, os.WNOHANG) + if finished: + reaped = True + break + time.sleep(.001) + if not reaped: + self.fail('native catalog contract exceeded its five-second deadline') + self.assertTrue(os.WIFEXITED(status), f'native catalog contract failed with wait status {status}') + self.assertEqual(os.WEXITSTATUS(status), 0) + self.assertEqual(os.read(reader, 1), bytes([1])) + return True + finally: + if not reaped: + os.kill(child, signal.SIGKILL) + os.waitpid(child, 0) + os.close(reader) diff --git a/opendbc_repo/opendbc/safety/tests/test_ford_explorer_extended.py b/opendbc_repo/opendbc/safety/tests/test_ford_explorer_extended.py new file mode 100644 index 0000000000..e3f2235d29 --- /dev/null +++ b/opendbc_repo/opendbc/safety/tests/test_ford_explorer_extended.py @@ -0,0 +1,102 @@ +"""Exact Explorer classic extension intersects original and modern limits.""" +from opendbc.car.structs import CarParams +from opendbc.safety.tests.libsafety import libsafety_py +import unittest +from opendbc.safety.tests import test_ford as ford +from opendbc.safety.tests import test_ford_stock_switch as stock + + +class TestFordExplorerExtended(unittest.TestCase): + + def setUp(self): + libsafety_py.libsafety.set_alternative_experience(0) + self.fixture = ford.TestFordLongitudinalSafety() + self.fixture.SAFETY_PARAM = 32 + self.fixture.setUp() + + def tearDown(self): + self.safety.set_alternative_experience(0) + self.safety.set_safety_hooks(CarParams.SafetyModel.noOutput, 0) + + def __getattr__(self, name): + fixture = self.__dict__.get('fixture') + if fixture is None: + raise AttributeError(name) + return getattr(fixture, name) + + def select(self, word=32, ae=0): + self.safety.set_alternative_experience(ae) + self.safety.set_safety_hooks(CarParams.SafetyModel.ford, word) + self.safety.set_timer(0) + + def announce(self, active=True, forbidden=False): + msg = self._lkas_command_msg(0) + msg[0].data[4] = (2 if active else 0) | int(forbidden) + return self._tx(msg) + + def prepare(self, speed=5.0): + self._reset_curvature_measurement(0.0, speed) + self._set_prev_desired_angle(0.0) + self.safety.set_controls_allowed(True) + + def test_namespace_and_classic_long_both_variants(self): + for word in (32, 33): + self.select(word) + self.assertTrue(self.announce()) + self.prepare() + self.assertTrue(self._tx(self._lat_ctl_msg(True, 0, 0, 0, 0.0002))) + self.assertEqual(word == 33, self._tx(self._acc_command_msg(self.INACTIVE_GAS, self.INACTIVE_ACCEL, False))) + for word in (32, 33): + self.select(word, 32) + self.assertTrue(self.announce()) + self.assertTrue(self._tx(self._lat_ctl_msg(False, 0, 0, 0, 0))) + for word, ae in ((34, 0), (36, 0), (40, 0), (48, 0), (96, 0), (32, 1), (33, 1)): + self.select(word, ae) + self.assertFalse(self.announce()) + self.assertFalse(self._tx(self._lat_ctl_msg(False, 0, 0, 0, 0))) + + def test_accepted_announcement_and_inactive_fields(self): + self.prepare() + self.assertFalse(self._tx(self._lat_ctl_msg(True, 0, 0, 0, 0.0002))) + self.assertFalse(self.announce(forbidden=True)) + self.prepare() + self.assertFalse(self._tx(self._lat_ctl_msg(True, 0, 0, 0, 0.0002))) + self.assertTrue(self.announce()) + for rate in (-0.001024, 0.00102375): + self.prepare() + self.assertTrue(self._tx(self._lat_ctl_msg(True, 0, 0, 0, rate))) + for offset, angle, curvature, rate in ((0.01, 0, 0, 0), (0, 0.01, 0, 0), (0, 0, 0, 0.0002), (0, 0, 0.001, 0)): + self.prepare() + self.assertFalse(self._tx(self._lat_ctl_msg(False, offset, angle, curvature, rate))) + self.assertTrue(self._tx(self._lat_ctl_msg(False, 0, 0, 0, 0))) + self.assertTrue(self.announce(active=False)) + self.prepare() + self.assertFalse(self._tx(self._lat_ctl_msg(True, 0, 0, 0, 0))) + + def test_modern_jerk_and_original_lookup_intersect(self): + self.assertTrue(self.announce()) + for speed, accepted_can, rejected_can in ((15.0, 40, 70), (26.0, 8, 12)): + self.prepare(speed) + self.assertTrue(self._tx(self._lat_ctl_msg(True, 0, 0, accepted_can / self.DEG_TO_CAN, 0))) + self.prepare(speed) + self.assertFalse(self._tx(self._lat_ctl_msg(True, 0, 0, rejected_can / self.DEG_TO_CAN, 0))) + self.assertEqual(self.safety.get_desired_curvature_last(), 0) + # A follow-up from zero must pass without resetting previous desire. + # Retaining the rejected positive command would make this reversal fail. + self.assertTrue(self._tx(self._lat_ctl_msg(True, 0, 0, -accepted_can / self.DEG_TO_CAN, 0))) + + def cruise(self, state): + return stock.TestFordStockSwitch.cruise(self, state) + + def physical_switch(self, pressed, bus=0): + return stock.TestFordStockSwitch.physical_switch(self, pressed, bus) + + def test_stock_resume_does_not_grant_steering(self): + for word in (32, 33): + self.select(word) + stock.TestFordStockSwitch.healthy(self, word) + self.assertFalse(self.safety.get_controls_allowed()) + self.assertEqual(word == 32, self._tx(self._acc_button_msg(ford.Buttons.RESUME, 0))) + self.assertFalse(self.safety.get_controls_allowed()) + self.assertTrue(self._rx(self.physical_switch(False))) + self.assertFalse(self._tx(self._acc_button_msg(ford.Buttons.RESUME, 0))) diff --git a/opendbc_repo/opendbc/safety/tests/test_ford_generic_canfd_extended.py b/opendbc_repo/opendbc/safety/tests/test_ford_generic_canfd_extended.py new file mode 100644 index 0000000000..46cee64591 --- /dev/null +++ b/opendbc_repo/opendbc/safety/tests/test_ford_generic_canfd_extended.py @@ -0,0 +1,89 @@ +"""Generic CAN FD extension; helpers composed without inheriting other suites.""" +import unittest +from opendbc.car import structs +from opendbc.safety.tests import test_ford as ford +from opendbc.safety.tests.libsafety import libsafety_py + + +class TestFordGenericCanfdExtended(unittest.TestCase): + def setUp(self): + self.safety = libsafety_py.libsafety + self.safety.set_alternative_experience(0) + self.debug = self.safety.set_safety_hooks(structs.CarParams.SafetyModel.allOutput, 0) == 0 + self.fixture = ford.TestFordCANFDLongitudinalSafety() + self.fixture.SAFETY_PARAM = 66 + self.fixture.setUp() + + def __getattr__(self, name): + fixture = self.__dict__.get("fixture") + if fixture is not None: + return getattr(fixture, name) + raise AttributeError(name) + + def tearDown(self): + self.safety.set_alternative_experience(0) + self.safety.set_safety_hooks(structs.CarParams.SafetyModel.noOutput, 0) + + def select(self, word, ae=0): + self.safety.set_alternative_experience(ae) + self.safety.set_safety_hooks(structs.CarParams.SafetyModel.ford, word) + self.safety.init_tests() + self.safety.set_timer(0) + + def announce(self): + msg = self._lkas_command_msg(0) + msg[0].data[4] = 2 + return self._tx(msg) + + def prepare(self, speed=5.): + # Unit-limit setup only; actual caller packet proof uses physical RX instead. + self._reset_curvature_measurement(0., speed) + self._set_prev_desired_angle(0.) + self.safety.set_controls_allowed(True) + + def test_exact_namespace_and_release_long_denial(self): + for word in (66,67): + self.select(word) + admitted = word == 66 or self.debug + self.assertEqual(admitted, self.announce()) + self.prepare() + self.assertEqual(admitted, self._tx(self._lat_ctl_msg(True,0,0,0,.0002))) + self.assertEqual(word == 67 and self.debug, + self._tx(self._acc_command_msg(self.INACTIVE_GAS,self.INACTIVE_ACCEL,False))) + for word, ae in ((64,0),(65,0),(68,0),(70,0),(74,0),(82,0),(98,0),(194,0),(66,33),(67,33)): + self.select(word,ae) + self.assertFalse(self.announce()) + self.assertFalse(self._tx(self._lat_ctl_msg(False,0,0,0,0))) + for word in (66, 67): + self.select(word, 32) + self.assertEqual(word == 66 or self.debug, self.announce()) + self.assertFalse(self._tx(self._lat_ctl_msg(True, 0, 0, .0002, 0))) + + def test_announcement_path_and_inactive_contract(self): + self.prepare() + self.assertFalse(self._tx(self._lat_ctl_msg(True,0,0,0,.0002))) + self.assertTrue(self.announce()) + for rate in (-.001024,.001023): + self.prepare() + self.assertTrue(self._tx(self._lat_ctl_msg(True,0,0,0,rate))) + for offset,angle,curvature,rate in ((.01,0,0,0),(0,.01,0,0),(0,0,.001,0),(0,0,0,.0002)): + self.prepare() + self.assertTrue(self._tx(self._lat_ctl_msg(True,0,0,.0002,0))) + self.assertEqual(10,self.safety.get_desired_curvature_last()) + self.assertFalse(self._tx(self._lat_ctl_msg(False,offset,angle,curvature,rate))) + self.assertEqual(0,self.safety.get_desired_curvature_last()) + self.assertTrue(self._tx(self._lat_ctl_msg(False,0,0,0,0))) + + def test_modern_envelope_and_rejected_history(self): + self.assertTrue(self.announce()) + for speed,accept,reject in ((15.,40,70),(26.,8,12)): + self.prepare(speed) + self.assertTrue(self._tx(self._lat_ctl_msg(True,0,0,accept/self.DEG_TO_CAN,0))) + self.assertEqual(accept,self.safety.get_desired_curvature_last()) + # Keep the accepted previous command for the extension-only path rejection. + self.assertFalse(self._tx(self._lat_ctl_msg(True,0,.01,accept/self.DEG_TO_CAN,0))) + self.assertEqual(0,self.safety.get_desired_curvature_last()) + self.prepare(speed) + self.assertFalse(self._tx(self._lat_ctl_msg(True,0,0,reject/self.DEG_TO_CAN,0))) + self.assertEqual(0,self.safety.get_desired_curvature_last()) + self.assertTrue(self._tx(self._lat_ctl_msg(True,0,0,-accept/self.DEG_TO_CAN,0))) diff --git a/opendbc_repo/opendbc/safety/tests/test_ford_mach_e_extended.py b/opendbc_repo/opendbc/safety/tests/test_ford_mach_e_extended.py new file mode 100644 index 0000000000..55cbf3176f --- /dev/null +++ b/opendbc_repo/opendbc/safety/tests/test_ford_mach_e_extended.py @@ -0,0 +1,195 @@ +"""Exact Mach-E extension intersects current Ford safety; variant-select methods.""" +import unittest + +from opendbc.safety.tests import test_ford as ford +from opendbc.car.structs import CarParams +from opendbc.safety.tests.libsafety import libsafety_py +from opendbc.safety.tests import test_ford_aol + + +class TestFordMachEExtended(unittest.TestCase): + SAFETY_PARAM = 18 + REQUIRES_DEBUG = None + MAX_CURVATURE_ERROR = 0.006 + + def setUp(self): + safety = libsafety_py.libsafety + debug = safety.set_safety_hooks(CarParams.SafetyModel.allOutput, 0) == 0 + safety.set_safety_hooks(CarParams.SafetyModel.noOutput, 0) + safety.set_alternative_experience(0) + if self.REQUIRES_DEBUG is not None and debug != self.REQUIRES_DEBUG: + self.skipTest("This case requires " + ("DEBUG" if self.REQUIRES_DEBUG else "RELEASE") + " safety") + self._message_fixture = ford.TestFordCANFDStockSafety() + self._message_fixture.SAFETY_PARAM = self.SAFETY_PARAM + self._message_fixture.setUp() + + def __getattr__(self, name): + fixture = self.__dict__.get("_message_fixture") + if fixture is None: + raise AttributeError(name) + return getattr(fixture, name) + + def announce(self, active=True, forbidden=False): + msg = self._lkas_command_msg(0) + msg[0].data[4] = (2 if active else 0) | int(forbidden) + return self._tx(msg) + + def prepare(self, speed=5.0, curvature=0.0195): + self._reset_curvature_measurement(curvature, speed) + self._set_prev_desired_angle(curvature) + self.safety.set_controls_allowed(True) + + def command(self, enabled=True, curvature=0.0195, rate=0.0, angle=0.02, offset=0.0, *, increment_timer=True): + return self._lat_ctl_msg(enabled, offset, angle, curvature, rate, increment_timer=increment_timer) + + def test_accepted_announcement_required_rejected_frame_cannot_grant(self): + self.prepare() + self.assertFalse(self._tx(self.command())) + self.assertFalse(self.announce(forbidden=True)) + self.prepare() + self.assertFalse(self._tx(self.command())) + self.assertTrue(self.announce()) + self.prepare() + self.assertTrue(self._tx(self.command())) + self.assertTrue(self.announce(active=False)) + self.prepare() + self.assertFalse(self._tx(self.command())) + + def test_original_path_recipe_and_inactive_fields(self): + self.assertTrue(self.announce()) + self.prepare() + self.assertTrue(self._tx(self.command())) + for kwargs in ({'angle': -0.02}, {'angle': 0.161}, {'angle': 0.08}, {'curvature': 0.0194}, {'offset': 0.01}): + with self.subTest(kwargs=kwargs): + self.prepare() + self.assertFalse(self._tx(self.command(**kwargs))) + self.prepare() + self.assertTrue(self._tx(self.command(enabled=False, curvature=0.0, angle=0.0))) + self.prepare() + self.assertFalse(self._tx(self.command(enabled=False, rate=0.000001, curvature=0.0, angle=0.0))) + + def test_modern_jerk_rejects_original_rate_counterexample(self): + self.assertTrue(self.announce()) + self.prepare(speed=15.0, curvature=0.0) + # Original15m/s lookup permits75CANunits; modernISOjerk permits46. + self.assertFalse(self._tx(self.command(curvature=0.0015, angle=0.0))) + self.prepare(speed=15.0, curvature=0.0) + self.assertTrue(self._tx(self.command(curvature=0.0009, angle=0.0))) + + def test_speed_combined_accel_and_authority_denials(self): + self.assertTrue(self.announce()) + for speed in (2.9, 8.8): + self.prepare(speed=speed) + self.assertFalse(self._tx(self.command())) + self.prepare() + self.assertTrue(self._tx(self.command(angle=0.05))) + self.prepare() + self.assertTrue(self._tx(self.command(angle=0.1))) + self.prepare(speed=8.7) + # 0.0195 * 8.7**2 + 0.12 * 8.7 > 2.5; path delta is only40CAN. + self.assertFalse(self._tx(self.command(angle=0.12))) + self.prepare() + self.safety.set_controls_allowed(False) + self.assertFalse(self._tx(self.command())) + + def test_rejected_path_does_not_commit_curvature_history(self): + self.assertTrue(self.announce()) + self.prepare() + self.assertFalse(self._tx(self.command(curvature=0.0175))) + self._reset_curvature_measurement(0.0, 5.0) + self.safety.set_controls_allowed(True) + # Reset history permits125CAN from zero; a leaked875CAN rejects this step. + self.assertTrue(self._tx(self.command(curvature=0.0025, angle=0.0))) + + def test_namespace_unknown_words_and_siblings_cannot_acquire(self): + for word, ae in ((2, 0), (3, 0), (10, 0), (11, 0), (22, 0), (26, 0), (50, 0), (18, 32)): + with self.subTest(word=word, ae=ae): + self.safety.set_alternative_experience(ae) + self.safety.set_safety_hooks(CarParams.SafetyModel.ford, word) + self.announce() + self.prepare() + self.assertFalse(self._tx(self.command())) + + def test_typed_aol_retains_curvature_without_path_angle(self): + for sign in (-1, 1): + with self.subTest(sign=sign): + self.setUp() + intent = test_ford_aol.TestFordAolDriverIntent() + intent.setUp() + intent.reset(self.SAFETY_PARAM) + intent.arm() + intent.pump(12, mask=1, speed=7.5, curvature=sign * .02) + self.assertTrue(self.safety.safety_config_valid()) + self.assertEqual(self.safety.aol_get_permission_mask(), 1) + self.assertFalse(self.safety.get_controls_allowed()) + self.assertTrue(self.announce()) + self._set_prev_desired_angle(sign * .02) + self.assertFalse(self._tx(self.command(curvature=sign * .02, angle=sign * .055, increment_timer=False))) + self._set_prev_desired_angle(sign * .02) + self.assertTrue(self._tx(self.command(curvature=sign * .02, angle=0., increment_timer=False))) + + def test_accelerator_assist_requires_retained_full_engagement(self): + for sign in (-1, 1): + with self.subTest(sign=sign): + self.setUp() + intent = test_ford_aol.TestFordAolDriverIntent() + intent.setUp() + intent.reset(self.SAFETY_PARAM) + intent.arm() + intent.pump(12, mask=1, speed=7.5, curvature=sign * .02) + self.assertTrue(self.safety.safety_config_valid()) + self.assertEqual(self.safety.aol_get_permission_mask(), 1) + self._set_prev_desired_angle(sign * .02) + self._rx(self._pcm_status_msg(True)) + self.assertTrue(self.announce()) + for gas in (0., 25., 0.): + self._rx(self._user_gas_msg(gas)) + self.assertTrue(self.safety.get_controls_allowed()) + self.assertTrue(self._tx(self.command(curvature=sign * .02, angle=sign * .055, increment_timer=False))) + + # Cruise returning to available revokes full engagement, while typed AOL keeps the lateral axis. + intent.rx('EngBrakeData', {'BpedDrvAppl_D_Actl': 1, 'CcStat_D_Actl': 3}) + self.assertFalse(self.safety.get_controls_allowed()) + self.assertEqual(self.safety.aol_get_permission_mask(), 1) + self.assertFalse(self._tx(self.command(curvature=sign * .02, angle=sign * .055, increment_timer=False))) + self._set_prev_desired_angle(sign * .02) + self.assertTrue(self._tx(self.command(curvature=sign * .02, angle=0., increment_timer=False))) + + self._rx(self._pcm_status_msg(True)) + self._rx(self._user_brake_msg(True)) + self.assertFalse(self.safety.get_controls_allowed()) + self.assertEqual(self.safety.aol_get_permission_mask(), 1) + self.assertFalse(self._tx(self.command(curvature=sign * .02, angle=sign * .055, increment_timer=False))) + self._set_prev_desired_angle(sign * .02) + self.assertTrue(self._tx(self.command(curvature=sign * .02, angle=0., increment_timer=False))) + + +class TestFordMachEDebugLongExtended(TestFordMachEExtended): + SAFETY_PARAM = 19 + REQUIRES_DEBUG = True + + +class TestFordMachELongReleaseDenied(unittest.TestCase): + SAFETY_PARAM = 19 + REQUIRES_DEBUG = False + + def setUp(self): + safety = libsafety_py.libsafety + debug = safety.set_safety_hooks(CarParams.SafetyModel.allOutput, 0) == 0 + safety.set_safety_hooks(CarParams.SafetyModel.noOutput, 0) + safety.set_alternative_experience(0) + if self.REQUIRES_DEBUG is not None and debug != self.REQUIRES_DEBUG: + self.skipTest("This case requires " + ("DEBUG" if self.REQUIRES_DEBUG else "RELEASE") + " safety") + self._message_fixture = ford.TestFordCANFDStockSafety() + self._message_fixture.SAFETY_PARAM = self.SAFETY_PARAM + self._message_fixture.setUp() + + def __getattr__(self, name): + fixture = self.__dict__.get("_message_fixture") + if fixture is None: + raise AttributeError(name) + return getattr(fixture, name) + + def test_long_profile_no_transmit_authority_in_release(self): + self.safety.set_controls_allowed(True) + self.assertFalse(self._tx(self._lat_ctl_msg(True, 0.0, 0.0, 0.0, 0.0))) diff --git a/opendbc_repo/opendbc/safety/tests/test_ford_stock_switch.py b/opendbc_repo/opendbc/safety/tests/test_ford_stock_switch.py new file mode 100644 index 0000000000..326bf33a7e --- /dev/null +++ b/opendbc_repo/opendbc/safety/tests/test_ford_stock_switch.py @@ -0,0 +1,91 @@ +"""Physical stock-resume permission never acquires openpilot steering authority.""" +from opendbc.car.structs import CarParams +from opendbc.safety.tests import common +from opendbc.safety.tests.libsafety import libsafety_py +import unittest + +from opendbc.safety.tests import test_ford as ford + +Buttons = ford.Buttons + + +class TestFordStockSwitch(unittest.TestCase): + SAFETY_PARAM = 2 + def setUp(self): + libsafety_py.libsafety.set_alternative_experience(0) + self._message_fixture = ford.TestFordCANFDStockSafety() + self._message_fixture.SAFETY_PARAM = self.SAFETY_PARAM + self._message_fixture.setUp() + + def __getattr__(self, name): + fixture = self.__dict__.get("_message_fixture") + if fixture is None: + raise AttributeError(name) + return getattr(fixture, name) + + + def select(self, word=2, ae=0): + self.safety.set_alternative_experience(ae) + self.safety.set_safety_hooks(CarParams.SafetyModel.ford, word) + self.safety.set_timer(0) + + def cruise(self, state): + return self.packer.make_can_msg_safety("EngBrakeData", 0, {"CcStat_D_Actl": state, "BpedDrvAppl_D_Actl": 1}) + + def physical_switch(self, pressed, bus=0): + return self.packer.make_can_msg_safety("Steering_Data_FD1", bus, {"CcAslButtnCnclResPress": int(pressed)}) + + def healthy(self, word=2, button=True, main=True): + for _ in range(6): + for msg in (self._speed_msg(5.0), self._speed_msg_2(5.0), self._yaw_rate_msg(0.0, 5.0), + self._user_gas_msg(0.0), self._vehicle_moving_msg(5.0), self.cruise(3 if main else 0)): + self.assertTrue(self._rx(msg)) + if word == 12: + self.assertTrue(self._rx(common.make_msg(0, 0x3CC))) + if button is not None: + self.assertTrue(self._rx(self.physical_switch(button))) + + def test_physical_available_inactive_resume_does_not_enable_controls(self): + for word in (2, 8, 10, 12, 18): + with self.subTest(word=word): + self.select(word) + self.healthy(word) + self.assertFalse(self.safety.get_controls_allowed()) + for bus in (0, 2): + self.assertTrue(self._tx(self._acc_button_msg(Buttons.RESUME, bus))) + self.assertFalse(self._tx(self._acc_button_msg(Buttons.CANCEL, bus))) + self.assertFalse(self.safety.get_controls_allowed()) + self.assertEqual(self.safety.safety_fwd_hook(0, 0x83), 2) + self.assertEqual(self.safety.safety_fwd_hook(2, 0x83), 0) + + def test_release_main_off_missing_and_wrong_bus_deny_resume(self): + for case in ("release", "main_off", "missing", "wrong_bus"): + with self.subTest(case=case): + self.select() + self.healthy(button=None if case in ("missing", "wrong_bus") else True) + if case == "release": + self.assertTrue(self._rx(self.physical_switch(False))) + elif case == "main_off": + self.assertTrue(self._rx(self.cruise(0))) + elif case == "wrong_bus": + self.assertTrue(self._rx(self.physical_switch(True, bus=2))) + self.assertFalse(self._tx(self._acc_button_msg(Buttons.RESUME, 0))) + + def test_stale_required_rx_and_profile_reset_revoke_exception(self): + self.select() + self.healthy() + self.assertTrue(self._tx(self._acc_button_msg(Buttons.RESUME, 0))) + self.safety.set_timer(1_000_001) + self.healthy(button=None) + self.assertFalse(self._tx(self._acc_button_msg(Buttons.RESUME, 0))) + self.select() + self.healthy(button=None) + self.assertFalse(self._tx(self._acc_button_msg(Buttons.RESUME, 0))) + + def test_long_unknown_ae_and_unreached_words_cannot_use_exception(self): + for word, ae in ((0, 0), (4, 0), (1, 0), (3, 0), (9, 0), (11, 0), (13, 0), (19, 0), (34, 0), (2, 32)): + with self.subTest(word=word, ae=ae): + self.select(word, ae) + self.healthy(word) + self.assertFalse(self._tx(self._acc_button_msg(Buttons.RESUME, 0))) + self.assertFalse(self.safety.get_controls_allowed()) diff --git a/opendbc_repo/opendbc/safety/tests/test_ford_three.py b/opendbc_repo/opendbc/safety/tests/test_ford_three.py new file mode 100644 index 0000000000..5d50b7ddd3 --- /dev/null +++ b/opendbc_repo/opendbc/safety/tests/test_ford_three.py @@ -0,0 +1,159 @@ +import unittest + +from opendbc.can import CANPacker +from opendbc.car import gen_empty_fingerprint +from opendbc.car.ford.fordcan import CanBus, create_acc_msg, create_lat_ctl_msg, create_lka_msg +from opendbc.car.ford.values import FordSafetyFlags +from opendbc.car.structs import CarParams +from opendbc.safety.tests.libsafety import libsafety_py + + +class TestFordThreeSafety(unittest.TestCase): + def setUp(self): + self.safety = libsafety_py.libsafety + self.packer = CANPacker("ford_lincoln_base_pt") + self.bus = CanBus(fingerprint=gen_empty_fingerprint()) + + @staticmethod + def packet(msg): + return libsafety_py.make_CANPacket(msg[0], msg[2], msg[1]) + + def init_mode(self, flags): + self.assertEqual(self.safety.set_safety_hooks(CarParams.SafetyModel.ford, int(flags)), 0) + self.safety.init_tests() + + def source(self, available): + return self.packet(self.packer.make_can_msg("Lane_Assist_Data3_FD1", 0, + {"LaActAvail_D_Actl": 3 if available else 0})) + + def denied_source(self): + return self.packet(self.packer.make_can_msg("Lane_Assist_Data3_FD1", 0, + {"LaActAvail_D_Actl": 3, "LaActDeny_B_Actl": 1})) + + def healthy_inputs(self, speed=20., curvature=0., cruise=True, omit=None): + for count in range(1, 7): + self.safety.set_timer(count * 10_000) + packets = ( + ("BrakeSysFeatures", {"Veh_V_ActlBrk": speed * 3.6, "VehVActlBrk_D_Qf": 3, "VehVActlBrk_No_Cnt": count}), + ("EngVehicleSpThrottle2", {"Veh_V_ActlEng": speed * 3.6, "VehVActlEng_D_Qf": 3}), + ("Yaw_Data_FD1", {"VehYaw_W_Actl": curvature * speed, "VehYawWActl_D_Qf": 3, "VehRollYaw_No_Cnt": count}), + ("EngBrakeData", {"BpedDrvAppl_D_Actl": 1, "CcStat_D_Actl": 5 if cruise else 0}), + ("EngVehicleSpThrottle", {"ApedPos_Pc_ActlArb": 0}), + ("DesiredTorqBrk", {"VehStop_D_Stat": 0}), + ) + for name, values in packets: + if name == omit: + continue + msg = self.packer.make_can_msg(name, 0, values) + self.assertTrue(self.safety.safety_rx_hook(self.packet(msg)), name) + self.assertTrue(self.safety.safety_rx_hook(self.source(True))) + + def test_stock_can_ownership_and_existing_mode_is_unchanged(self): + acc = self.packet(create_acc_msg(self.packer, self.bus, False, -5., 0., False, False, 255.)) + for variant in (FordSafetyFlags.NEW_PORT, FordSafetyFlags.NEW_PORT | FordSafetyFlags.CANFD, + FordSafetyFlags.NEW_PORT | FordSafetyFlags.LKA_STEERING): + with self.subTest(variant=variant): + self.init_mode(variant) + self.assertFalse(self.safety.safety_tx_hook(acc)) + self.assertTrue(self.safety.safety_tx_hook(self.packet(create_lka_msg(self.packer, self.bus, transit=True)))) + self.init_mode(FordSafetyFlags.NEW_PORT | FordSafetyFlags.LONG_CONTROL) + self.assertTrue(self.safety.safety_tx_hook(acc)) + self.init_mode(0) + self.assertTrue(self.safety.safety_tx_hook(self.packet(create_lka_msg(self.packer, self.bus)))) + + def test_transit_lka_requires_source_control_shape_and_rate(self): + self.init_mode(FordSafetyFlags.NEW_PORT | FordSafetyFlags.LKA_STEERING) + active = self.packet(create_lka_msg(self.packer, self.bus, True, 1., 2, .0002, transit=True)) + inactive = self.packet(create_lka_msg(self.packer, self.bus, transit=True)) + self.safety.set_controls_allowed(True) + self.assertFalse(self.safety.safety_tx_hook(active)) + wrong_bus = self.packet(self.packer.make_can_msg("Lane_Assist_Data3_FD1", 2, + {"LaActAvail_D_Actl": 3})) + self.safety.safety_rx_hook(wrong_bus) + self.assertFalse(self.safety.safety_tx_hook(active)) + self.assertTrue(self.safety.safety_rx_hook(self.source(True))) + self.assertFalse(self.safety.safety_tx_hook(active)) # no speed, yaw or cruise source yet + self.healthy_inputs() + self.assertTrue(self.safety.safety_tx_hook(active)) + self.assertFalse(self.safety.safety_tx_hook(self.packet(create_lat_ctl_msg(self.packer, self.bus, True, 0., 0., 0., 0.)))) + self.assertTrue(self.safety.safety_tx_hook(self.packet(create_lat_ctl_msg(self.packer, self.bus, False, 0., 0., 0., 0.)))) + jump = self.packet(create_lka_msg(self.packer, self.bus, True, 5.8, 2, .01023, transit=True)) + self.assertFalse(self.safety.safety_tx_hook(jump)) + malformed = bytearray(active[0].data[0:8]) + malformed[0] = (malformed[0] & 0x1f) | 0x60 # action 3 is not a steering request + self.assertFalse(self.safety.safety_tx_hook(self.packet((0x3CA, bytes(malformed), 0)))) + self.assertTrue(self.safety.safety_tx_hook(inactive)) + self.assertTrue(self.safety.safety_rx_hook(self.source(False))) + self.assertFalse(self.safety.safety_tx_hook(active)) + self.assertTrue(self.safety.safety_rx_hook(self.denied_source())) + self.assertFalse(self.safety.safety_tx_hook(active)) + self.assertTrue(self.safety.safety_rx_hook(self.source(True))) + self.safety.set_timer(160001) + self.assertFalse(self.safety.safety_tx_hook(active)) + + def test_transit_dynamic_speed_jerk_and_measured_curvature(self): + self.init_mode(FordSafetyFlags.NEW_PORT | FordSafetyFlags.LKA_STEERING) + self.healthy_inputs(speed=30.) + self.assertTrue(self.safety.get_controls_allowed()) + small = self.packet(create_lka_msg(self.packer, self.bus, True, 1., 2, .0001, transit=True)) + jump = self.packet(create_lka_msg(self.packer, self.bus, True, 1., 2, .0006, transit=True)) + static_max = self.packet(create_lka_msg(self.packer, self.bus, True, 1., 2, .01023, transit=True)) + self.assertTrue(self.safety.safety_tx_hook(small)) + self.assertFalse(self.safety.safety_tx_hook(jump)) # 33 Hz jerk envelope + self.assertFalse(self.safety.safety_tx_hook(static_max)) # speed-based lateral acceleration + + self.init_mode(FordSafetyFlags.NEW_PORT | FordSafetyFlags.LKA_STEERING) + self.healthy_inputs(speed=30., curvature=-.004) + self.assertFalse(self.safety.safety_tx_hook(small)) # measured curvature error + + def test_transit_missing_sources_brake_cancel_and_relay(self): + active = self.packet(create_lka_msg(self.packer, self.bus, True, 1., 2, .0001, transit=True)) + for missing in ("BrakeSysFeatures", "EngVehicleSpThrottle2", "Yaw_Data_FD1", "EngBrakeData"): + with self.subTest(missing=missing): + self.init_mode(FordSafetyFlags.NEW_PORT | FordSafetyFlags.LKA_STEERING) + self.healthy_inputs(omit=missing) + self.safety.set_controls_allowed(True) + self.assertFalse(self.safety.safety_tx_hook(active)) + + self.init_mode(FordSafetyFlags.NEW_PORT | FordSafetyFlags.LKA_STEERING) + self.healthy_inputs() + self.assertTrue(self.safety.safety_tx_hook(active)) + brake = self.packet(self.packer.make_can_msg("EngBrakeData", 0, + {"BpedDrvAppl_D_Actl": 2, "CcStat_D_Actl": 5})) + self.assertTrue(self.safety.safety_rx_hook(brake)) + self.assertFalse(self.safety.safety_tx_hook(active)) + cancel = self.packet(self.packer.make_can_msg("EngBrakeData", 0, + {"BpedDrvAppl_D_Actl": 1, "CcStat_D_Actl": 0})) + self.assertTrue(self.safety.safety_rx_hook(cancel)) + self.safety.set_controls_allowed(True) + self.assertFalse(self.safety.safety_tx_hook(active)) + + self.init_mode(FordSafetyFlags.NEW_PORT | FordSafetyFlags.LKA_STEERING) + self.healthy_inputs() + self.safety.safety_rx_hook(active) + self.assertFalse(self.safety.safety_tx_hook(active)) + + def test_transit_independent_native_permission_keeps_ae0_stock_requirement(self): + try: + for experience in (0, 32): + with self.subTest(experience=experience): + self.safety.set_alternative_experience(experience) + self.init_mode(FordSafetyFlags.NEW_PORT | FordSafetyFlags.LKA_STEERING) + self.healthy_inputs(cruise=False) + for name, values in ( + ("EPAS_INFO", {"EPAS_Failure": 0}), + ("Steering_Data_FD1", {"TjaButtnOnOffPress": 0}), + ("PowertrainData_10", {"TrnRng_D_Rq": 3}), + ): + self.assertTrue(self.safety.safety_rx_hook(self.packet(self.packer.make_can_msg(name, 0, values)))) + self.safety.set_aol_test_heartbeat(True) + self.assertTrue(self.safety.safety_rx_hook(self.packet(self.packer.make_can_msg( + "EngBrakeData", 0, {"BpedDrvAppl_D_Actl": 1, "CcStat_D_Actl": 3})))) + self.safety.aol_set_host_request(1) + self.assertFalse(self.safety.get_controls_allowed()) + self.assertEqual(self.safety.aol_get_permission_mask(), 1 if experience == 32 else 0) + active = self.packet(create_lka_msg(self.packer, self.bus, True, 1., 2, .0001, transit=True)) + self.assertEqual(bool(self.safety.safety_tx_hook(active)), experience == 32) + finally: + self.safety.set_alternative_experience(0) + self.safety.set_safety_hooks(CarParams.SafetyModel.noOutput, 0) diff --git a/openpilot/starpilot/car/ford/aol.py b/openpilot/starpilot/car/ford/aol.py new file mode 100644 index 0000000000..0b72fcc365 --- /dev/null +++ b/openpilot/starpilot/car/ford/aol.py @@ -0,0 +1,74 @@ +from dataclasses import replace +from opendbc.car import structs +from opendbc.car.ford.aol import qualified, AOL_WORDS, temporary_restriction +from openpilot.starpilot.aol.intent import AolCardIntent, AOL_TOGGLE +from openpilot.starpilot.aol.policy import AolVehiclePolicy + + +def policy_for(cp): + if qualified(cp): + return AolVehiclePolicy(intent_supported=True, settings_supported=True, runtime_supported=True, + normal_runtime_supported=True, ordinary_axis_ack_required=qualified(cp, marked_only=True), + explicit_latch=True, alternative_experience_addition=32) + return AolVehiclePolicy() + + +def native_profile_supported(model, param): + return model == int(structs.CarParams.SafetyModel.ford) and param in AOL_WORDS + + +def native_accepts_cp(cp, model, param): + return qualified(cp, marked_only=True) and native_profile_supported(model, param) and param == cp.safetyConfigs[0].safetyParam + + +def native_latch_rejected(cp, native): + return qualified(cp, marked_only=True) and native.requestedLateral and not native.lateralAllowed + + +def ordinary_axis_request_allowed(cp, cs): + return qualified(cp, marked_only=True) and cs.canValid and not cs.canTimeout and not cs.steerFaultPermanent + + +def retain_on_native_denial(cp, native, state): + return temporary_restriction(cp, state) + + +class FordCardIntent(AolCardIntent): + observe_stock_engagement = True + def __init__(self, cp, settings): + self.cp = cp + self.main_seen = False + self.main_available = False + self.main_neutral = False + self.main_pulse = False + effective = settings + self.auto_main = settings.lkas_action != AOL_TOGGLE and settings.main_action != AOL_TOGGLE + if self.auto_main: + effective = replace(settings, main_action=AOL_TOGGLE) + super().__init__(effective, explicit_latch=True) + + def update(self, CS, **kwargs): + state = structs.CarState(**CS.to_dict()) + events = [structs.CarState.ButtonEvent(**event.to_dict()) for event in CS.buttonEvents] + available = bool(state.cruiseState.available) + healthy = state.canValid and not state.canTimeout + if healthy: + if self.main_pulse: + events.append(structs.CarState.ButtonEvent(type=structs.CarState.ButtonEvent.Type.mainCruise, pressed=False)) + self.main_pulse = False + if not self.main_seen or available != self.main_available: + if not available: + self.main_neutral = True + elif self.main_neutral: + events.append(structs.CarState.ButtonEvent(type=structs.CarState.ButtonEvent.Type.mainCruise, pressed=True)) + self.main_pulse = True + self.main_seen = True + self.main_available = available + if self.auto_main and not available: + self.allowed_latch = False + state.buttonEvents = events + super().update(state.as_reader(), **kwargs) + + +def create_intent(cp, settings): + return FordCardIntent(cp, settings) diff --git a/openpilot/starpilot/car/ford/lateral_preferences.py b/openpilot/starpilot/car/ford/lateral_preferences.py new file mode 100644 index 0000000000..3c14673961 --- /dev/null +++ b/openpilot/starpilot/car/ford/lateral_preferences.py @@ -0,0 +1,19 @@ +"""Saved Ford controller selection; no onroad CP mutation or saved-byte repair.""" +from openpilot.starpilot.saved_source import read_saved + +KEY = "FordLateralMode" +CHOICES = {0: "Current curvature", 1: "BluePilot angle"} + + +def read_choice(params): + raw, readable = read_saved(params, KEY, 8) + valid = readable and raw in (None, b"0", b"1") + return (1 if valid and raw == b"1" else 0), raw, readable, valid + + +def selected(params, *, enabled): + value, _, readable, valid = read_choice(params) + safe, safe_ok = read_saved(params, "SafeMode", 8) + aol, aol_ok = read_saved(params, "AlwaysOnLateral", 8) + return int(enabled and readable and valid and value == 1 and safe_ok and safe in (None, b"0") and + aol_ok and aol in (None, b"0")) diff --git a/openpilot/starpilot/ui/ford_lateral_feature.py b/openpilot/starpilot/ui/ford_lateral_feature.py new file mode 100644 index 0000000000..b2c1f7bb2a --- /dev/null +++ b/openpilot/starpilot/ui/ford_lateral_feature.py @@ -0,0 +1,61 @@ +"""One saved Ford enum shared by Galaxy and the native feature presentation.""" +from opendbc.bluepilot_lateral.hosts.starpilot import supported +from openpilot.starpilot.car.ford.lateral_preferences import KEY, CHOICES, read_choice +from openpilot.starpilot.saved_source import read_saved +from openpilot.starpilot.saved_document import commit_exact +from openpilot.starpilot.ui.feature_settings_state import FeatureRow + + +class FordLateralFeature: + def __init__(self, owner): + self.owner = owner + + def capability(self): + cp = self.owner.vehicle_params() + try: + if cp is None or not supported(cp): + return None + return (str(cp.carFingerprint), int(cp.flags), int(cp.alternativeExperience), bool(cp.openpilotLongitudinalControl), + bool(cp.pcmCruise), str(cp.steerControlType), bool(cp.passive), bool(cp.dashcamOnly), bool(cp.notCar), + tuple((str(c.safetyModel), int(c.safetyParam)) for c in cp.safetyConfigs)) + except (AttributeError, TypeError, ValueError, OverflowError): + return None + + def dependencies(self): + values = [] + for key in ("SafeMode", "AlwaysOnLateral"): + raw, readable = read_saved(self.owner.params, key, 8) + if not readable or raw not in (None, b"0"): + return None + values.append((key, raw)) + return tuple(values) + + def rows(self, parked): + capability = self.capability() + if capability is None: + return () + value, raw, readable, valid = read_choice(self.owner.params) + dependencies = self.dependencies() + return (FeatureRow(KEY, "Ford steering controller", CHOICES[value] if valid else "Invalid saved choice", raw, + choices=tuple(CHOICES.values()), available=parked and self.owner.authority("parked_preferences") and + readable and dependencies is not None, capability=capability, + dependencies=dependencies or (), repair_value="" if valid else CHOICES[0], default_value=CHOICES[0], + reason="Applies next drive. BluePilot angle is available with normal cruise control on supported Ford vehicles."),) + + def apply(self, request): + value = next((code for code, label in CHOICES.items() if label == request.value), None) + if (request.key != KEY or value is None or request.related_source is not None or request.display_unit or request.direction): + return False + + def authorized(): + capability = self.capability() + _, raw, readable, valid = read_choice(self.owner.params) + dependencies = self.dependencies() + return (self.owner.authority("parked_preferences") and bool(request.vehicle_fingerprint) and + self.owner.vehicle_fingerprint() == request.vehicle_fingerprint and capability is not None and + capability == request.capability and dependencies is not None and dependencies == request.dependencies and + readable and raw == request.expected and (valid or value == 0)) + + result = commit_exact(self.owner.params, key=KEY, max_bytes=8, raw=str(value).encode(), expected=request.expected, + authorized=authorized, temp_prefix=".ford-lateral-") + return result.committed and result.verified