Compare commits

..

5 Commits

Author SHA1 Message Date
Prabhaav Pillai 3b1ce61fb8 fix updater 2026-10-20 01:19:32 -04:00
Prabhaav Pillai 6c93a41942 Test update 2026-10-20 01:14:30 -04:00
Prabhaav Pillai b4154fdc5b Merge commit '0e7503448c2f3fd2678ceeb6ab3799be0f517c65' into test_updates 2026-10-20 01:12:15 -04:00
Prabhaav Pillai ea7de662dc test update 2026-10-20 01:07:24 -04:00
Prabhaav Pillai cc5b618884 update 2026-10-20 01:05:44 -04:00
2768 changed files with 27083 additions and 463659 deletions
-17
View File
@@ -12,12 +12,6 @@ openpilot/selfdrive/modeld/models/big_*_tinygrad.pkl -text
*.woff2 -text
*.wav -text
openpilot/starpilot/galaxy/web/vendor/vue/vue.esm-browser.js -text
*.apk -text
openpilot/starpilot/galaxy/bin/hev-socks5-tunnel_linux_arm64 -text
openpilot/starpilot/soloist/pulseaudio/bin/pulseaudio -text
openpilot/starpilot/soloist/pulseaudio/bin/pactl -text
openpilot/starpilot/soloist/bluealsa/bin/bluealsa-aplay -text
openpilot/starpilot/soloist/bluealsa/bin/bluealsad -text
openpilot/selfdrive/car/tests/test_models_segs.txt -text
openpilot/common/hardware/comma/updater -text
@@ -49,14 +43,3 @@ openpilot/system/loggerd/loggerd -text
openpilot/starpilot/galaxy/bin/frpc_linux_arm64 -text
openpilot/starpilot/maps/provider/mapd -text
openpilot/selfdrive/test/process_replay/refs/starpilot/*.zst -text
# Published Panda object files are AArch64 ELF, not text.
openpilot/selfdrive/pandad/main.o -text
openpilot/selfdrive/pandad/panda.o -text
openpilot/selfdrive/pandad/panda_safety.o -text
openpilot/selfdrive/pandad/panda_usb.o -text
openpilot/selfdrive/pandad/pandad.o -text
openpilot/selfdrive/pandad/spi.o -text
# Compressed recorded regression fixture; retain exact binary bytes.
openpilot/starpilot/tests/testdata/ford_mache_lead_departure.json.gz -text
+3 -7
View File
@@ -5,7 +5,7 @@ on:
branches:
- master
- Domathon
- Dom
- SecretGoodStarPilot
pull_request:
workflow_call:
inputs:
@@ -29,15 +29,11 @@ jobs:
steps:
- uses: commaai/timeout@v1
- uses: actions/checkout@v7
with:
sparse-checkout: |
/docs/
/openpilot/selfdrive/assets/icons_mici/settings/comma_icon.png
sparse-checkout-cone-mode: false
- run: ./tools/op.sh setup
# Build
- name: Build docs
run: python3 docs/serve.py --build
run: ./tools/op.sh docs --build
# Push to docs.comma.ai
- uses: actions/checkout@v7
-69
View File
@@ -1,69 +0,0 @@
name: iOS companion
on:
push:
branches: [Dom, secretgood-ios-integration]
paths:
- 'openpilot/starpilot/companion/ios/**'
- 'openpilot/starpilot/galaxy_bluetooth/**'
- '.github/workflows/ios-companion.yaml'
pull_request:
paths:
- 'openpilot/starpilot/companion/ios/**'
- 'openpilot/starpilot/galaxy_bluetooth/**'
- '.github/workflows/ios-companion.yaml'
workflow_dispatch:
permissions:
contents: read
concurrency:
group: ios-companion-${{ github.event.pull_request.number || github.ref }}
cancel-in-progress: true
jobs:
app:
name: Swift tests and iOS Simulator build
runs-on: macos-26
timeout-minutes: 25
defaults:
run:
working-directory: openpilot/starpilot/companion/ios
steps:
- uses: actions/checkout@v4
with:
submodules: false
lfs: false
persist-credentials: false
- uses: actions/setup-node@v4
with:
node-version: '22'
- name: Run companion regressions
env:
CI_PRIMARY_REPOSITORY_PATH: ${{ github.workspace }}/openpilot/starpilot/companion/ios
run: sh ci_scripts/ci_post_clone.sh
- name: Build for iOS Simulator
run: >-
xcodebuild -project GalaxyBluetooth.xcodeproj
-scheme GalaxyBluetooth -configuration Debug
-sdk iphonesimulator -destination 'generic/platform=iOS Simulator'
-derivedDataPath "$RUNNER_TEMP/galaxy-ios-build"
CODE_SIGNING_ALLOWED=NO build
bridge:
name: Comma Bluetooth bridge tests
runs-on: ubuntu-24.04
timeout-minutes: 10
steps:
- uses: actions/checkout@v4
with:
submodules: false
lfs: false
persist-credentials: false
- uses: actions/setup-python@v5
with:
python-version: '3.12'
- name: Install bridge test dependencies
run: python -m pip install pycryptodome
- name: Run bridge regressions
run: python -m unittest discover -s openpilot/starpilot/galaxy_bluetooth/tests -v
+1 -1
View File
@@ -2,7 +2,7 @@ name: safety qualification
on:
push:
branches: [master, Domathon, Dom]
branches: [master, Domathon, SecretGoodStarPilot]
pull_request:
workflow_dispatch:
+9 -207
View File
@@ -5,7 +5,7 @@ on:
branches:
- master
- Domathon
- Dom
- SecretGoodStarPilot
pull_request:
workflow_dispatch:
workflow_call:
@@ -34,13 +34,6 @@ jobs:
contents: read
steps:
- uses: actions/checkout@v7
- name: Validate published device build receipt
if: github.event_name == 'push' && github.ref == 'refs/heads/Dom'
run: python3 tools/ci/check_prebuilt_receipt.py --revision HEAD
- name: Check shipped device runtime dependencies
run: |
python3 -m unittest tools.laptop_device_build.tests.test_runtime_dependencies -v
python3 -c 'from pathlib import Path; assert b"starting pandad (comma hardware)" in Path("openpilot/selfdrive/pandad/pandad").read_bytes(), "Shipped pandad must use the comma hardware build profile"'
- name: Validate tracked dependencies
run: python3 tools/vendor/check.py --revision HEAD
- run: ./tools/op.sh setup
@@ -203,21 +196,17 @@ jobs:
timeout-minutes: ${{ contains(runner.name, 'nsc') && 2 || 20 }}
env:
RAYLIB_BACKEND: headless
STARPILOT_TEST_DIAGNOSTICS: ci-results/host-test-diagnostics/unittest
run: tools/op.sh test --json-output unit-test-results.json
- name: Test custom module-level pytest cases
if: ${{ !cancelled() && steps.build.outcome == 'success' }}
timeout-minutes: 15
env:
RAYLIB_BACKEND: headless
run: python3 tools/ci/run_host_tests.py --pytest
- name: Test GM vehicle configurations and CAN behavior
if: ${{ !cancelled() && steps.build.outcome == 'success' }}
timeout-minutes: 5
run: tools/op.sh test opendbc_repo/opendbc/car/gm/tests --json-output gm-test-results.json
- name: Test shared GM discovery, routing, and manual overrides
if: ${{ !cancelled() && steps.build.outcome == 'success' }}
timeout-minutes: 2
run: >-
.venv/bin/python -m pytest -q --import-mode=importlib
opendbc_repo/opendbc/car/gm/tests/test_shared_discovery.py
opendbc_repo/opendbc/car/gm/tests/test_automatic_discovery.py
opendbc_repo/opendbc/car/gm/tests/test_bolt_vin_discovery.py
--junitxml=gm-discovery-results.xml
- name: Test native independent-axis protocol
if: ${{ !cancelled() && steps.build.outcome == 'success' }}
run: |
@@ -238,140 +227,13 @@ jobs:
STARPILOT_PYTHON: ${{ github.workspace }}/.venv/bin/python
run: go test -mod=readonly -race -run '^Test(MsgqNativeLayout|Shadow(GoPythonIPC|ExecutableHostGpsIPC))$' -count=1 -v
- name: Save complete unit test results
if: ${{ always() && (hashFiles('unit-test-results.json') != '' || hashFiles('gm-test-results.json') != '' || hashFiles('gm-discovery-results.xml') != '' || hashFiles('ci-results/host-test-diagnostics/**') != '') }}
if: ${{ always() && (hashFiles('unit-test-results.json') != '' || hashFiles('gm-test-results.json') != '') }}
uses: actions/upload-artifact@v4
with:
name: unit-test-results
path: |
unit-test-results.json
gm-test-results.json
gm-discovery-results.xml
ci-results/host-test-diagnostics/
if-no-files-found: error
custom_pytest:
name: custom pytest (${{ matrix.shard }})
runs-on: ubuntu-24.04
timeout-minutes: 35
permissions:
contents: read
strategy:
fail-fast: false
matrix:
shard: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23]
steps:
- uses: actions/checkout@v7
- name: Provide JavaScript runtime for Galaxy contract tests
uses: actions/setup-node@v7
with:
node-version: '24'
package-manager-cache: false
- name: Provide pinned map provider toolchain
uses: actions/setup-go@v7
with:
go-version: '1.25.1'
cache-dependency-path: mapd_repo/go.sum
- name: Fetch pinned map provider dependencies
working-directory: mapd_repo
env:
GOTOOLCHAIN: local
run: go mod download
- run: ./tools/op.sh setup
id: setup
- name: Build openpilot
id: build
run: scons
- name: Provide H.264 encoder for Android Auto integration tests
if: ${{ !cancelled() && steps.build.outcome == 'success' }}
run: |
uv pip install --python .venv/bin/python --only-binary av av==19.0.1
.venv/bin/python -c "import av; assert 'libx264' in av.codecs_available"
- name: Test every assigned custom pytest node serially
if: ${{ !cancelled() && steps.build.outcome == 'success' }}
timeout-minutes: 15
env:
RAYLIB_BACKEND: headless
run: .venv/bin/python -m tools.ci.custom_pytest_shards run --index "${{ matrix.shard }}" --count 24 --output "ci-results/custom-pytest-${{ matrix.shard }}"
- name: Save collection, every outcome, JUnit and durable worker diagnostics
if: always()
uses: actions/upload-artifact@v4
with:
name: custom-pytest-${{ matrix.shard }}
path: ci-results/custom-pytest-${{ matrix.shard }}/
if-no-files-found: error
custom_pytest_complete:
name: complete custom pytest catalog
needs: custom_pytest
if: ${{ always() && !cancelled() }}
runs-on: ubuntu-24.04
permissions:
contents: read
steps:
- uses: actions/checkout@v7
- uses: actions/download-artifact@v4
with:
pattern: custom-pytest-*
path: ci-results/custom-pytest-shards
- name: Require every case passed or audited capability-unavailable
run: python3 -m tools.ci.custom_pytest_shards aggregate --directory ci-results/custom-pytest-shards --count 24 --output ci-results/custom-pytest-complete.json
- name: Save complete custom catalog verdict
if: always()
uses: actions/upload-artifact@v4
with:
name: custom-pytest-complete
path: ci-results/custom-pytest-complete.json
if-no-files-found: error
aol_lifecycles:
name: AOL lifecycles (${{ matrix.shard }})
runs-on: ubuntu-24.04
timeout-minutes: 35
permissions:
contents: read
strategy:
fail-fast: false
matrix:
shard: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
env:
FUZZ_SEED: '0'
steps:
- uses: actions/checkout@v7
- run: ./tools/op.sh setup
- name: Build native host dependencies
run: scons
- name: Gate every assigned lifecycle module serially
timeout-minutes: 10
run: python3 tools/ci/run_vehicle_tests.py --suite aol-lifecycle --shard-index "${{ matrix.shard }}" --shard-count 16 --output "ci-results/aol-lifecycle-${{ matrix.shard }}"
- name: Save every lifecycle outcome and native build
if: always()
uses: actions/upload-artifact@v4
with:
name: aol-lifecycle-${{ matrix.shard }}
path: ci-results/aol-lifecycle-${{ matrix.shard }}/
if-no-files-found: error
aol_lifecycle_complete:
name: complete AOL lifecycle catalog
needs: aol_lifecycles
if: ${{ always() && !cancelled() }}
runs-on: ubuntu-24.04
permissions:
contents: read
steps:
- uses: actions/checkout@v7
- uses: actions/download-artifact@v4
with:
pattern: aol-lifecycle-*
path: ci-results/aol-lifecycles
- name: Require every full-catalog case exactly once and passed
run: python3 tools/ci/lifecycle_shards.py ci-results/aol-lifecycles --count 16 --output ci-results/aol-lifecycle-complete.json
- name: Save complete catalog verdict
if: always()
uses: actions/upload-artifact@v4
with:
name: aol-lifecycle-complete
path: ci-results/aol-lifecycle-complete.json
if-no-files-found: error
map_provider:
@@ -407,7 +269,7 @@ jobs:
strategy:
fail-fast: false
matrix:
suite: [interfaces, safety-debug]
suite: [interfaces, safety-debug, safety-release]
env:
FUZZ_SEED: '0'
steps:
@@ -433,57 +295,6 @@ jobs:
path: ci-results/${{ matrix.suite }}/
if-no-files-found: error
safety_release_contracts:
name: RELEASE vehicle contracts (${{ matrix.shard }})
runs-on: ubuntu-24.04
timeout-minutes: 35
permissions:
contents: read
strategy:
fail-fast: false
matrix:
shard: [0, 1, 2, 3]
env:
FUZZ_SEED: '0'
steps:
- uses: actions/checkout@v7
- run: ./tools/op.sh setup
- name: Build native host dependencies
run: scons
- name: Run every assigned RELEASE target serially
timeout-minutes: 20
run: python3 tools/ci/run_vehicle_tests.py --suite safety-release --shard-index "${{ matrix.shard }}" --shard-count 4 --output "ci-results/safety-release-${{ matrix.shard }}"
- name: Save every RELEASE outcome and native build
if: always()
uses: actions/upload-artifact@v4
with:
name: safety-release-${{ matrix.shard }}
path: ci-results/safety-release-${{ matrix.shard }}/
if-no-files-found: error
safety_release_complete:
name: complete RELEASE vehicle catalog
needs: safety_release_contracts
if: ${{ always() && !cancelled() }}
runs-on: ubuntu-24.04
permissions:
contents: read
steps:
- uses: actions/checkout@v7
- uses: actions/download-artifact@v4
with:
pattern: safety-release-*
path: ci-results/safety-release-shards
- name: Require every RELEASE case exactly once and passed
run: python3 tools/ci/lifecycle_shards.py ci-results/safety-release-shards --suite safety-release --count 4 --output ci-results/safety-release-complete.json
- name: Save complete RELEASE verdict
if: always()
uses: actions/upload-artifact@v4
with:
name: safety-release-complete
path: ci-results/safety-release-complete.json
if-no-files-found: error
recorded_vehicles:
name: recorded vehicles (${{ matrix.variant }})
runs-on: ubuntu-24.04
@@ -587,15 +398,6 @@ jobs:
with:
name: process_replay_diff.txt
path: openpilot/selfdrive/test/process_replay/diff.txt
- name: Save complete replay outputs for review
uses: actions/upload-artifact@v7
if: always()
with:
name: process-replay-outputs
path: |
openpilot/selfdrive/test/process_replay/fakedata/*.zst
openpilot/selfdrive/test/process_replay/coverage.json
if-no-files-found: error
- name: Upload diff report
uses: actions/upload-artifact@v7
if: always() && github.event_name == 'pull_request'
-7
View File
@@ -18,7 +18,6 @@ a.out
.venv-linux-arm64/
bin/
!openpilot/starpilot/galaxy/bin/
!openpilot/starpilot/soloist/pulseaudio/bin/
# created at launch for comma hardware PYTHONPATH (PC uses editable installs via pyproject.toml)
/msgq
@@ -45,12 +44,8 @@ bin/
*.os-*
*.so
!openpilot/tools/replay/libmedia_mux.so
!openpilot/starpilot/soloist/pulseaudio/lib/*.so
!openpilot/starpilot/soloist/pulseaudio/modules/*.so
*.a
st[0-9A-Za-z][0-9A-Za-z][0-9A-Za-z][0-9A-Za-z][0-9A-Za-z][0-9A-Za-z]
!/openpilot/starpilot/system/starport/
!/openpilot/tools/starport/
*.unchunked
*.clb
*.class
@@ -143,5 +138,3 @@ openpilot/selfdrive/modeld/models/*.unchunked
/jetlink_repo/jetlink.egg-info/
# Local Google Play resolver build output (source and lockfile are versioned).
openpilot/starpilot/flm/_primitive_walk.cpp
+8 -20
View File
@@ -2,7 +2,7 @@
## Jetlink external inference
The comma-side Jetlink client and USB transport in `jetlink_repo` are by Zeph Leggett and the [Jetlink contributors](https://github.com/zoompilot/jetlink). They are vendored from revision `a863c3801da6fd925d14eb1f5b1e250f8efcc649` under the MIT license, retained in [jetlink_repo/LICENSE](jetlink_repo/LICENSE). StarPilot's adapter (`openpilot/starpilot/models/jetlink_adapter.py`) builds on Jetlink's openpilot layer and owns its param names, Always On Lateral rule, model runner reset, settings and alerts. Companion applications and inference servers remain distributed by Jetlink.
The comma-side Jetlink client and USB transport in `jetlink_repo` are by Zeph Leggett and the [Jetlink contributors](https://github.com/zoompilot/jetlink). They are vendored from revision `d24328d849b0e5154b55f149dc18c5dfe8bd79cc` under the MIT license, retained in [jetlink_repo/LICENSE](jetlink_repo/LICENSE). StarPilot's adapter (`openpilot/starpilot/models/jetlink_adapter.py`) builds on Jetlink's openpilot layer and owns its param names, Always On Lateral rule, model runner reset, settings and alerts. Companion applications and inference servers remain distributed by Jetlink.
## MRR35 Hyundai angle and radar
@@ -12,28 +12,16 @@ The copied MRR35 generator source and DBC definition are at `opendbc_repo/opendb
## Ford support adapted from BluePilot
Ford lateral control vendors [BluePilot lateral](https://github.com/BluePilotDev/bluepilot-lateral) v0.2.1 (`2b9dc6cc784faac47a1885d0bda0561f7b76f74d`), developed by Alan Polk (`alan-polk`) and the BluePilot contributors. Alan provided the [StarPilot integration in PR #269](https://github.com/StarPilotHQ/StarPilot/pull/269); his commits and authorship are retained. BluePilot maintains the library and its integration; StarPilot keeps its settings, AOL policy, packaging and integration tests separate. Complete contributor and license notices remain in [the library credits](opendbc_repo/opendbc/bluepilot_lateral/CREDITS.md) and [license](opendbc_repo/opendbc/bluepilot_lateral/LICENSE).
The Ford lateral strategies, extended CAN constructors, camera-radar filtering and native checks are adapted from StarPilot `2efe6017bfe14cee4807833e05f9a7f6ba255cdb`. Their lineage includes BluePilot's `bp-7.0` Ford work, principally by Alan Polk, with contributions from John Christman, Jacob Neulight, tonesto7, Haibin Wen and other sunnypilot and BluePilot contributors. The reference snapshot is [`e1d051d7ba270261b4455068bd68f1a58db15a4a`](https://github.com/BluePilotDev/bluepilot/commit/e1d051d7ba270261b4455068bd68f1a58db15a4a); the exact checkout used for the earlier StarPilot import was not recorded.
The Ford CAN FD camera-lead radar filtering is adapted from StarPilot `2efe6017bfe14cee4807833e05f9a7f6ba255cdb`. Its lineage includes BluePilot's `bp-7.0` Ford work, principally by Alan Polk, with contributions from John Christman, Jacob Neulight, tonesto7, Haibin Wen and other sunnypilot and BluePilot contributors. The reference snapshot is [`e1d051d7ba270261b4455068bd68f1a58db15a4a`](https://github.com/BluePilotDev/bluepilot/commit/e1d051d7ba270261b4455068bd68f1a58db15a4a); the exact checkout used for the earlier StarPilot import was not recorded.
Relevant lineage includes the controller and integration work in [`db2bdff05`](https://github.com/BluePilotDev/bluepilot/commit/db2bdff05df103d71df62f45c2a3cb5211aba6e6) and [`d0aac605f`](https://github.com/BluePilotDev/bluepilot/commit/d0aac605f99d37e9da205e419f7989c1e9eaa386), extended CAN and safety work in [`8f8d6d15f`](https://github.com/BluePilotDev/bluepilot/commit/8f8d6d15f0a590f42b78de964ffb0d0af7f5d63d), and manual-turn detection in [`97867c1eb`](https://github.com/BluePilotDev/bluepilot/commit/97867c1eb57b7472f6fc3de62f0fef576e5a5497).
The radar interface preserves that attribution while adapting to the current interfaces. Upstream contributors do not maintain or endorse this adaptation. Applicable notices are retained in [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md).
The vehicle strategy and CAN/native owners preserve that attribution while adapting to the current controller interfaces and shared safety limits. Upstream contributors do not maintain or endorse this adaptation. Applicable notices are retained in [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md).
## Optional Ford angle controller
The vendored `opendbc_repo/opendbc/bluepilot_lateral` angle core, codecs and Ford-only safety hooks are adapted directly from [BluePilot bp-7.0 e1d051d7ba270261b4455068bd68f1a58db15a4a](https://github.com/BluePilotDev/bluepilot/commit/e1d051d7ba270261b4455068bd68f1a58db15a4a), principally by Alan Polk, with John Christman, Jacob Neulight, Nathan Ingraham, Praeuner and other BluePilot, sunnypilot and comma contributors. Exact source paths and intentionally stricter safety checks are recorded in that folder. Both upstream `LICENSE` and `LICENSE.md` notices are retained. Its layout follows Alan Polk's September 2026 library proposal; this is a StarPilot adapter, not a published BluePilot library release.
## RAV4 Continental ARS510 receiver
The optional ACC-target and fused-track receivers and DBC preserve firestar5683's Dom integration from `b220a37f4bd119e402225a7aa16a7cd84878d0af` (Sea Turtles, 2026-10-13) and its ARS510 source attribution to ds-sebastian/ars510-radar `fb5b29c2b5999f34afeb6f7ac494a73949d66c67`, copyright 2026 ARS510 radar contributors. The complete MIT permission and warranty notice is retained in THIRD_PARTY_NOTICES.md. Startup/settings ownership is adapted to the current StarPilot architecture; no original firmware binaries or safety permissions are copied.
## Spotify Bluetooth output
Spotify's Bluetooth output binds the comma's BlueALSA A2DP source to the selected speaker through a process-local ALSA configuration, leaving the system ALSA default, soundd and the warning speaker untouched. That approach is adapted from firestar5683's RoadScore Bluetooth output (`roadscore/prototype/bluetooth_output.py`, firestar5683/StarPilot `RoadScore` at `249eb88b3a397db847e4a595d7e23b7e85d329e5`). The Soloist player itself is never included: each user downloads it from Spotify, and the PulseAudio server that carries its audio is vendored unmodified from Ubuntu (see THIRD_PARTY_NOTICES.md).
## Tesla Pre-AP pedal control
The Pre-AP configuration, pedal codec/feedback, VirtualDAS feedforward table, grade compensation, torque-zero estimator and vehicle-specific gains preserve firestar5683's intentional Dom work, including `7837a3c1aab`, `aed0b7fdb9e9` and pinned `b220a37f4bd119e402225a7aa16a7cd84878d0af`. Original author attribution: firestar5683 <168790843+firestar5683@users.noreply.github.com>. Startup/calibration ownership, current upstream button/PID interfaces and native command bounds are adapted to the current StarPilot architecture; the old permissive native gateway is not transplanted. Existing source/license notices remain intact.
## Subaru angle steering from Jacob Waller's fork
Subaru angle support includes implementation maintained and integrated by **Jacob Waller (jacobw)** in [jacobwaller/openpilot, jul-angle-based](https://github.com/jacobwaller/openpilot/tree/542816196a18dba5f6f0af093c1ece4f415b5a22), with its [opendbc implementation at 8acbeccdab45a47aa7af170d2d17b61f0eb5e4f0](https://github.com/jacobwaller/opendbc/tree/8acbeccdab45a47aa7af170d2d17b61f0eb5e4f0). Jacob authored the VehicleModel angle-limit type correction and integrated the Crosstrek support. The branch also retains the original angle implementation and follow-up work by **lukasloetkolben and elkoled**, alongside comma contributors; their authorship remains theirs.
The inherited source covers Subaru angle platform/firmware definitions, `ES_Status` cruise state, angle controller/CAN integration, vehicle-model limits and native angle enforcement. StarPilot has additional platform-specific limits, driver handoff, discovery and AOL safety guards; this attribution does not claim identical tuning or complete parity with the reference fork. Original source commits, author names, emails and titles are recorded in [the Subaru origin history](opendbc_repo/opendbc/car/subaru/ORIGIN_HISTORY.tsv).
The explicit StarPilot [jacobw Subaru adapter](opendbc_repo/opendbc/car/subaru/JACOBW.md) additionally integrates that branch's low-speed filter, target-first limiting and Crosstrek EPS envelope. Its preserved stricter guards and platform scope are documented alongside the code.
-202
View File
@@ -1,202 +0,0 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
+11 -87
View File
@@ -1,90 +1,16 @@
# StarPilot
StarPilot is an independent fork of [openpilot](https://github.com/commaai/openpilot), with custom driving controls, vehicle integrations, raylib interfaces for comma 3 and comma four, and the Galaxy companion interface.
[![Ask DeepWiki](https://img.shields.io/badge/Ask-DeepWiki-blue?logo=readthedocs&logoColor=white)](https://deepwiki.com/StarPilotHQ/StarPilot)
[![Discord](https://img.shields.io/discord/1387432184121393333?label=Discord)](https://firestar.link/discord)
[![Last Updated](https://img.shields.io/github/last-commit/StarPilotHQ/StarPilot/StarPilot)](https://github.com/StarPilotHQ/StarPilot)
[![Wiki](https://img.shields.io/badge/Wiki-StarPilot-blue?logo=wiki)](https://wiki.firestar.link)
[![iOS App Store](https://img.shields.io/badge/iOS-App_Store-black?logo=apple&logoColor=white)](https://apps.apple.com/ca/app/starpilot-bt/id6821039119)
[![Android Beta](https://img.shields.io/badge/Android-Join_Beta-green?logo=android&logoColor=white)](https://groups.google.com/g/galaxy-starpilot-android-beta)
**Domathon is the development branch for StarPilot 7.0.** It rebuilds StarPilot on a current openpilot foundation. Feature migration and vehicle qualification are still in progress; this branch is not a completed replacement for the existing Dom release.
**StarPilot** is a custom fork of [comma.ai's openpilot](https://comma.ai/openpilot),
an open source driver assistance system.
## Explore the project
**This is the StarPilot 7.0 development branch (`SecretGoodStarPilot`). Feature migration,
vehicle qualification, and Auto Learn validation are still in progress.**
Openpilot provides
* Automated Lane Centering
* Adaptive Cruise Control
* Lane Change Assist
* Driver Monitoring *without wheel nags*
Ford-specific lateral-control and vehicle-support work includes substantial adaptations from
[BluePilot](https://github.com/BluePilotDev/bluepilot/tree/bp-7.0), principally developed by
[Alan Polk](https://github.com/alan-polk) with additional BluePilot contributors. StarPilot's
implementation has since diverged, but that does not erase its lineage. See [CREDITS.md](CREDITS.md)
for the code-level provenance and [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md) for applicable
upstream notices and terms. BluePilot and its contributors do not maintain or endorse StarPilot;
please direct support requests for this adaptation to the StarPilot project.
Hyundai, Kia, and Genesis angle steering and related vehicle support include substantial adaptations
from [sunnypilot](https://github.com/sunnypilot/sunnypilot/tree/hkg-angle-steering-2025) and its
[opendbc angle-steering branch](https://github.com/sunnypilot/opendbc/tree/hkg-angle-steering-2025).
StarPilot's implementation has diverged significantly; the upstream contributors do not maintain
this adaptation. Detailed code lineage is recorded in [CREDITS.md](CREDITS.md).
StarPilot has a vibrant, welcoming community [discord](https://firestar.link/discord).
Stop by to chat or ask questions!
If your car isn't driving as well as you'd like, [open a ticket so we can help](https://firestar.link/logs)!
## Documentation
Please see [https://wiki.firestar.link](https://wiki.firestar.link) for hardware lists,
installation guides, and software configuration.
## Features
* **Full support for Comma C3, C3X, and C4**
* Full support for chestnut/eGPU on C3, C3X, and C4. C3/C3X may require special gps handling.
* Model switcher with all of comma's tinygrad driving models
* StarPilot custom torque controller
* StarPilot custom longitudinal planner for both radar and VoACC (visual only, radar-less) vehicles
* **Custom tuning for an expanding list of vehicles**
* Firestar Lateral Method -
Auto tuning system to adapt openpilot to *your* car's unique lateral characteristics.
* Galaxy: StarPilot's portal to configure your comma device using your phone from anywhere.
Download models, change settings, update software, diagnostics, manage dashcam video, and more.
* Navigation - Display routes and give the driving model hints on taking exits and turns.
* Always On Lateral (full time steering assist)
* Lane Centering - Enable to center between detected lane lines,
with graceful fallback to model E2E lateral outputs and safety breakout
* Force Stop 2.0 - Better stops at stop signs and traffic lights.
* Speed Limit Controller - Use dashboard, map data, and/or vision detection for speed limit signs
* Curve Speed Controller - Learns from how you take curves
* Conditional Experimental Mode (CEM)
* Conditional Chill Mode (CCM)
* Driving Profiles and Traffic Mode
* Custom themes
* Alert volume customization
* Comma Pedal Interceptor support
* Bluetooth support - Connect keyboards, controllers, steering wheel remotes, and more.
* Sentry mode - Record when motion is detected while parked.
* V-ASM - Detect vehicles in the adjacent/blind spots using the driver-facing camera.
* Additional car support - Toyota SDSU, ZSS, CAN filter; pre-AP tesla; ford; Polestar 2; and more.
* And more!
## GM-only Features
* Increased LKAS fault resiliency
* ASCM_INT and SASCM support
* Custom lateral torque controller, with special tuning for Bolts
* 50% extra torque on 2017 Chevy Bolt
* Improved lateral and longitudinal tuning
* Dashboard cruise control display speed spoofing for vehicles with pedal interceptor
* Extra steering wheel button functionality for vehicles with pedal interceptor
* Optional toggle to boot comma when remote starting your vehicle
- [Developer commands](tools/STARPILOT_DEVELOPMENT.md): host tools, replay, and device builds.
- [Driving interfaces](openpilot/starpilot/ui/README.md) and [Galaxy](openpilot/starpilot/galaxy/README.md): native and companion controls.
- [Driving models](openpilot/starpilot/models/README.md): model management, artifact compatibility, and Model Laboratory status.
- [Builds and developer tools](docs/how-to/laptop-device-build.md): local development and device builds.
- [Dependency maintenance](tools/vendor/README.md): tracked source folders and upstream sync records.
## Development
@@ -110,10 +36,8 @@ StarPilot retains upstream vehicle and Panda safety interfaces and adds regressi
Support depends on the vehicle configuration and enabled feature. An existing vehicle identifier or settings page does not by itself establish driving support. Model Laboratory currently exposes management controls, but paired driving inference remains unavailable pending integration and Chestnut validation.
## Third-Party Notices
## Upstream and attribution
* Portions of this software include modified versions of the Material Design Icons provided by Google under the Apache License 2.0. A copy of the license is included in the `LICENSE-MDI` file.
* Ford support includes software adapted from BluePilot's `bp-7.0` branch. The source repository contains both a standard MIT notice and a separate custom SUNNYPILOT LLC notice; StarPilot preserves both in [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md).
* Hyundai, Kia, and Genesis support includes software adapted directly from sunnypilot's HKG angle-steering branch and sunnypilot/opendbc. StarPilot preserves the applicable notices in [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md).
The current openpilot baseline is [`78dccf0b482ea1298fd1f6fa59b0554187b02ce6`](https://github.com/commaai/openpilot/commit/78dccf0b482ea1298fd1f6fa59b0554187b02ce6). Its history remains intact, followed by the StarPilot foundation and feature commits. Upstream development continues independently; the baseline changes only after an update has been integrated and checked.
> This project uses software from Haibin Wen and SUNNYPILOT LLC and is licensed under a custom license requiring permission for use.
See [LICENSE](LICENSE), [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md), and [CREDITS.md](CREDITS.md) for licensing and source attribution. Component licenses remain with their source folders. StarPilot is maintained independently of comma.
+1 -2
View File
@@ -318,7 +318,7 @@ SConscript([
if arch == "comma_arm64":
SConscript(['openpilot/system/camerad/SConscript'])
SConscript(['openpilot/starpilot/system/starport/SConscript'])
SConscript(['openpilot/starpilot/system/android_auto/SConscript'])
# Build selfdrive
SConscript([
@@ -329,7 +329,6 @@ SConscript([
'openpilot/selfdrive/ui/SConscript',
'openpilot/starpilot/audio/native/SConscript',
'openpilot/starpilot/models/runtime_bridge/SConscript',
'openpilot/starpilot/flm/SConscript',
])
# Replay is also the isolated on-device viewer engine.
+11 -33
View File
@@ -73,7 +73,17 @@ the exclusion of the other.
## BluePilot Ford support
The Ford CAN FD camera-radar filtering includes work adapted from BluePilot's `bp-7.0` source, through StarPilot `2efe6017bfe14cee4807833e05f9a7f6ba255cdb`. See [CREDITS.md](CREDITS.md#ford-support-adapted-from-bluepilot) for contributors and source revisions. The upstream extension-file and `LICENSE.md` notices reproduced above also apply to that source; they are retained without resolving the difference between their published license descriptions.
The Ford lateral strategies, CAN constructors, camera-radar filtering and native checks include work adapted from BluePilot's `bp-7.0` source, through StarPilot `2efe6017bfe14cee4807833e05f9a7f6ba255cdb`. See [CREDITS.md](CREDITS.md#ford-support-adapted-from-bluepilot) for contributors and source revisions. The upstream extension-file and `LICENSE.md` notices reproduced above also apply to the Ford extension sources; they are retained without resolving the difference between their published license descriptions.
## Optional BluePilot angle library adapter
The angle-only adapter in `opendbc_repo/opendbc/bluepilot_lateral` is sourced directly from BluePilot bp-7.0 commit e1d051d7ba270261b4455068bd68f1a58db15a4a. The complete upstream MIT notice is retained in that folder's `LICENSE`, and the simultaneously published Custom MIT notice is retained verbatim in `LICENSE.md`. The applicable SUNNYPILOT acknowledgments reproduced above are also retained in its `CREDITS.md`. This preserves the published terms without resolving their scope or representing the adapted extension as unambiguously plain MIT.
The optional, default-disabled angle lane-centering trim additionally derives from
BluePilot bp-dev e22afa6be9b881fa784c92ebb316db47728a3d81. Its exact source and
contributors are recorded in the library CREDITS.md; the same root/opendbc MIT
and Custom MIT notices coexist unchanged at that revision. This adds attribution,
not a license-scope decision or permission grant.
## Continental ARS510 radar
@@ -102,35 +112,3 @@ 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.
## PulseAudio server for Spotify
`openpilot/starpilot/soloist/pulseaudio/` contains unmodified AArch64 binaries from Ubuntu 24.04 packages: PulseAudio 16.1 (LGPL-2.1-or-later), libltdl (LGPL-2.1-or-later), libtdb (LGPL-3.0-or-later), libsoxr (LGPL-2.1-or-later), liborc and speexdsp (BSD-style). The complete copyright and license notices are in that directory's `licenses/`, package hashes in `PACKAGES.sha512`, and the corresponding source is available from Ubuntu's archive for the exact versions listed in its README. The libraries are dynamically linked and may be replaced with `update.sh`.
## Galaxy Android companion tunnel
`openpilot/starpilot/galaxy/bin/hev-socks5-tunnel_linux_arm64` is the upstream
[hev-socks5-tunnel 2.18.0](https://github.com/heiher/hev-socks5-tunnel/releases/tag/2.18.0)
static Linux ARM64 release, under the MIT license. Its notice is retained in
`openpilot/starpilot/galaxy/bin/LICENSE.hev-socks5-tunnel`; the adjacent SHA-256
file pins the downloaded artifact. The Android companion uses the Kotlin
standard library (Apache-2.0) and the Gradle wrapper (Apache-2.0); no third-party
UI framework is bundled.
## Galaxy Bluetooth companion source snapshot
The Galaxy Bluetooth phone bridge and iOS app from https://github.com/StarPilotHQ/StarPilot
(natehuby76, PRs #224/#225) are included under `openpilot/starpilot/galaxy_bluetooth/`
and `openpilot/starpilot/companion/ios/`, with their license files (`UPSTREAM-LICENSE`, `openpilot/starpilot/companion/ios/UPSTREAM-GALAXY-LICENSE`).
The bridge runs on openpilot's Python with PyCryptodome 3.23.0 (BSD/public-domain
components, from opendbc). Its other dependencies are vendored unmodified, as
pure-Python sources, in `openpilot/starpilot/galaxy_bluetooth/vendor/`:
dbus-next 0.2.3 (MIT), ifaddr 0.2.0 (MIT) and Zeroconf 0.151.3
(LGPL-2.1-or-later). Their license texts are in `vendor/licenses/`, and
`vendor/VENDOR.json` records each PyPI source file and its SHA-256. Zeroconf is
kept as separate, unmodified source files that can be replaced with another
compatible version, as the LGPL requires.
## Subaru angle support from jacobw
The Subaru angle implementation includes work from Jacob Waller's `jul-angle-based` openpilot/opendbc branches and their upstream contributors. See [CREDITS.md](CREDITS.md#subaru-angle-steering-from-jacob-wallers-fork) and `opendbc_repo/opendbc/car/subaru/ORIGIN_HISTORY.tsv` for pinned sources, original authors and titles. The source repositories publish the comma MIT license; the complete applicable notice remains in the project `LICENSE` and `opendbc_repo/LICENSE`. StarPilot's adaptations preserve additional native and caller safety guards.
-8
View File
@@ -1,8 +0,0 @@
#!/usr/bin/env bash
set -euo pipefail
ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PYTHON_BIN="${HEATDEATH_PYTHON:-python3}"
if [[ -z "${HEATDEATH_PYTHON:-}" && -x /usr/local/venv/bin/python3 ]]; then
PYTHON_BIN=/usr/local/venv/bin/python3
fi
exec "$PYTHON_BIN" -B "$ROOT_DIR/tools/heatdeath/heatdeath.py" "$@"
+1 -1
View File
@@ -10,4 +10,4 @@ jetlink: run openpilot's large driving models on an attached Jetson.
# so does the release check (macos/scripts/check-version.sh). The comma runs
# jetlink from a checkout, not an install, so this is also all it has. The Swift
# reads it from Pinned.swift: run JetlinkKit/Scripts/make_pins.py after a bump.
__version__ = '0.8.12'
__version__ = '0.8.7'
+6 -20
View File
@@ -224,16 +224,12 @@ class JetlinkClient:
# -- handshake ------------------------------------------------------------
def hello(self, timeout: float = 5.0, pick: dict | None = None) -> dict:
def hello(self, timeout: float = 5.0) -> dict:
"""Introduce this client. The server starts its session over on a hello,
so this is also how a new owner of the gadget takes over one the server
never saw end; see Session.greet in JetlinkServer. `pick` is the comma's
own big-model pick and its age, {ref, sha256, nbytes, name, age_s}; the
answer's `pick` is the newer of it and the server's (PickStore)."""
never saw end; see Session.greet in JetlinkServer."""
seq = self._next_seq()
client = {'nonce': self.nonce, 'name': self.name}
if pick is not None:
client['pick'] = pick
try:
link = self.t.link_info()
except Exception:
@@ -305,8 +301,7 @@ class JetlinkClient:
frame_skip: int = DEFAULT_FRAME_SKIP,
progress: ProgressFn | None = None,
build_timeout: float = 900.0,
should_stop: StopFn | None = None,
fetch: bool = False, ref: str | None = None) -> ModelSpec:
should_stop: StopFn | None = None) -> ModelSpec:
"""Make the server ready to run this model, uploading and building if needed.
Blocks until ready or the build fails, and returns the spec the server
@@ -314,12 +309,8 @@ class JetlinkClient:
parser rejects an export (tinygrad and the org.tinygrad domain) still runs.
`onnx_path` None means the caller cannot upload (modeld) and a missing
engine is EngineMissing. `fetch` asks a server that lacks the model to
download it itself (state downloading, stage download) rather than answer
need_upload; one that cannot, or is too old to, answers need_upload as
before. `ref` is the catalog ref the model is known by.
`progress(stage, frac, msg)` has stage in
download/upload/patch/parse/build/load. `should_stop` is polled during long waits.
engine is EngineMissing. `progress(stage, frac, msg)` has stage in
upload/patch/parse/build/load. `should_stop` is polled during long waits.
"""
self.progress_cb = progress
self._should_stop = should_stop or (lambda: False)
@@ -327,12 +318,7 @@ class JetlinkClient:
self._engine_state = None
seq = self._next_seq()
request = {'sha256': sha256, 'nbytes': nbytes, 'frame_skip': frame_skip}
if fetch:
request['fetch'] = True
if ref:
request['ref'] = ref
self.t.send_json(P.Msg.ENGINE_REQ, seq, request)
self.t.send_json(P.Msg.ENGINE_REQ, seq, {'sha256': sha256, 'nbytes': nbytes, 'frame_skip': frame_skip})
resp = json.loads(bytes(self._expect(P.Msg.ENGINE_RESP, seq, 60.0).payload))
self._engine_state = resp
log.info("server engine state: %s (%s)", resp['state'], resp.get('detail', ''))
+1 -1
View File
@@ -55,7 +55,7 @@ POLL = 0.5
# what a borrower passes on of the server's hello (Loan.note_server): the owner
# never speaks the protocol, and sleep_after is how it knows whether letting
# go of the gadget lets the Jetson sleep. The rest is for its status record
SERVER_FIELDS = ('protocol', 'device', 'backend', 'runtime_version', 'trt_version', 'sleep_after', 'pick', 'fetches')
SERVER_FIELDS = ('protocol', 'device', 'backend', 'runtime_version', 'trt_version', 'sleep_after')
def _send(conn: socket.socket, msg: dict) -> None:
+3 -36
View File
@@ -45,23 +45,15 @@ class Keys:
offroad: str # BOOL: is the car parked (manager's IsOffroad)
progress: str # JSON {stage, frac, msg, drops}: provisioning and join progress
spec: str # JSON: the built model's spec and whether its engine is built
pointers: str # JSON: catalog ref, or a hash-named pick's sha256 -> {oid, size}
pointers: str # JSON: catalog ref -> {oid, size}
# sunnypilot's model manager: the big-model pick, JSON {ref, displayName},
# and the big-model catalog, JSON {bundles}. Without one both are None, and
# jetlink runs its own default big model, or the one picked on the server.
# A fork with a picker of its own and no catalog (StarPilot) declares only
# big_model, and may name its pick by the ONNX's hash, {sha256,
# displayName}; a newer pick made on the server is written into it
# jetlink runs its own default big model
big_model: str | None = None
catalog: str | None = None
# BOOL: an iPhone on a direct cable is asked to charge from the comma
# (comma.port). Off when unset, and without the key
charge_phone: str | None = None
# STRING: where the model manager takes a pick by its ref and stores it in
# big_model (sunnypilot's ModelManager_DownloadRef). A newer pick made on
# the server is written there, so the comma's own list shows it; without
# the key it drives all the same
select: str | None = None
@dataclass(frozen=True)
@@ -160,16 +152,6 @@ class ModelSide(WorkerSide, Protocol):
frame thread at a hand-back, so it zeroes the history in place and
allocates and compiles nothing; warp.reset_queues makes one."""
def model_warp(self, small: Any, cam_w: int, cam_h: int, model_w: int, model_h: int) -> FrameWarp | None:
"""Optional (OPTIONAL): the warp the link sends frames through, warmed,
or None for openpilot's driving warp pickle at warp_path (warp.Warp). For
a fork whose runtime cannot load that pickle, typically with its small
model's own warp. Asked once on modeld's main thread before the frame
loop, after the small model's warmup; raising keeps the drive on the
small model, as a pickle that does not load does. The offroad checks
still look for the pickle (Warps.built): only modeld has a small model
to ask, so warp_path must name a file either way."""
class Openpilot(ModelSide, Protocol):
"""The whole adapter: one object implements every side."""
@@ -216,28 +198,13 @@ class JoinedModel(Protocol):
"""Let go of the link at modeld's exit."""
class FrameWarp(Protocol):
"""What an adapter's model_warp returns, warp.Warp's shape, run on modeld's
frame thread. Only one of the small and the large model runs a frame, so a
warp that shares the small model's JIT and buffers is never in use by both.
On a comma, a warp that reads its GPU output back moves it first with
warp.make_coherent, before the warp's JIT first runs."""
output: Any # the warped frame, (2, 6, model_h/2, model_w/2) uint8 as bytes: read after wait(), until the next start()
def start(self, frame: int, big_frame: int, tfm: Any, big_tfm: Any) -> None:
"""Warp the camera buffers at these addresses under their 3x3 transforms."""
def wait(self) -> None:
"""Return once `output` holds what start() warped."""
# The members of each protocol an implementation may lack: jetlink reads them
# with getattr and a fallback. conformance() passes an object without one and
# holds one with it to its signature, and adding one keeps API. Kept out of
# the protocols, where a name would be a member itself; a type checker still
# asks for these, as typing has no optional member
OPTIONAL: dict[type, tuple[str, ...]] = {
ModelSide: ('small_reset', 'model_warp'),
ModelSide: ('small_reset',),
SmallModel: ('desire_key', 'numpy_inputs', 'lat_delay', 'PLANPLUS_CONTROL'),
JoinedModel: ('get_action_from_model', 'constants', 'LAT_SMOOTH_SECONDS', 'LONG_SMOOTH_SECONDS', 'lat_delay'),
}
+2 -8
View File
@@ -334,7 +334,7 @@ class JoiningModelState:
self._demote(BEHIND)
elif self._active is not self._small and self._frame_drop_ratio > DROP_LIMIT:
# modeld is behind the large model; this frame is the small model's
self._log.warning("jetlink: modeld dropped %.2f %% of camera frames behind the large model, " +
self._log.warning("jetlink: modeld dropped %.2f %% of camera frames behind the large model, "
"the small model drives from this one", self._frame_drop_ratio * 100)
self._demote(BEHIND)
self._maybe_swap()
@@ -745,7 +745,6 @@ def join(parts, cam_w: int, cam_h: int, small) -> JoiningModelState:
link = links.Link(parts.log)
def prepare():
from jetlink.openpilot.interface import FrameWarp, conformance
from jetlink.openpilot.warp import Warp, prepare_reset
# the gadget first, so the Jetson enumerates while the warp loads. Left to
# the join thread the bind lands ~3 s later, behind the small model's
@@ -760,12 +759,7 @@ def join(parts, cam_w: int, cam_h: int, small) -> JoiningModelState:
try:
# the fork's own reset of its small model, else jetlink's from its shape
ready['reset_small'] = getattr(op, 'small_reset', lambda small: None)(small) or prepare_reset(small)
# the fork's own warp, else openpilot's driving warp pickle
warp = getattr(op, 'model_warp', lambda *args: None)(small, cam_w, cam_h, *geometry)
if warp is None:
warp = Warp(parts.warps.load(cam_w, cam_h, *geometry), face.frame_size(cam_w, cam_h))
elif problems := conformance(warp, FrameWarp):
raise RuntimeError(f"the adapter's model_warp is not a warp: {', '.join(problems)}")
warp = Warp(parts.warps.load(cam_w, cam_h, *geometry), face.frame_size(cam_w, cam_h))
except Exception:
link.close()
raise
+11 -25
View File
@@ -43,8 +43,6 @@ PRESENT_TIMEOUT = 5.0
# hardware; the ceiling is only there so a server that has stopped answering
# does not hold the caller for the rest of the day.
BUILD_TIMEOUT = 1800.0
# and on top of that, a server downloading the model itself: 1.75 GB at 1 MB/s
FETCH_TIMEOUT = 1800.0
class ModelMissing(RuntimeError):
@@ -228,15 +226,12 @@ def identity(parts, entry: dict) -> tuple[str, int]:
"""The picked model's sha256 and byte count, from the catalog model's LFS
pointer, so the comma can name the model without holding or hashing the
ONNX. Looked up once per model ever and kept in a param: the one part of
provisioning that needs the internet. A model picked by its hash alone is
only sized."""
provisioning that needs the internet."""
sha256, nbytes = entry.get('oid'), entry.get('size')
if sha256 and nbytes:
return sha256, int(nbytes)
parts.progress.report('connect', 0.0, 'finding model', code='finding_model')
if entry.get('ref'):
return parts.models.resolve_pointer(entry['ref'])
return parts.models.resolve_size(sha256)
return parts.models.resolve_pointer(entry['ref'])
# What has already been hashed in this process, keyed on the file as it was
@@ -283,27 +278,21 @@ def verified_upload(log, model_path: Path | None, sha256: str, nbytes: int) -> P
def ensure(parts, client, sha256: str, nbytes: int, model_path: Path | None, *,
progress=None, should_stop=None, build_timeout: float = BUILD_TIMEOUT, ref: str | None = None,
fetch: bool = True):
progress=None, should_stop=None, build_timeout: float = BUILD_TIMEOUT):
"""Make the server ready for this model and remember what it answered.
Asks without the file first: the server answers from the sha alone when it
has the model, which is every parked poll and every join. Without the file
here either, the server is asked to download the model itself, which only
the Jetson needs. EngineMissing means the Jetson has neither the plan nor
the bytes and could not get them, and neither has the caller. `fetch` False
never asks for the download: a stand-in is a model the server has. `ref`,
the catalog's name for the model, goes with a download."""
has the model, which is every parked poll and every join. EngineMissing means
the Jetson has neither the plan nor the bytes, and neither has the caller."""
from jetlink.client import EngineMissing
fetch = fetch and model_path is None
ask = functools.partial(client.ensure_engine, sha256, nbytes, progress=progress, should_stop=should_stop)
ask = functools.partial(client.ensure_engine, sha256, nbytes, progress=progress,
build_timeout=build_timeout, should_stop=should_stop)
try:
spec = ask(onnx_path=None, fetch=fetch, ref=ref if fetch else None,
build_timeout=build_timeout + (FETCH_TIMEOUT if fetch else 0.0))
spec = ask(onnx_path=None)
except EngineMissing:
upload = verified_upload(parts.log, model_path, sha256, nbytes)
if upload is None:
raise
spec = ask(onnx_path=upload, build_timeout=build_timeout)
spec = ask(onnx_path=upload)
parts.spec.store(spec)
return spec
@@ -357,14 +346,11 @@ def open_link(parts, link: Link, should_stop=None):
# booting; both resolve on their own
client = connect_patiently(link)
try:
hello = parts.models.heard(client.hello(timeout=10.0, pick=parts.models.hello_pick()))
hello = client.hello(timeout=10.0)
parts.log.warning("jetlink: %s trt %s, engine %s, loaded %s",
hello.get('device'), hello.get('trt_version'),
hello.get('engine_state'), str(hello.get('loaded'))[:16])
link.note_server(hello)
# a newer pick on the server drives, and is ours from now on
parts.models.adopt()
selected = parts.models.selected_model() or selected
sha256, nbytes = identity(parts, selected)
path = parts.models.shipped_model_path()
built = parts.spec.ready_spec()
@@ -384,7 +370,7 @@ def open_link(parts, link: Link, should_stop=None):
# server that restarted reloads from the plan cache, 13 to 25 s; one
# that has never seen this model builds it, 102 to 294 s
spec = ensure(parts, client, sha256, nbytes, path, progress=parts.progress.report_with_eta,
should_stop=should_stop, ref=selected.get('ref'), fetch=standin is None)
should_stop=should_stop)
client.deadline = INFERENCE_TIMEOUT
return client, spec
except EngineMissing as e:
@@ -157,9 +157,9 @@ class JetlinkModelState:
# model manager key off this flag
self.chestnut = True
# a warp.Warp or the adapter's model_warp, loaded and warmed ahead: its
# first call links the JIT, and this runs on modeld's frame thread. Frames
# go out of its output as they are, over either transport
# a warp.Warp, loaded and warmed ahead: its first call links the JIT, and
# this runs on modeld's frame thread. Frames go out of its output as they
# are, over either transport
self.warp = warp
self.input_shapes = spec.input_shapes
@@ -305,9 +305,9 @@ class JetlinkModelState:
# over the cable: how frames go, how many never came back, and what the
# kernel dropped on the way in (softnet), since the link came up
drops = getattr(self.client.t, 'net_drops', lambda: None)()
cable = (f"; frames {'as datagrams' if self.client.t.datagrams else 'on the stream'}, " +
cable = (f"; frames {'as datagrams' if self.client.t.datagrams else 'on the stream'}, "
f"{self.client.frames_lost} lost, net drops {drops}" if drops is not None else '')
self._log.warning("jetlink: frame %d warp %.1f data %.1f send %.1f wait %.1f ms%s; " +
self._log.warning("jetlink: frame %d warp %.1f data %.1f send %.1f wait %.1f ms%s; "
"server gpu %.1f queue %.1f total %.1f ms; ffs maxima prepare %.1f read_wait %.1f handoff %.1f ms%s",
self._frame_id, (frame.t1 - frame.t0) * 1e3, (frame.t2 - frame.t1) * 1e3,
(frame.sent - frame.t2) * 1e3, (t4 - waiting_from) * 1e3,
+28 -196
View File
@@ -16,25 +16,16 @@ export, and jetlink's registry follows that to comma's model repo; see
jetlink.registry.lfs.
Without a model manager (Keys.big_model and Keys.catalog None) there is no
pick and no catalog, and the large model is the one picked on the server, else
jetlink's own default, named by its ref: its pointer resolves from the ref as
any pick's does.
A fork with a picker of its own but no catalog jetlink reads (Keys.big_model
without Keys.catalog, StarPilot's) may name its pick by the ONNX's sha256
instead of a ref, which is all its catalog knows of a model. Its size is looked
up from comma's LFS servers once (resolve_size). With no catalog no model
manager owns the slot either, so jetlink writes a newer pick from the server
into it itself, and the fork's picker shows what drives.
pick and no catalog, and the large model is jetlink's own default, named by its
ref: its pointer resolves from the ref as any pick's does.
"""
from __future__ import annotations
import os
import re
import time
from pathlib import Path
from jetlink.registry.catalog import DEFAULT_BIG_MODEL_NAME, DEFAULT_BIG_MODEL_REF, is_ref, is_sha256
from jetlink.registry.catalog import DEFAULT_BIG_MODEL_NAME, DEFAULT_BIG_MODEL_REF
POINTER_TIMEOUT = 10.0
_REF = re.compile(r'[0-9a-f]{40}')
@@ -48,32 +39,13 @@ INDEX_TTL = 2.0
# on from the .part the last left, so a stall costs the wait, not the bytes
# (lfs.lfs_download)
DOWNLOAD_RETRY_DELAYS = (5.0, 15.0, 30.0, 60.0, 120.0)
# server_pick() before this process has heard a hello
_UNHEARD = object()
def _dated(pick) -> dict | None:
"""A server's pick as its hello carries it, dated by this clock:
{ref, sha256, nbytes, name, at}. None for none, or one naming no model."""
if not isinstance(pick, dict) or not isinstance(pick.get('age_s'), (int, float)):
return None
ref = pick['ref'] if is_ref(pick.get('ref')) else None
sha256 = pick['sha256'] if is_sha256(pick.get('sha256')) else None
if ref is None and sha256 is None:
return None
return {'ref': ref, 'sha256': sha256, 'nbytes': pick.get('nbytes'), 'name': pick.get('name'),
'at': time.time() - float(pick['age_s'])}
class Models:
def __init__(self, op):
self.op = op
self._index_cache: tuple[float, list[dict], dict[str, dict]] | None = None
self._slot_cache: tuple[float, dict | None, float | None] | None = None
# the pick of the last hello this process heard, and the owner's record
# of the last hello any process heard
self._heard: dict | None | object = _UNHEARD
self._record_cache: tuple[float, dict | None] | None = None
self._slot_cache: tuple[float, dict | None] | None = None
def catalog(self) -> list[dict]:
"""sunnypilot's big-model bundles as {name, ref}, newest first, as the model
@@ -105,28 +77,13 @@ class Models:
def resolve_pointer(self, ref: str) -> tuple[str, int]:
"""The oid and size behind a catalog model, fetched the first time and kept for good."""
return self._resolve(ref, self.fetch_pointer)
def fetch_size(self, sha256: str) -> tuple[str, int]:
"""The ONNX with this hash and its byte count, from the LFS servers a
download asks."""
from jetlink.registry.lfs import fetch_size as registry_fetch_size
pointer = registry_fetch_size(sha256, self.lfs_endpoints(), timeout=POINTER_TIMEOUT)
return pointer.oid, pointer.size
def resolve_size(self, sha256: str) -> tuple[str, int]:
"""A model picked by its hash, sized the first time and kept for good with
the catalog's pointers, under the hash."""
return self._resolve(sha256, self.fetch_size)
def _resolve(self, key: str, fetch) -> tuple[str, int]:
known = self.pointers()
if key in known:
return known[key]['oid'], int(known[key]['size'])
oid, size = fetch(key)
known[key] = {'oid': oid, 'size': size}
if ref in known:
return known[ref]['oid'], int(known[ref]['size'])
oid, size = self.fetch_pointer(ref)
known[ref] = {'oid': oid, 'size': size}
self._keep_pointers(known)
self.op.log.warning("jetlink: %s is %s, %d MB", key[:10], oid[:16], size >> 20)
self.op.log.warning("jetlink: %s is %s, %d MB", ref[:10], oid[:16], size >> 20)
return oid, size
def _keep_pointers(self, known: dict[str, dict]) -> None:
@@ -135,11 +92,9 @@ class Models:
self._index_cache = None
@staticmethod
def _row(name: str, ref: str | None, known: dict[str, dict], sha256: str | None = None) -> dict:
"""A model as a catalog row, by its ref's pointer, else by its hash, sized
once resolve_size has looked it up."""
p = known.get(ref) or known.get(sha256) or {}
return {'name': name, 'ref': ref, 'oid': p.get('oid') or sha256, 'size': int(p['size']) if p.get('size') else None}
def _row(name: str, ref: str, known: dict[str, dict]) -> dict:
p = known.get(ref) or {}
return {'name': name, 'ref': ref, 'oid': p.get('oid'), 'size': int(p['size']) if p.get('size') else None}
def _index(self) -> tuple[list[dict], dict[str, dict]]:
"""The catalog's rows and the pointers behind them, read together once per INDEX_TTL."""
@@ -155,27 +110,18 @@ class Models:
return self._index()[0]
def selected_slot(self) -> dict | None:
"""The big-model slot's pick as {name, ref, sha256}, from the raw param
rather than a parsed bundle, and memoised with when it was made
(picked_at): the UI asks every frame. It names its model by the catalog's
ref, by the ONNX's sha256 (a fork whose catalog knows only that), or by
both; the one it lacks is None."""
"""The big-model slot's pick as {name, ref}, from the raw param rather than a
parsed bundle, and memoised: the UI asks every frame."""
now = time.monotonic()
if self._slot_cache is not None and now - self._slot_cache[0] < INDEX_TTL:
return self._slot_cache[1]
key = self.op.keys.big_model
slot = self.op.get(key) if key else None
slot = slot if isinstance(slot, dict) else {}
ref = slot['ref'] if isinstance(slot.get('ref'), str) and slot['ref'] else None
sha256 = slot['sha256'] if is_sha256(slot.get('sha256')) else None
pick, at = None, None
if ref or sha256:
pick = {'name': str(slot.get('displayName') or (ref or sha256)[:10]), 'ref': ref, 'sha256': sha256}
try:
at = os.stat(Path(self.op.params_dir()) / key).st_mtime
except OSError:
pass
self._slot_cache = (now, pick, at)
ref = slot.get('ref') if isinstance(slot, dict) else None
pick = None
if isinstance(ref, str) and ref:
pick = {'name': str(slot.get('displayName') or ref[:10]), 'ref': ref}
self._slot_cache = (now, pick)
return pick
def default_model(self) -> dict | None:
@@ -196,129 +142,12 @@ class Models:
return _TRAILING_DATE.sub('', model['name']) if model else None
def selected_model(self) -> dict | None:
"""The model picked last, here or on the server: the slot's pick, listed
in the catalog or not (a ref is enough to find its pointer), unless the
server's last hello named a newer one. With neither, default_model()."""
if (theirs := self._newer_server_pick()) is not None:
return self._server_row(theirs)
if (own := self.selected_slot()) is not None:
return self._own_row(own)
"""The slot's pick, listed in the catalog or not: a ref is enough to find its
pointer. With no pick, default_model()."""
if (pick := self.selected_slot()) is not None:
return self._row(pick['name'], pick['ref'], self._index()[1])
return self.default_model()
def _own_row(self, own: dict) -> dict:
return self._row(own['name'], own['ref'], self._index()[1], own['sha256'])
# -- picks on both ends -----------------------------------------------------
# A pick is made on either end: in the comma's list, or on the server (its
# web page, an app's Use Model). Each hello carries the comma's own pick and
# how long ago it was made, and the server answers with the newer of that
# and its own (PickStore in JetlinkServer). The answer is kept with the rest
# of the hello (gadget.SERVER, through the owner), dated by this clock, and
# selected_model() takes whichever pick is newer; so a model picked on the
# server drives without being picked here too, and one picked here goes to
# the server at the next hello.
def picked_at(self) -> float | None:
"""When the slot was last written, by this clock: when the pick was made.
None with no pick of our own, or no date for it."""
return self._slot_cache[2] if self.selected_slot() is not None and self._slot_cache else None
def hello_pick(self) -> dict | None:
"""Our own pick, for the hello: {ref, sha256, nbytes, name, age_s}, the
pointer where it is resolved already (no network here). None with nothing
picked here, or no date for it: the server's pick, if any, stands."""
own, at = self.selected_slot(), self.picked_at()
if own is None or at is None:
return None
row = self._own_row(own)
return {'ref': row['ref'], 'sha256': row['oid'], 'nbytes': row['size'], 'name': row['name'],
'age_s': round(max(0.0, time.time() - at), 1)}
def heard(self, hello: dict) -> dict:
"""The server's hello with its `pick` dated by this clock (_dated), which
is how the owner keeps it (lending.SERVER_FIELDS) and server_pick() reads
it. This process goes by it at once, whatever the owner does with it."""
self._heard = _dated(hello.get('pick'))
return {**hello, 'pick': self._heard} if self._heard is not None else hello
def server_pick(self) -> dict | None:
"""The pick the server last answered a hello with, {ref, sha256, nbytes,
name, at}, or None: a server too old to say, or one with no pick. What
this process heard last, else the owner's record of the last hello: the
UI says no hello, and reads it every frame."""
if self._heard is not _UNHEARD:
return self._heard
now = time.monotonic()
if self._record_cache is None or now - self._record_cache[0] >= INDEX_TTL:
from jetlink.comma import gadget
pick = (gadget.read_record(gadget.SERVER) or {}).get('pick')
self._record_cache = (now, pick if isinstance(pick, dict) and isinstance(pick.get('at'), (int, float)) else None)
return self._record_cache[1]
def _newer_server_pick(self) -> dict | None:
"""The server's last pick, when it is another model than ours and was
picked after it, or we have none."""
theirs, own = self.server_pick(), self.selected_slot()
if theirs is None or (own is not None and (self._same(theirs, self._own_row(own)) or
theirs['at'] <= (self.picked_at() or 0.0))):
return None
return theirs
@staticmethod
def _same(pick: dict, row: dict) -> bool:
"""One model: by the catalog ref where both have one, since two refs can
share one export, else by the hash. The server's PickStore.sameModel."""
if pick['ref'] and row['ref']:
return pick['ref'] == row['ref']
return bool(pick['sha256']) and pick['sha256'] == row['oid']
def _server_row(self, pick: dict) -> dict:
"""The server's pick as a catalog row: ours where we list it, with the
server's oid and size, which name the bytes it has."""
listed = next((m for m in self.model_index() if pick['ref'] and m['ref'] == pick['ref']), None)
row = self._row(listed['name'] if listed else pick.get('name') or (pick['ref'] or pick['sha256'])[:16],
pick['ref'], self._index()[1], pick['sha256'])
if pick['sha256'] and pick.get('nbytes'):
row['oid'], row['size'] = pick['sha256'], int(pick['nbytes'])
return row
def adopt(self) -> None:
"""Keep the server's pointer for its pick, by ref and by hash, so naming
the model here needs no lookup; and make a newer pick from the server
ours. With a catalog, ask the model manager for it (Keys.select), so the
comma's own list shows what drives: only a model the catalog lists, which
is all the model manager takes; any other drives all the same
(selected_model). Without one, no model manager owns the slot, so the
pick is written into it, whatever the model. Never raises."""
try:
if (theirs := self.server_pick()) is None:
return
known = self.pointers()
if theirs['sha256'] and theirs.get('nbytes'):
pointer = {'oid': theirs['sha256'], 'size': int(theirs['nbytes'])}
missing = {k: pointer for k in (theirs['ref'], theirs['sha256']) if k and k not in known}
if missing:
self._keep_pointers({**known, **missing})
if self._newer_server_pick() is None:
return
model, keys = self._server_row(theirs), self.op.keys
if keys.catalog is None:
if keys.big_model:
self.op.log.warning("jetlink: %s was picked on the server, picking it here too", model['name'])
slot = {k: v for k, v in (('displayName', model['name']), ('ref', model['ref']), ('sha256', model['oid'])) if v}
self.op.put(keys.big_model, slot, block=True)
self._slot_cache = None
return
# a download the user asked for that the model manager has not taken
# yet is left alone: the next hello asks again
key = keys.select
if key and model['ref'] and self.op.get(key) is None and any(m['ref'] == model['ref'] for m in self.model_index()):
self.op.log.warning("jetlink: %s was picked on the server, picking it here too", model['name'])
self.op.put(key, model['ref'])
self._slot_cache = None
except Exception:
self.op.log.exception("jetlink: could not take the server's pick")
def selected_model_name(self) -> str | None:
selected = self.selected_model()
return selected['name'] if selected else None
@@ -398,8 +227,11 @@ class Models:
def _fetch_once(self, pointer, dest: Path, progress, should_stop) -> Path:
from jetlink.registry.catalog import NetworkError
from jetlink.registry.lfs import lfs_download, lfs_hrefs
for endpoint, href in lfs_hrefs(self.lfs_endpoints(), pointer):
from jetlink.registry.lfs import lfs_download, lfs_resolve
for endpoint in self.lfs_endpoints():
href = lfs_resolve(endpoint, pointer)
if href is None:
continue
self.op.log.warning("jetlink: fetching the large model (%d MB) from %s", pointer.size >> 20, endpoint)
return lfs_download(href, pointer, dest, progress=progress, should_stop=should_stop)
raise NetworkError(f"no LFS server has {pointer.oid[:16]}")
+32 -53
View File
@@ -126,8 +126,10 @@ class ProvisioningRun:
return path
def needs_download(self) -> bool:
"""Could the Jetson need the picked model from the comma? Only while its
engine is not known to be built and the file is not here."""
"""Does the comma have to fetch the picked model before a Jetson can build
it? Only while its engine is not known to be built and the file is not here.
Asked without the Jetson: a download needs only the internet, and a car
whose Jetson goes off with the ignition has no Jetson while parked."""
parts = self.parts
entry = parts.models.selected_model()
if entry is None:
@@ -138,17 +140,12 @@ class ProvisioningRun:
return parts.models.shipped_model_path() is None
def provision(self) -> bool:
"""Make the Jetson ready for the picked model; a host is attached. The
hello settles which pick that is, the comma's or a newer one made on the
server. A server without the model downloads it itself; only one that
cannot (no internet, or too old) gets the bytes from the comma, fetched
here then."""
"""Make the Jetson ready for the selected model; a host is attached. run()
has fetched the file already unless the spec record said the model was
built; a server that lost it since asks for the bytes, and they are
fetched then."""
from jetlink.client import EngineMissing
parts = self.parts
parts.progress.report('connect', 0.0, 'connecting', code='connecting')
hello = self.hello()
self.log.warning("jetlink: server %s trt %s", hello.get('device'), hello.get('trt_version'))
parts.models.adopt()
entry = parts.models.selected_model()
if entry is None:
# no catalog yet; not an error
@@ -157,24 +154,27 @@ class ProvisioningRun:
return False
sha256, nbytes = link.identity(parts, entry)
# only needed if the server turns out not to have this model and cannot
# get it; None is a legitimate state here, see EngineMissing below
# only needed if the server turns out not to have this model; None is a
# legitimate state here, see EngineMissing below
model_path = parts.models.shipped_model_path()
self.log.warning("jetlink: provisioning %s (%d MB, sha %s)",
entry.get('name', sha256[:16]), nbytes >> 20, sha256[:16])
parts.progress.report('connect', 0.0, 'connecting', code='connecting')
def ensure(path):
return link.ensure(parts, self.client, sha256, nbytes, path, progress=parts.progress.report_with_eta,
should_stop=lambda: self.stop, ref=entry.get('ref'))
should_stop=lambda: self.stop)
hello = self.hello()
self.log.warning("jetlink: server %s trt %s", hello.get('device'), hello.get('trt_version'))
try:
spec = ensure(model_path)
except EngineMissing:
# the server has nothing to build from and could not download it, and
# neither have we: fetch the model and hand it over in this run. The
# owner lends the link for the whole run; leaving after the download
# would put the build a WORKER_BACKOFF later
# the server has nothing to build from, and neither have we: fetch the
# model and hand it over in this run. The owner lends the link for the
# whole run; leaving after the download would put the build a
# WORKER_BACKOFF later
if model_path is not None or (model_path := self.fetch_model()) is None:
raise
# a download of minutes can outlast the session; a hello starts a new one
@@ -186,35 +186,16 @@ class ProvisioningRun:
return True
def hello(self) -> dict:
"""Say hello with our pick, and pass the answer on to the owner, which
needs its sleep_after to decide whether letting go of the gadget is worth
what it costs, never speaks the protocol to learn it, and keeps the
server's pick and whether it downloads for the comma (Models.heard)."""
models = self.parts.models
hello = models.heard(self.client.hello(timeout=10.0, pick=models.hello_pick()))
"""Say hello, and pass the answer on to the owner, which needs its
sleep_after to decide whether letting go of the gadget is worth what it
costs and never speaks the protocol to learn it."""
hello = self.client.hello(timeout=10.0)
if self.loan is not None:
self.loan.note_server(hello)
return hello
# -- the parked car -------------------------------------------------------
def without_jetson(self) -> None:
"""No Jetson came to the bind: a car whose Jetson is switched with the
ignition has none while parked. Only the Jetson needs the model, and one
that can download it gets it itself when it is on; the comma fetches it
now only for a Jetson that cannot (no internet when it was last here, or
too old to say), so the build can start the moment it is."""
if not self.has_work():
return
if self.needs_download():
if server_fetches():
self.parts.progress.report('waiting', 0.0, 'the jetson downloads it when it is on', code='waiting_for_host')
return
if self.fetch_model() is None:
return
self.parts.progress.report('waiting', 0.0, 'downloaded, builds when the jetson is on',
code='downloaded_waiting_host')
def has_work(self) -> bool:
"""Is there a reason to wake the Jetson? Only things the link can fix count."""
spec = self.parts.spec.load()
@@ -278,21 +259,25 @@ class ProvisioningRun:
self.log.warning("jetlink: no warp built for this camera, nothing to provision for")
return True
# Nothing to build, unless a model was picked on the server since: a
# Jetson awake on the bus is asked, which costs a hello and no wake. Not
# a phone's cable, which is there only once the app dials in
if not self.has_work() and not (gadget.host_attached() and gadget.link_kind(self.parts.settings.mode()) == 'usb'):
if not self.has_work():
self.log.warning("jetlink: nothing to provision")
return True
finished = False
try:
# the bytes first while no host is on the cable: a parked car whose
# Jetson is switched with the ignition never has one to wait for. A host
# that is there is asked first, since one with the model built needs
# nothing from the comma; provision() fetches it if the host has not
if self.needs_download() and not gadget.host_attached() and self.fetch_model() is None:
return False
if not self.open_link():
return False
if not self.wait_for_jetson():
self.log.warning("jetlink: no jetson within %.0f s, leaving it for the next run", WAKE_TIMEOUT)
self.close_link()
self.without_jetson()
if self.parts.models.shipped_model_path() is not None:
self.parts.progress.report('waiting', 0.0, 'downloaded, builds when the jetson is on',
code='downloaded_waiting_host')
return False
finished = self.provision()
except Exception:
@@ -303,12 +288,6 @@ class ProvisioningRun:
return finished
def server_fetches() -> bool:
"""Did the server the comma last spoke to say it downloads a model itself
(its hello's `fetches`, as the owner keeps it)? No for one too old to say."""
return (gadget.read_record(gadget.SERVER) or {}).get('fetches') is True
def main(argv: list[str] | None = None) -> None:
"""One provisioning round over the fork's adapter, as the owner starts it.
Exits 0 when nothing is left to do, and 1 when the owner should try again."""
+5 -11
View File
@@ -31,17 +31,14 @@ PROGRESS_MIN_INTERVAL = 0.25
# what a progress record's `code` may be, for a fork that words the line
# itself; `msg` stays the English one. `args`, where a code has them:
# downloading, download and upload {got_mb, total_mb}, download_stalled
# {retry_s}, reconnecting {why: lost, behind, load_failed or bad_output},
# build {eta_s}. downloading is the comma fetching the model, download the
# server fetching it itself. From download on they are stage names, and the
# server's stages are its own:
# downloading and upload {got_mb, total_mb}, download_stalled {retry_s},
# reconnecting {why: lost, behind, load_failed or bad_output}, build {eta_s}.
# From upload on they are stage names, and the server's stages are its own:
# a server can add one, so a fork falls back to `msg` for a code it does not
# know. A server message with no stage has no code
PROGRESS_CODES = ('waiting_for_host', 'finding_model', 'model_missing', 'ready_waiting_window', 'reconnecting',
'connecting', 'downloading', 'download_stalled', 'download_failed', 'downloaded_waiting_host',
'engine_ready', 'failed', 'download', 'upload', 'patch', 'parse', 'convert', 'compile', 'build',
'load', 'warm')
'engine_ready', 'failed', 'upload', 'patch', 'parse', 'convert', 'compile', 'build', 'load', 'warm')
def estimated_build_seconds(size: int) -> int:
@@ -107,15 +104,12 @@ class Progress:
size. Only the build: the upload reports MB of MB and a connect has nothing
to predict."""
args = None
size = self._size() if self._size is not None and stage in ('build', 'upload', 'download') else None
size = self._size() if self._size is not None and stage in ('build', 'upload') else None
if size and stage == 'build':
left = estimated_build_seconds(size) * max(0.0, 1.0 - frac)
msg, args = _eta(left), {'eta_s': round(left)}
elif size:
args = {'got_mb': int(frac * size) >> 20, 'total_mb': size >> 20}
if stage == 'download' and args:
# the server downloading the model itself: not the comma's own 'downloading'
msg = f"jetson downloading {args['got_mb']} of {args['total_mb']} MB"
self.report(stage, frac, msg, code=stage or None, args=args)
+5 -10
View File
@@ -161,7 +161,7 @@ class Warp:
out = jit.captured.ret.uop.base.buffer
self._device = out.device
if self._device.startswith('QCOM'):
make_coherent(out)
_make_coherent(out)
# the two buffers every frame passes, written in place by start()
self._tensors = {name: Tensor(np.zeros(shape, dtype=dtype), device=device).realize()
for name, (shape, dtype, device) in specs.items()}
@@ -191,15 +191,10 @@ class Warp:
self._replay(self._inputs, {})
def make_coherent(out) -> None:
"""Move a QCOM buffer to KGSL memory flagged IOCOHERENT and write-back, so
the CPU reads it through its cache once the GPU is done (see Warp). Raises
if the kernel keeps either flag back (the allocation's record holds its
answer): write-back memory that is not coherent reads stale frames.
For an adapter's model_warp too. Move a buffer before the first call of
the JIT that writes it: that call links its address into the JIT, which
would keep writing the memory this frees."""
def _make_coherent(out) -> None:
"""Move a QCOM buffer to KGSL memory flagged IOCOHERENT and write-back.
Raises if the kernel keeps either flag back (the allocation's record holds
its answer): write-back memory that is not coherent reads stale frames."""
from tinygrad.device import Device
dev = Device[out.device]
mem = dev._gpu_alloc(out.nbytes, flags=COHERENT_WRITEBACK)
-30
View File
@@ -294,36 +294,6 @@ def lfs_resolve(endpoint: str, pointer: Pointer, timeout: float = CONNECT_TIMEOU
return None
def lfs_hrefs(endpoints, pointer: Pointer, timeout: float = CONNECT_TIMEOUT, opener=None):
"""Each of `endpoints` that has the object, in order, with its download href."""
for endpoint in endpoints:
href = lfs_resolve(endpoint, pointer, timeout=timeout, opener=opener)
if href is not None:
yield endpoint, href
def fetch_size(oid: str, endpoints=LFS_ENDPOINTS, timeout: float = POINTER_TIMEOUT, opener=None) -> Pointer:
"""The pointer for an ONNX known by its oid alone, as a fork whose catalog
names a model by its hash knows it (StarPilot's). comma's LFS servers hand
out a download address for any oid they hold, whatever size the batch asks
for, and the first byte of that download says how many there are. No
server with it is NotFound; one that would not say, a NetworkError."""
opener = opener or urllib.request.urlopen
for endpoint, href in lfs_hrefs(endpoints, Pointer(oid, 1), timeout=timeout, opener=opener):
request = urllib.request.Request(href, headers={'Range': 'bytes=0-0'})
try:
with opener(request, timeout=timeout) as response:
# a server that ignores the range answers 200 with the whole length
total = (response.headers.get('Content-Range') or '').rpartition('/')[2] \
if response.status == 206 else response.headers.get('Content-Length')
except (OSError, ValueError) as e:
raise NetworkError(f"could not size {oid[:16]} at {endpoint}: {e}") from e
if not str(total).isdigit() or int(total) <= 0:
raise NetworkError(f"{endpoint} did not say how big {oid[:16]} is")
return Pointer(oid, int(total))
raise NotFound(f"no LFS server has {oid[:16]}")
def lfs_download(href: str, pointer: Pointer, dest: Path, progress: ProgressFn | None = None,
should_stop: StopFn | None = None, opener=None) -> Path:
"""Stream to a .part file, hashing as we go, and only then take the name.
-5
View File
@@ -1,10 +1,5 @@
#!/usr/bin/env bash
# Device Params must not depend on the platform used to compile native libraries.
if [ -f /AGNOS ] && [ -z "${PARAMS_ROOT:-}" ]; then
export PARAMS_ROOT="/data/params"
fi
export OMP_NUM_THREADS=1
export MKL_NUM_THREADS=1
export NUMEXPR_NUM_THREADS=1
+1 -11
View File
@@ -10,12 +10,7 @@ $Go.import("pfeifer.dev/mapd/cereal/custom");
# DO rename the structs
# DON'T change the identifier (e.g. @0x81c2f05a394cf4af)
struct StarPilotCarControl @0x81c2f05a394cf4af {
# The first three fields are pointer slots mapd does not read.
hudControl @0 :AnyPointer;
steeringLimitInfo @1 :AnyPointer;
navigation @2 :AnyPointer;
phoneGps @3 :StarPilotCarState.Gps; # sourceMonoTime is comma receive time minus the phone's fix age
struct CustomReserved0 @0x81c2f05a394cf4af {
}
struct CustomReserved1 @0xaedffd8f31e7b55d {
@@ -291,11 +286,6 @@ struct MapdOut @0xa4f1eb3323f5f582 {
computedMonoTime @31 :UInt64; # Computation boot-time nanoseconds, not send time.
sourceGeneration @32 :UInt64;
producerSession @33 :UInt64; # Random nonzero process session.
# Data-only preview from the same qualified GPS fix; no controller smoothing.
previewSpeedLimit @34 :Float32;
previewDistance @35 :Float32;
previewBoundaryId @36 :Text;
previewWayId @37 :Int64;
enum SampleStatus {
unknown @0;
+334 -456
View File
@@ -9,137 +9,69 @@ import (
math "math"
)
type StarPilotCarControl capnp.Struct
type CustomReserved0 capnp.Struct
// StarPilotCarControl_TypeID is the unique identifier for the type StarPilotCarControl.
const StarPilotCarControl_TypeID = 0x81c2f05a394cf4af
// CustomReserved0_TypeID is the unique identifier for the type CustomReserved0.
const CustomReserved0_TypeID = 0x81c2f05a394cf4af
func NewStarPilotCarControl(s *capnp.Segment) (StarPilotCarControl, error) {
st, err := capnp.NewStruct(s, capnp.ObjectSize{DataSize: 0, PointerCount: 4})
return StarPilotCarControl(st), err
func NewCustomReserved0(s *capnp.Segment) (CustomReserved0, error) {
st, err := capnp.NewStruct(s, capnp.ObjectSize{DataSize: 0, PointerCount: 0})
return CustomReserved0(st), err
}
func NewRootStarPilotCarControl(s *capnp.Segment) (StarPilotCarControl, error) {
st, err := capnp.NewRootStruct(s, capnp.ObjectSize{DataSize: 0, PointerCount: 4})
return StarPilotCarControl(st), err
func NewRootCustomReserved0(s *capnp.Segment) (CustomReserved0, error) {
st, err := capnp.NewRootStruct(s, capnp.ObjectSize{DataSize: 0, PointerCount: 0})
return CustomReserved0(st), err
}
func ReadRootStarPilotCarControl(msg *capnp.Message) (StarPilotCarControl, error) {
func ReadRootCustomReserved0(msg *capnp.Message) (CustomReserved0, error) {
root, err := msg.Root()
return StarPilotCarControl(root.Struct()), err
return CustomReserved0(root.Struct()), err
}
func (s StarPilotCarControl) String() string {
func (s CustomReserved0) String() string {
str, _ := text.Marshal(0x81c2f05a394cf4af, capnp.Struct(s))
return str
}
func (s StarPilotCarControl) EncodeAsPtr(seg *capnp.Segment) capnp.Ptr {
func (s CustomReserved0) EncodeAsPtr(seg *capnp.Segment) capnp.Ptr {
return capnp.Struct(s).EncodeAsPtr(seg)
}
func (StarPilotCarControl) DecodeFromPtr(p capnp.Ptr) StarPilotCarControl {
return StarPilotCarControl(capnp.Struct{}.DecodeFromPtr(p))
func (CustomReserved0) DecodeFromPtr(p capnp.Ptr) CustomReserved0 {
return CustomReserved0(capnp.Struct{}.DecodeFromPtr(p))
}
func (s StarPilotCarControl) ToPtr() capnp.Ptr {
func (s CustomReserved0) ToPtr() capnp.Ptr {
return capnp.Struct(s).ToPtr()
}
func (s StarPilotCarControl) IsValid() bool {
func (s CustomReserved0) IsValid() bool {
return capnp.Struct(s).IsValid()
}
func (s StarPilotCarControl) Message() *capnp.Message {
func (s CustomReserved0) Message() *capnp.Message {
return capnp.Struct(s).Message()
}
func (s StarPilotCarControl) Segment() *capnp.Segment {
func (s CustomReserved0) Segment() *capnp.Segment {
return capnp.Struct(s).Segment()
}
func (s StarPilotCarControl) HudControl() (capnp.Ptr, error) {
return capnp.Struct(s).Ptr(0)
// CustomReserved0_List is a list of CustomReserved0.
type CustomReserved0_List = capnp.StructList[CustomReserved0]
// NewCustomReserved0 creates a new list of CustomReserved0.
func NewCustomReserved0_List(s *capnp.Segment, sz int32) (CustomReserved0_List, error) {
l, err := capnp.NewCompositeList(s, capnp.ObjectSize{DataSize: 0, PointerCount: 0}, sz)
return capnp.StructList[CustomReserved0](l), err
}
func (s StarPilotCarControl) HasHudControl() bool {
return capnp.Struct(s).HasPtr(0)
}
// CustomReserved0_Future is a wrapper for a CustomReserved0 promised by a client call.
type CustomReserved0_Future struct{ *capnp.Future }
func (s StarPilotCarControl) SetHudControl(v capnp.Ptr) error {
return capnp.Struct(s).SetPtr(0, v)
}
func (s StarPilotCarControl) SteeringLimitInfo() (capnp.Ptr, error) {
return capnp.Struct(s).Ptr(1)
}
func (s StarPilotCarControl) HasSteeringLimitInfo() bool {
return capnp.Struct(s).HasPtr(1)
}
func (s StarPilotCarControl) SetSteeringLimitInfo(v capnp.Ptr) error {
return capnp.Struct(s).SetPtr(1, v)
}
func (s StarPilotCarControl) Navigation() (capnp.Ptr, error) {
return capnp.Struct(s).Ptr(2)
}
func (s StarPilotCarControl) HasNavigation() bool {
return capnp.Struct(s).HasPtr(2)
}
func (s StarPilotCarControl) SetNavigation(v capnp.Ptr) error {
return capnp.Struct(s).SetPtr(2, v)
}
func (s StarPilotCarControl) PhoneGps() (StarPilotCarState_Gps, error) {
p, err := capnp.Struct(s).Ptr(3)
return StarPilotCarState_Gps(p.Struct()), err
}
func (s StarPilotCarControl) HasPhoneGps() bool {
return capnp.Struct(s).HasPtr(3)
}
func (s StarPilotCarControl) SetPhoneGps(v StarPilotCarState_Gps) error {
return capnp.Struct(s).SetPtr(3, capnp.Struct(v).ToPtr())
}
// NewPhoneGps sets the phoneGps field to a newly
// allocated StarPilotCarState_Gps struct, preferring placement in s's segment.
func (s StarPilotCarControl) NewPhoneGps() (StarPilotCarState_Gps, error) {
ss, err := NewStarPilotCarState_Gps(capnp.Struct(s).Segment())
if err != nil {
return StarPilotCarState_Gps{}, err
}
err = capnp.Struct(s).SetPtr(3, capnp.Struct(ss).ToPtr())
return ss, err
}
// StarPilotCarControl_List is a list of StarPilotCarControl.
type StarPilotCarControl_List = capnp.StructList[StarPilotCarControl]
// NewStarPilotCarControl creates a new list of StarPilotCarControl.
func NewStarPilotCarControl_List(s *capnp.Segment, sz int32) (StarPilotCarControl_List, error) {
l, err := capnp.NewCompositeList(s, capnp.ObjectSize{DataSize: 0, PointerCount: 4}, sz)
return capnp.StructList[StarPilotCarControl](l), err
}
// StarPilotCarControl_Future is a wrapper for a StarPilotCarControl promised by a client call.
type StarPilotCarControl_Future struct{ *capnp.Future }
func (f StarPilotCarControl_Future) Struct() (StarPilotCarControl, error) {
func (f CustomReserved0_Future) Struct() (CustomReserved0, error) {
p, err := f.Future.Ptr()
return StarPilotCarControl(p.Struct()), err
}
func (p StarPilotCarControl_Future) HudControl() *capnp.Future {
return p.Future.Field(0, nil)
}
func (p StarPilotCarControl_Future) SteeringLimitInfo() *capnp.Future {
return p.Future.Field(1, nil)
}
func (p StarPilotCarControl_Future) Navigation() *capnp.Future {
return p.Future.Field(2, nil)
}
func (p StarPilotCarControl_Future) PhoneGps() StarPilotCarState_Gps_Future {
return StarPilotCarState_Gps_Future{Future: p.Future.Field(3, nil)}
return CustomReserved0(p.Struct()), err
}
type CustomReserved1 capnp.Struct
@@ -2887,12 +2819,12 @@ type MapdOut capnp.Struct
const MapdOut_TypeID = 0xa4f1eb3323f5f582
func NewMapdOut(s *capnp.Segment) (MapdOut, error) {
st, err := capnp.NewStruct(s, capnp.ObjectSize{DataSize: 128, PointerCount: 7})
st, err := capnp.NewStruct(s, capnp.ObjectSize{DataSize: 112, PointerCount: 6})
return MapdOut(st), err
}
func NewRootMapdOut(s *capnp.Segment) (MapdOut, error) {
st, err := capnp.NewRootStruct(s, capnp.ObjectSize{DataSize: 128, PointerCount: 7})
st, err := capnp.NewRootStruct(s, capnp.ObjectSize{DataSize: 112, PointerCount: 6})
return MapdOut(st), err
}
@@ -3260,54 +3192,12 @@ func (s MapdOut) SetProducerSession(v uint64) {
capnp.Struct(s).SetUint64(104, v)
}
func (s MapdOut) PreviewSpeedLimit() float32 {
return math.Float32frombits(capnp.Struct(s).Uint32(76))
}
func (s MapdOut) SetPreviewSpeedLimit(v float32) {
capnp.Struct(s).SetUint32(76, math.Float32bits(v))
}
func (s MapdOut) PreviewDistance() float32 {
return math.Float32frombits(capnp.Struct(s).Uint32(112))
}
func (s MapdOut) SetPreviewDistance(v float32) {
capnp.Struct(s).SetUint32(112, math.Float32bits(v))
}
func (s MapdOut) PreviewBoundaryId() (string, error) {
p, err := capnp.Struct(s).Ptr(6)
return p.Text(), err
}
func (s MapdOut) HasPreviewBoundaryId() bool {
return capnp.Struct(s).HasPtr(6)
}
func (s MapdOut) PreviewBoundaryIdBytes() ([]byte, error) {
p, err := capnp.Struct(s).Ptr(6)
return p.TextBytes(), err
}
func (s MapdOut) SetPreviewBoundaryId(v string) error {
return capnp.Struct(s).SetText(6, v)
}
func (s MapdOut) PreviewWayId() int64 {
return int64(capnp.Struct(s).Uint64(120))
}
func (s MapdOut) SetPreviewWayId(v int64) {
capnp.Struct(s).SetUint64(120, uint64(v))
}
// MapdOut_List is a list of MapdOut.
type MapdOut_List = capnp.StructList[MapdOut]
// NewMapdOut creates a new list of MapdOut.
func NewMapdOut_List(s *capnp.Segment, sz int32) (MapdOut_List, error) {
l, err := capnp.NewCompositeList(s, capnp.ObjectSize{DataSize: 128, PointerCount: 7}, sz)
l, err := capnp.NewCompositeList(s, capnp.ObjectSize{DataSize: 112, PointerCount: 6}, sz)
return capnp.StructList[MapdOut](l), err
}
@@ -3437,318 +3327,306 @@ func NewMapdOut_GpsSource_List(s *capnp.Segment, sz int32) (MapdOut_GpsSource_Li
return capnp.NewEnumList[MapdOut_GpsSource](s, sz)
}
const schema_b526ba661d550a59 = "x\xda\x94zkp\x1c\xd5\x95\xff9\xdd3\x1a==" +
"\x1a\xdf1\xd8\x92\xc5\xd8\xc6\xc2\xc8A\xc4F\xf8\x1f\xe4" +
"\xe0\x08Y2\xb6U#\xacV\xdb\x16v\xe1\xaa\\M" +
"_\xcd\xb4\xdd\xea\x1ew\xf7H\x1a\x17.\x1b\xc7T\x01" +
"\x7f\xa8@6\x0f'\x156<LU\x92\x85\x84\xcd\xc2" +
"\x96\x97\"\xb5\x84\"U\x86\xc5U\x90\x0a\xa9<\xc8\xe2" +
"\xe4\x0bI\x96\x14\x9b,\xa9\xcdfC\xf5\xd6\xb9=\x8f" +
"\xd6#\x18}\xf1\xa8\x7f\xe7\xf4\xb9\xe7\x9e{\xee\xb9\xe7" +
"w\xdb[N\xb6\xdc\x16\xdb\xda\x96o\x05E{8\xde" +
"\x10\xa4\x8e\x1d\xfa\xb5\xed\x7f\xe74\xa4:18\xd4|" +
"\xa0k\xea\x85\xeb\x9e\x87X\x02\xa0oM\xc3ad\xbd" +
"\x0d\x09P\x83\xef~\x90\xed?\xfc\x9f/\xdf3_+" +
".\xd5\x9a\x1aN \xebjH\x00\xb05\x0d\xef\x02\x06" +
"w\x0e\xbd\xfc\xf9\xc9\xeb\xbeq/\xa4:\x95\xba2`" +
"\x1f&F\x90\xadJ\xd0K\xa9\x84\x13\x03\x0cz_-" +
"\xdd\xf9\xed5\x0f=\x02Z/6\x05/\xdb\xff\xdar" +
"\xf0\x95\xbb\xfe\x0b\xe2H:\x0f\xb5<\x80\xec\xa9\x16\xfa" +
"\xf3\xf1\x96w\x14\xc0\xe0\xef?\xf1~\xc9<q\xf8\xcb" +
"\x90\xbaV\x09\xce\xfc\xe9O\xd7\xf6\xfd\xc7\x1f\xce\x93\xe5" +
"\x9f\xad8\x83\xec\xf7+\xc8\x87\xdf\xae\xf8\x0a`\xb0\xf2" +
"9\xcc\xe7/^\xfa\xfa\x12\xd3\xeaON\"\x1bM\xd2" +
"\xb4z\x7f\x91Q\x87\x13\x85\xc7\x97\xd0\xeaI\x1eF\xb6" +
"CjYj\xdfm\x7f\x9elx\x12\xb4N\\4\xfb" +
"5\xa4\xd7\x9b\x0c_\x99@\xc0\xba_Z'\xb6G\xd4" +
"\xe5\xbc\x1fm\xef@\xf6L\xfb&\x80\xbeW\xdb'\x1a" +
"\x01\x83\xe1\xa1\x97^{\xe6\x9d'\x9fZ\x14\xadC\x1d" +
"g\x90Mw\xd0\x9c\xcc\x8eO\x01\x06\x07\xcek?\xbb" +
"a\xe6\xd2SKx;\xddq\x18\xd9=\x1d\xe4\xedw" +
"~\x91\xfb\xd2\xff\xff\xe6\xfb\xff\xb0\xc8\xde\x91\x8e\xedu" +
"{\xfb\x00\x83#\xcf\xbf\xbb\xf5\xf3\x1f\xbe\xf3\x9d%\xec" +
"\x9d${\x8fH{\x03\xef\xfc\xee\xe4\xe8\xba\x89g\x97" +
"\x1cu\xb2:\xeaE\xcc\xae7s\xf6\x85%\xb4\x8e\x90" +
"\xad\xe3R\xab\xf0\xe2\xdf}Q\xff\xf4\xf0\xf7\x97\xd0\x1a" +
"%[\\j\x9dUo\xbe,n\xdd\xf8\xf2\x12Z;" +
"HK\x93Z\xef\xff\xd3g\xde\xbce\xc7\xd1\x8b\x0bW" +
"E!\xbd\xde\x8e\x95\xc8vt\xc8\xe5\xee\xc8\xd0\xaal" +
"?4Q\xb4\xde\xfa\xc6\xbf-5t'\x0d\xddIF" +
"\xdf8\xf3X\xfe\x7f\x7f\xfe\xe5KK\x0dMZ\x9a\xd4" +
"\xeaz%\xf7\xf6\xdb\xfe\x997\x17\x85\xb8\xb7s'\xb2" +
"\x1d\x9dr\xd8N\x99\x0c\xfd\xfd/>\xfe\xfa\x03\xff\xfd" +
"\x13\xf2R]\x98bkG\x90\xedXK\x0b\xd2\xbf\x96" +
"6\xce\xb6\xec\xf0\xe7\xceM|\xf9\xe7K\x8c\xde\xd5u" +
"\x18\xd9\xd6.\x1a\xbd\xffs\xaf}\xed+\xf1\xaf\xfc;" +
"\x99T\x16\xa8\xb5u\xedD\xd6\xd5%\xf7b\xd7,`" +
"p\xfd\x9b?y\xff\x86]\xcf\xfdq\xd1\x8e9\xd9u" +
"\x14\xd9#R\xf3\xa1\xae<`}\xf3\xcd7\x1bn\xc5" +
"\x7f!\xedK]W\x03\xf4\xbd\xd5\x95H\x00\x06k\x1e" +
"}to\xd3{W}\xb0\x84\xaf\xbf\xec>\x8c\xec\x0f" +
"\xdd\xe4\xeb\x93\xb1\xe2\x87\x9f>\xfb\xd0\xff,\xa1u\x89" +
"\xb4~%\xb56\xff\xa6\xfb\x8ew\xef\xfa\xcc_\x16\xc5" +
"\xf3\xfb\xdd\x93\xc8\xde\xec&'/u\x9f\x02\x0c\x9e\xf0" +
"\xc6.\xbev\xe4\xc9\xbf,tR.z\xdbug\x90" +
"\xad\xbfN\x86\xeb:\x19\xfd\xd4?\xcf\xde\xf7\xfb\xc1\xc9" +
"\xbf.1\xfc\xa3\x9b&\x91\xfd\xe3&\x1a\xfe\xd4\xb9g" +
"\xdf\xd5\xcf\xdd\x17,\xcc\xa4\xb0\x08mz\x01\xd9S\x9b" +
"\xc8\x85\xc77}\x17z\x83\x9cp\x05\xb7>\x99\x8b\x95" +
"<\xdf\x99\xfedN\xfe\xdc\x98\xe3E\xbb\xb8}H>" +
"\x8c\x0bO\xb83B5n\x1eC\xfcH}\xdd\xe7\xee" +
"\x98i9\xfe\x10w\x87\x06\x1c\xdbw\x1dk\x0cQk" +
"Wc\x001\x04H\xf1\xc3\x00\xdagU\xd4,\x05S" +
"\x88i$\xd0\xfc\x02\x80f\xa9\xa8\xcd)\x98R\x944" +
"*\x00\xa9\x12i\xfa*j\xa7\x15L\xa9j\x1aU\x80" +
"\xd4\xc9\x11\x00\xedn\x15\xb5\xfb\x14\x0c\x0a%c\x88\xc6" +
"\x00\xd5\xb1p%(\xb8\x120\xf0|!\\\xd3\xcec" +
"\xd6\x9c6\xfd\xbd\xf6\x14:5\x99\xcdg\xcc<\xf7M" +
"P\x1d\xbb\x06\x16\x0b\x8e-v\x17=\x00\xc0\xf6z\x01" +
"\x07\xc4v\xf8\xe8\xd9\x8e\xf2\xa2\xb1\xd7.\x96\xfc\xfd\xe5" +
"\xa2\x00\xa0\x89\xbeH\xae\xb3^e\x04\x00W\xb0\x1e\xe5" +
"{\x00\x98d=\xca\x13d\x9c\xf5(\xdf\x06\xc0\x14\xeb" +
"Q^\x06\xc0\x95\xacG\xf99\x00\xb6\xb0^e\x12\x00" +
"\x19\xebQ^\x03\xc04\xeb\x95\xbf\xc8\xb6*'\x00P" +
"a\xbd\xcaQ\x00\\\xc5z\xe4\xf3U\xac[\xf9\x1d\x00" +
"^\xcdz\x94\x1f\x01\xe0j\xd6\xab\xfc\x1a\x00\xd7\xb0\xad" +
"\xf2\xb9\x83mS\xbe\x06\x80\x9dl\x9b\x1cw-\xdb&" +
"\xedu\xb1~\xf9|\x0d\xeb\x97~\xa9\x95\xe7\x18\xeb\x97" +
"\xfedX\xbf\xb4\xbb\x8e\xed\x90\xf6\xd6\xf7\x0d*\xdb\x11" +
"\x00\xe3l\xaf\xf2\x02\x006\xb0\xbd\xd2\x816\xb6K9" +
"\x0c\x80\xadlP:\xb6\x81\xed\x90/^\xcb\x06\xa5\xe1" +
"\x8d\x95\xdf\xee\xbeAe%\x19hf{\x95\x07\x00\xf0" +
":\xb6W\xf9#\x00n\xea\x1bU6\x90\xe0zv@" +
"\x86\xa0\xa7\xef\x90\xa2\x10\xb0\xb9\xefH\xf8\xc7'\x18W" +
"\xbe\x00\x8070._\xede\\\x06/Qynd" +
"\\9\x03\x80M\xec\x88\xfc\xbd\x91\x1d\"\x1f\x02\xc3\x99" +
"\xb5-\x87\x1b\x00\x10x\xc2\xdf\xcf\xdd\xbc@?\xcb}" +
"\xe1r+3\x98\xcb\x09\x8bp\xbd(\x84\x11\xa6\xc8\xbe" +
"\xa9\xa9\x84'\xfc\x05\xe8\x90c'){\x09\x1e\xe5\xc5" +
"\xa1R\xdc\x9d\x11R>\x14\xa65x\xc2?hz\xa6" +
"c\x0f\x95\xe6\x89\xd4\xf0\xa5\xac\x93\xcf\x0aH\xcc\x84\xe3" +
"IM%T\x95>\x91K\x83\xa1\x8fQ\xd9\xa8i\x87" +
"\xe2\x83\x00\x81+h&\xba\x80\x01\xdf7\xed\xbc\x17x" +
"|F\xe8\xc2\xf7!\x19>\x0a\x7f\x97\xcd'-\x18\x08" +
"\x87_h\xec\x80'\xa4\\\xe8\xc9\xaaXNE\x99'" +
"+\x0a\x81Fm\xf6\x8a\x9c}D\x9a\xa8\xbc\xb9\xc7\xb1" +
"\x8c\xac\xc2=_\x17\xc2\x96\xaa\xa4\x89~$\xca\x12\x1d" +
"\x11\xaa{l!8\x98KT\x02/Q%D\xf7\x9b" +
"\xd3b\xdf\xd4\x94'\xfc0\x10\xc3b\x8a\x97\xd0\xf2\xb3" +
"\xdc\x16\x13f\xc2\xf0\x0b5\x97\xb1\x1a\xb7\x8c\x0c\\@" +
"\x81!u,Y>E\xc4LP@\x08\x1d\x179'" +
">=-lC\x18Rb\xe7=Z+\xddrf\x87" +
"\x9dY\xfbv\xc7\xbdC\xcc\x85\x0ed\x934\xd9\xfa\xdc" +
"\x0f\x14\xe7I\xcdDEJs\xd7\xd5\xea\x9c\xfd\x89\x82" +
"i\x89\xa1\x02\xb7\xf3\xa6\x9d\xd7\xc5@\xa8.G\x1f\x13" +
"\xae\x87\xa6\xe7\x0b\xdb'A\xb8l9n\xe7\x845\xec" +
"\xc0@\x98\x9b\x95\xf4\x18\xf1\xa8\x0eU\x1et\x07\x92%" +
"7'\xe4\xa2\xce\xf9\xc2Uln\xd5\xc2</\x1d\xa5" +
"\x18\xab\xe2Lv\xde\x1c\xc2\xec\x1ds\xcd\x8c\xe3\x9a~" +
"\xb9\x86\xab\xa1\x19rZ\x8c\x8b\xe3%\xd3\x15\x1e\xed\x86" +
"\"\xfa\x01\xa7__/bu\xb4p9\xc6\\\xe1y" +
"\xcan\xee\xedw\x06+\x1a\xf3\xc6\x1b4\x8e\x96<\x95" +
"\xc2\x1f\xaefT\xab\x1e;\x09*~}*\xb4\xea\x8e" +
"Z\xf2kC4\xc9!\xf6\xcd\x08\xd75\x0dQW\xa4" +
"U\x1brl\xc3\xf4Mga0\xaa;P/p\xc3" +
"\x99\x1d\xe2\xae\xees\x1fe\xf4$\x84\xb3\xa3\x8e!\xac" +
"\x837\x85S\xa9`\xbb\x8b^\xd6\xc9\xf1$\x19$x" +
"\xc4s\xec1\xe4~\xe1v\xcb\xe1\x95YK\xac\x81\xfb" +
"\x85\xfdbN\xba \x01\xee\x17v:\xd1!+\xa6\xc8" +
"\x12\xadG\xd2\xb5\xb9U;,\xe2W8\x1a\xc9Yq" +
"\xa3<s\xe8\xd0\xb8\xb9z:\xb2#x\x02@\xbf\x0b" +
"U\xd4\x0bX? \x99\xc0\x11\x00\xdd \xbc\x88\xf53" +
"\x92M\xe38\x80n\x11>\x87\xf5c\x92\x95\xa4\xbeO" +
"\xf8i\xc2c\x8di\x8c\x01\xb0\x93x\x13\x80>G\xf8" +
"Y\xc2\xe3Mi\x8c\x03\xb0{\xf00\x80~\x9a\xf0\x07" +
"\x09ohNc\x03\x00\xbb\x1f\xbf\x06\xa0?H\xf89" +
"\xc2\x13-ij\"\xd8\x97\xf0\x01\x00\xfd\x1c\xe1\xe7\x09" +
"olMc#u\x14R\xff<\xe1\xcf\x12\xde\xd4\x96" +
"\xc6&\x00\xf6\x0c\xba\x00\xfa\xd3\x84_ \xbc9\x91\xc6" +
"f\x00\xf6<>\x01\xa0_ \xfc\x15Tp}\x8b\x92" +
"\xc6\x16\x00\xf6\x03\xdc\x0e\xa0\xbfH\xf8ET\x10[\xd3" +
"\xd8\x0a\xc0~\x88\x9b\x01\xf4\x97\x08~\x1b\x15\x0c<\x87" +
"\xb6\xcc\xa8\x03\x03\xb6Ci\x85M\xa0`\x13``q" +
"\xdf\xf4K\x86\xa03\xbd\x05\x14l!\xcc\xb1\xf3\x04\x02" +
"\x8a\x1a\xc6\xadEz\x19On\xa3fP\xb0\x190\x98" +
"\x14\x9c\xba\x89aPE\xbe\x06\x16\x1c\xd7<\xe1\xd8>" +
"rk0\x97+\xb9\\\xcd\x95k\xc2\x19\xe1\xfaf\x8e" +
"[\x18\x8are:\x00\xe7[\x1b\xc4\x8ah8j\xd5" +
"\x0b+e\x0e2RV\xc3K\xb69'g\xe7\xf9|" +
"\xba8jZ\x09\xcb\xf40\x0e\x0a\xc6\x01\x07\x0a\xdc\xbb" +
"\xdd\x9cC\x04\x05\x1109s\xc7\xaea\\\x018\xa6" +
"\xa24\xb0\"\xd2\xc3\xc4\xffF\x0f\xb3\xaf\xe4\xdf\xa8\xf3" +
"\xe9\xa2%(1K\x9eL\xca\xd5\xb2\x09\x1b\xdcI\x8d" +
"H\xaa\xff&\xeaCR[\xe9\xd4WS\xbd\x04\xc6R" +
"\xdd\xd4\x0b\xc4S\xeb\x8f\x02\x9c*\xd9\xc7lg\xd6\xce" +
"\xd8\xce\xee\xa2\x17\xd8\xce\x903#\\\x0ej^\x9c\xb2" +
"\x9dQ\xee\xe7\x0a\xc14\xfd+\x8c;`\xc0\x09KH" +
"\x05\xc8BX\x85?v\x1f\x9a0\xb6\xdet\xa5Ft" +
"A\xe3\xda\x7f%}\x0a\x03\xedc:5\xf6\xa9%_" +
"F\xa0\xd6\xb4~\xf5\x01\x00\xed\xeb*j\xdf\x8c4\xad" +
"OQ+z^E\xed\xd9H\xd3\xfa\xccf\x00\xed\x9b" +
"*j\xafD\x9a\xd6\x1f\x90\xe6K*j\xaf+\x881" +
"\xb9\x13S\xaf\x9e\x01\xd0.\xaa\xa8\xfd\x98\xb6!\xcam" +
"\x98zs\x12@{CE\xedm\x05k\x9d\x0c\x8e\xb9" +
"N\x9e\xea\xa4\xecOk\x84\xa1\xd2\x9fz\xd5#\x8e\xfa" +
"1P\xb0\x150Y\xe4~\xa1\x9a\x03\xedu\xc6\x06(" +
"\xb3\xa1\xe8x\xb2\xa2\x86\xfdn\x8d|U\xecY\x8eS" +
"\x1c\xe7\xbe\xc0AZ\xc0\xbc\xa8\xe7nU\x02\x89Q\xd3" +
"\xae\xa1\xd5\xa0\xaa\x7f+\xb7\xd4\x92\xaf5b\xf4\xaa\xa3" +
"\xe9h\x84\xc55\x8d\x07\xd5\xd4\x83$%_\xb0\xbb\xe8" +
"\xe9\xb4\xaf\x01\x85v\xaeV\x19\xd7\xc4v\x02\xe8\xe9\x98" +
"\x8a\xfa\xbaX\xa42v\xc5\xa8R\xac&|c,R" +
"\x19\xd7\xc7\xa8\x02\xae#\xfc\x86\x98\x82X)\x8c=1" +
"*t\xd7\x13|3\xa9\xc70,\x8c[cTx\xb7" +
"\x10~+\xe1q%,\x8c\xfd\xb1\x17\x00\xf4[\x09\xdf" +
"Cx\x83\x1a\x16\xc6]r\xd8\xdb\x08\xcf\x12\x9e\x88\x85" +
"\x85q\xaf\xb4\xbf\x87\xf0\xfd\x847\xaaaa\xd4bT" +
"\x18\xf7\x13\xfeY\xc2\x9bbaa<\x12\xa3\xc2x\x17" +
"\xe1\x05\xc2\x9b\xe3aa\x14\xb1/\x00\xe8\x05\xc2}\xc2" +
"[\x1a\xc2\xc2x<\xf6#*\xe0\x84\x9f%\xbc\xf5r" +
"X\x19\xef\x91\xfe\xdcM\xf8}\x84\xb7u\xa5\xb1\x0d\x80" +
"\xdd\x1b\xa3\x82\x7f\x9a\xf0\x07\x09_\xf1\xab4\xae\xa0\xc2" +
".\xfd\xbc\x8f\xf0/\x12\x9elLc\x12\x80=\x12{" +
"\x8d\x0a;\xe1\xe7\x09ooJc;\x15v\x19\x9f\xc7" +
"\x08\x7f\x9a\xf0Ts\x1aS\x00\xec[r^O\x13~" +
"\x81\xf0\x95\xc94\xae\xa4\xc2\x1e\x9b\x04\xd0\x9f#\xfc%" +
"\xc2YK\x1a\x19\x00\xfb~\xec{T\xc1\x09\x7f\x9d\xf0" +
"tk\x1a\xd3\x00\xec\xd5\x18\x1d(\xaf\x13\xfeS\xc2W" +
"\xb5\xa5q\x15\x00{K\xc6\xe7\xc7\x84_&\xfc\xaa\xb5" +
"i\xbc\x0a\x80\xfdR\xea_&\xfc=\xc2\xaf\xfeu\x1a" +
"\xaf\x06`\xbf\x95\xfe\xbcG\xf8\x9f\x09_\xdd\x95\xc6\xd5" +
"\x00\xecO\xb1\xa3\x00\xfa\x071\x15\xc7\xe3\x0a\xa6\xd64" +
"\xa6q\x0d\x00\xfbP\x86\xe7\xcf\xa4\x1e#\xbc#\x9e\xc6" +
"\x0e\x00\x86qr3\x16WQo'\xbc\xf3\x9a4v" +
"\x02\xb0\xb68\xb9\xd3J\xf8j\xc2\xd7f\xd2\xb8\x16\x80" +
"\xad\x8aS8\xd3\x84\xaf#\xbckc\x1a\xbb(;\xe3" +
"t>\xaf%\xfcz\xc2\xafiN\xe35\x00\xac;N" +
"\xe1\xd9H\xf8\x16\xc23-i\xcc\x10q\x8c\xd3\xb4\xb6" +
"\x10~+\xe1\xebZ\xd3\xb8\x8e\xd2P\xe2\xb7\x12\xbe\x87" +
"\xf0\xf5mi\\Oi\x18?\x03\xa0\x0f\x13>F\xf8" +
"\x06\x96\xc6\x0d\x00l4N\xe93F\xf8]\x84_\xbb" +
"6\x8d\xd7\x02\xb0CR\xffN\xc2\x0d\xc276\xa4q" +
"#\x00\xe3R\xdf \xbcHxw2\x8d\xdd\xd4_\xc4" +
")l\x16\xe1sq\x05O\xcd\xf2\xf2\x1d|ZT+" +
"\xcd\xc0,/\x8f\x8b\xa9\xeac\xe0:\xdc y\xa4\x18" +
"\x85\xa7Z\xd6\x9c\x06\xd5\xf4kU\xc3\xae\xf4\xd80\x10" +
"vt\x8b\x04\x18\xe2\xc3\xe6\x80\xe7S\xf7\\U\x18(" +
"\xf0\x13\xdc5j\xd6I\x7f\x0f?\xc1A]\x02D\xd7" +
"\x186\xe9}\xb5n \xe0\xc6\x8c\xe99n\x192\xfa" +
"\xbc\x83\x9e^\x1a4fL$a\xe8\xc2\"\x99R\x95" +
"U\xec\xe6\xb0\xee\x98c\x8b\x09^\xae\x9e\xc3\x19\x8b\xdb" +
"\xc2\xc3\x06P\xb0\x010\xf0MKd\x89\x95\xaa\xc2\xa8" +
"\xaa\xd4\"\xa3\x98\xbe^\xca\xe7\x85\xe7\x0bC\x1a\x8f4" +
"\x0c^E\x00\x03\xc6|w\x85\xe7\x9b\xd3T\xa7\x8dq" +
"\x87\x1b\x13\xa6\xa1\xfa\x85\x9a\x90\xd6\x81\x9adH\x889" +
"\x1f\x93\xf5+T@L\x02\x06\x86Y\x89\xea\xed\xae3" +
"=\xc1\xcbC\x19a\x13\xa7\xa8\xb50\x15^\x8bUb" +
"\x1b\xf1h\x9a\xe8\x98;#\x16\xc6o\x96\x97ua\x89" +
"\x1c\xd2\xd9\x12^\x88`\xb2~\x13V\x19\xb9:g4" +
"Cb\xe0G\x03R0\xf3\x85Y^\x1e\x82\xa4\xc5=" +
"\x0f\x93\xf5{\xc9\xf0\xed\xcc,/\xef5\xaa\x9dO\x90" +
"\xabp\x83\x05T\xa8\x9ey\xf2\\9( \xe3\xd2t" +
"0\x01\x0a&*\xd1\xa1F\x07\xd4\x12\x0dR;\x98*" +
".\xe6\xeb\xe7\x0f&\xeb'U]:\xea\xd8\xce~H" +
"D\xfb\xcd\x9c3],\xf9\xc2@)3i\x07\xd4d" +
"a\x93\xba[\xa0-\\\x1e\x1e\xbc5Y\xd1u\x8cR" +
"N\xb8\xa8\x0b\x8f|\x8cJ\xc4\x8c)fu\xac3\xed" +
"Z\xa8+\xb2a\xac,#,\x94\xecD\xa7d\x1b\xdc" +
"-\xef\xc5\xfa\xae\xa8\xc8& 9?\x8a\x1f\xc5Yj" +
"\x94+\xa4\xe9rY\xa95j\x94\xcdNj\xbbl\x0e" +
"\x9bv\x02\xd06\xf5\xcd\xdc\xa9\xa2ps\xc2\xf6\x97\xd3" +
"\x9bm\x8b\xf6fK\xb5\x11\x94\xe0\xf22Q\xcc\xc9\xbe" +
"\xacU\x0e\xde\x15v\xa6\xab6\xcb\xce\xb4m'\xc0\xa9" +
")W\x88Y^N\xe6L\xbf\\\xedH\x97\xe3\xc9\xd6" +
"eu\x95\x09c\xeb\xcd\xcblC?\xb5\xdc\x01\xb6-" +
"\xf7\x85\xadW\x0a\xa6\xbc\xb3D\x9b\xe2\x98\xae\xf5\xb7'" +
"\xa9k\x9dSQ;\x1b\xe9o\xef\xb9\xa9~\xd5\x8a\x95" +
"\xf6\xf6\xde\x0d\x00\xdai\x15\xb5\x07\xa9\xbdm\x0f\xdb\xdb" +
"\xfb\xe9\xed\xb3*j\x0f\xd7\x1b\xaa\xd4C\xd4\xf3>\xa8" +
"\xa2vN\xc1\xa4_.\xd2^\xaa}G\xabl\xe7)" +
"b\xdd\xd5\xdcMx\xbe[\xeb`'\x1d\xc7\xaa\x95\x85" +
"\xa3\x15\x02\x1e=U\x96\x13\x93-\xcb\x0db\xdf\x95^" +
"\xd8S)TT\xa6\xe4~\xb8EF\xe7\xf10%\xbf" +
":\"S\xf2KG%Yz\xe4&I\x96\xee\x1f\x97" +
"d\xe9^RiH\x9d\x9c\x04\xc0D\xaaL`c\xaa" +
"\xe4RIH\x1d\xa7\xf7\x9aS\xd3\xf4^K\xca\xa4\x9f" +
"\xd6\x94 \xcd\xb6\x14\x8f\x90\xac`\xda\xf1\x1dw\x96\x97" +
"\x01\xa0\xfew2k\xda\xc72\xbe[\xb2\x8f\x05\xf2\xdf" +
"\xaci\x03\x1e;Ut\xcdi\xee\x96\x83\xcao\x16\x12" +
"\xa6},\xf0\x04UO\xee\x02\x96\xeb\x7fg\xcad#" +
"\xf0\x89\xc0rW\x9a\xaf\xfd-\xcd\x07%;Gs6" +
"!9e\x0a#p\x85g\x1a\x82\xce\x19\x93[\x81e" +
"\xce\x98v\x9e\xfaxW\x08\xff\x8at\x8b\x96t\xcc1" +
"m?\xbc\x04\x89|\"\x18Y\xea\x13\xc18\x80VP" +
"Q\xf3\xa9\xc9\x8f\x85\xe9x\x9c\xc0\xa2\x8a\xda\xdd\x94\x8e" +
"\xf10\x1d\xcb'\xea\xc9\xfc\xb1/\x02r%w\x86\xfb" +
"%\x17\xea'z\xe0\x87\x17\xb1\x02\x06,\x87J\xca\"" +
"\xce\xf31v|\xdf\xc7!\x9ecUF&Kk-" +
"\x0e=\x14\x87\xebU\xd4n\x8e\xc4a+My\x8b\x8a" +
"\xda\xad\xcb\x99\xdd\x15\x1c\xd8W\xf2o\x94\xb4K^A" +
"\xca\xd5\x90\xf1\xed\xd9,\x13z}\x98\xd0]#2\xa1" +
"\xd7l\x00H\xda\x8e-\x02\x93\x9a\x06\x9b[\x94(b" +
"\xae\xf6w\"\xc7\xdd\x8f\xfd\x95HO\xfa\xdc\x17Z\x0c" +
"#\xdf\xceS\xb8!\xb1\xbb\xe8i\xa7k\xec\xef\xb8J" +
"}hQUQ\xbf[\x8d\xb0\xbf\xb2J\xf4\xecn\xc2" +
"\xefS#\xec\xef^\x95\xfa\xeb\xb3\x84?L\xb8\x8a!" +
"\xfd{H}\x02@\x7f\x98\xf0\xaf\x13\x1eSC\xfa\xf7" +
"Ui\xff\x1c\xe1\xe7\x09\x8f\xc7B\xfa\xf7\xb8J\xfd\xf2" +
"c\x84?MxC<\xa4\x7f\xdf\x92v\x9e&\xfc\x02" +
"\xe1\x89\x86\x90\xfe=\xaf\xbe\x0c\xa0_ \xfc\x15\xc2\x1b" +
"\x13!\xfd\xfb\x81J\xec\xf5E\xc2/\x12\xde\xd4\x18\xd2" +
"\xbf\x1f\xaa\xc4\x1b^!\xfc\x0d\xc2\x9b\x9bB\xfawI" +
"%\xf6\xfa:\xe1?%\xbc\xa59\xa4\x7foI?\x7f" +
"L\xf8e\xc2[[B\xfa\xf7K\x95\xfa\xf7\xcb\x84\xbf" +
"Gx[kH\xff~\xab\x12\xff\xf8\x0d\xe1\x1f\x10\xbe" +
"\xa2-\xa4\x7f\x7fP\x89&}\xa0\xaa8.\xd9\xdf\x8a" +
"\x90\xfd}(\x87\xfd+\xa97J\xf6\x97\x0c\xd9_\\" +
"\xb2\xb9\x18\xd1\xa4v\xc9\xfe\xdaC\xf6\xd7&\xd9Y+" +
"\xe1\xab%\xfbK\x85\xeco\x95d\xcduR\xce\xd4\x90" +
"\xfd\xad\x97\xacv#\xe1[$\xfb[\x19\xb2\xbf^i" +
"\xe7\x06\xc2o\x91\xec\x8f\x85\xeco\x9b\xd4\xbf\x85\xf0a" +
"\xc9\xfe\xd2!\xfb\x1b\x94,r\x98\xf01\xc9\xfeV\x85" +
"\xecoT\xda\xc9\x12~\xa7d\x7fW\x85\xec\xef@\xec" +
"\xcc<\xf6\xbd\xe6\xea\x90\xfe\x1d\x91\xac\xb6\xce\xbe;n" +
"\x0b\xe9\xdfB\xf6\xdd9\x18\xd2\xbf\xe3\xd2N\x91\xf0\xbb" +
"\x09_\xbb3\xa4\x7fe\x89\xd7Yy\xd7PH\xff\xee" +
"\x91x\x9d}_3\x1c\xd2\xbf\xfb\xa5\x9f5\xf6\x8d\x99" +
"\x90\xfd=\x12\xdb\x00\xa0?H\xf0\xb9\x98\x82\xf2^\xde" +
"\x1as\x05$=/\xd2&sk\x96\x97\xbd}6V" +
"\xbej\xed\x1a\x90\x9fj\xea\x0a\x93.?&\xb2f\x1e" +
"\x12\x05\xdf\xab\xa1\x06\xf7\x0a\x93\x0ew\xd1\x88\xdc\xd0\xd7" +
"j\x9a!\x96\x1c\xab\xc6\x14\xe4M\xbd0`\xb1$\xeb" +
"\xd8y\x92&\x96zO9(\xdcrU#\xfa\xfe)" +
"\x91sv\x0b\xee\xd6\xde\x98r\xdc\x9c\x18r8\xa8\x9e" +
"_\x03Mo\x8c\xbb\xc7\x88\x7f\xd4\x07.\xf2\x92'\xb2" +
"\xdc\x87$M~\x01\xec\xd8(\xab\x9fis\xb4\"L" +
"\xcbq\xfd\xdd\x82\x03\xd6\xc7\xf3]>5e\xe6F\xd1" +
"1\xc2o]Q&\x92\xe7\x9e\xee\xf3\xdc\xb1\xe8\xb8\xd3" +
"\x8e!h\x160o\xa2aa\x1bs!#>r\x91" +
"\x06\x07,\xcb\x99\x8dF\xa8\xbe\x1c\xbeS\xd4\xcd<\xda" +
"5\xba\x18~0Zl4\xc4\xb3\x0eV\xe3\x89\x0be" +
"\x07\x05V\xe3\xbd\xe0\xdd\xa20\xb85\xca\xe7 3." +
"\xf2\xc2\x9e\x8f\xcb\xb8\x0d\xe6|sF\xd4'\xec\x0b\xcf" +
"\xe2CC\xbb`\xc0\xce\xf3|\xc4TE@\xfcCH" +
"\x11.\x92\xdd\x81\x8e?\xe8NG\x13Ff\xf3\x1e\x9a" +
"\xf0\x90[2\xbd\xc8@2\xf7\x96\x94\x14K\x96'\x06" +
"m\x032\xbb-\xd3\x10U<\x91/z\xcb\xfcV\xbf" +
"\xe0\\\xbee\x99\x9d\xfb\xff\xbb\x92\xfeD\x85\xfeJ\xf6" +
"\x9b(\x17\xe5)\x1av)\xdb\xc2\xb6\xb0w\\\x9e\xa2" +
"=\xe1)\xda=\"\xdb\xc2\xf5\x9b\x01N\xe5J\xaeK" +
"\xa4\xa9\xe8\x0a\xc3\xcc\xf9\x02\xd0\x08\x8a\x8e\xe7\x99\x93\x96" +
"\xa8\x9e\xad\xb6!wAr\x8a\x9b\xd6\x15/\xf4\x87+" +
"W\xc7\xb5\x9b\xe3\x05\xd7\xd9\xdb\x01\xb4/\xaa\xa8=\x16" +
"i,\x1e\x1d\x8f\xdcq+\x18\xba\xfe\xd4\xe1\xc8\x1d\xb7" +
"\xaa\x84\x0d\xd63g\x00\xb4\xa7U\xd4.\xd4\xaf\xb3\x9f" +
"\xa7\xb7\x9fSQ{#r\x9d}\x89\x14_WQ\xfb" +
"\x8d\x82\x03\\f\xd7\x82t\xb5h\xae\xf5\xdcq|n" +
"\xddnZ\xa0\x0a\x0f\x1bA\xc1F\x88\\\x83\x0b\xe3v" +
"\xd3\x12\x1e\xd4$V\xe5\xfb\x1b\xa0W\xbd\xedn\xad|" +
"\xf1\xa8\x8apX\xf8\xdc\xb4<\xa8_\x87\xd7\xfesL" +
"\xe5:|9\xc4`^\x16\\)\xf8\xd5\xcf\x83\xc3\x03" +
"\xa1\x0f\x92\xba\xd6\xd6`\x175w\xc3*jc\x0aV" +
"\x97`\x94\xa2\x9dUQ\xbb3\xb2\x04\x07(\x88\xfbU" +
"\xd4>\xabD\xa6\x1c\xa1B\xcb\x8b\xda\xff\x05\x00\x00\xff" +
"\xff1<\xb37"
const schema_b526ba661d550a59 = "x\xda\x94z\x0d\x90T\xd5\x95\xff9\xef\xf5L\xcf'" +
"M\xf3\x1a\x01\x01\xdb!\x928\xc41\xc0\xc8?\x0eh" +
"\x86\xa1g@\xa8\xeea\xde<>\x1c\x94\xaa\xdc\xe9w" +
"\xa7\xe7\xc1\x9b\xf7\x9a\xf7^\xcfLSX \x81*\xf4" +
"\x8f\x15\xcdj\x82)\xd9\xf8\x81\xb5\x9a\x95\x84du\x8b" +
"XX\x0b\x14\xa9B\x17\xaa4\xa5)c\xcc\xfaQ\xd9" +
"\xd2d\xb5\x8cY\xad5\xd9X\xbdu\xee\xed\xaf\xf9\x88" +
"8E\xd5t\xf7\xef\x9cw\xee\xb9\xe7\x9e{\xee\xf9\xdd" +
"\xc7r6\x7fmhE\xf3?\x8d\x81bdkjj" +
"\x0b\xd1\xdd\x03\xef:\xc1O\x0e@t!\x16\x06\x1a\xb6" +
".\x1ez\xfe\xab\xcfA(\x0c\xd0\xfe\x8b5;P\xbb" +
"\xbc&\x0cj\xe1\xa7\x9f$;v\xfc\xe9\xfc\xdd\xd3h" +
"=MZ/\x08\xad\xdb\x13\xe7\xbf;\xf8\xd5\x1f\x1d\x86" +
"\xe8B\xa5\xa2\x05\xd8\xfe\xf0\x9aM\xa8\x9d\\#\xd5\xdd" +
"\x10`\xa1\xed\xc5\xdc\xed?^p\xdf\x03\xa0\xb7a}" +
"\xe1\xbc\xf3o\x8d\xdb.\xdc\xf9\xdfP\x83\xa4\xb3t\xed" +
"\xbd\xa8\xdd\xba\x96\xbev\xac}K\x01,\xfc\xe3\xd7?" +
"\xcaY{w|\x1f\xa2_Q\x0a\x07?\xfd\xf4+\xed" +
"\xff\xf5\xf1\x09\xb2\xbc'q\x10\xb5\xc3\x890\x80vw" +
"\xe2\x07\x80\x859\xcfb&s\xf1\xf2#\xd3x\xfaJ" +
"b\x10\xb5\xffL\x90\xa7m\xbf\x8d\xab\xdd\xe1\xe1\xc7\xa6" +
"\xd1:\x97\xd8\x81\xdakB\xcbV\xdb\xd7~6X\xfb" +
"\x04\xe8\x0b\xb1J\xadF\xe8\xfd\x8c\xf4~\x99\x90\x8fl" +
"G\xc0\x8a_\xfaB\x9cU\xa5^K:\xabz\xaeF" +
"\xad\xa7\xe7k\x00\xed\xacg,\x0cX\xe8N\x9c}\xe9" +
"\xe4[O<9%Z\x7fH\x1dD\xed\xf3\x14\xcd\xe9" +
"/\xa9o\x02\x16\xb6\x9e\xd0\x7fs\xc3\xe8\xe5'\xa7\xf1" +
"\xf6\xf3\xd4\x0e\xd4\xa2\xbd\xe4\xedO~\x9b~\xe8\xff?" +
"\xf5\xd1?O\xb1\xf7aju\xc5\xdef\xc0\xc2\xce\xe7" +
"\xde[\xf1\xdd\xcf\xdf\xfa\xc94\xf6\x9a{w\xa0\xd6\"" +
"\xecu\xbe\xf5\xc7\xbbR\xd7n?5\xed\xa8\x83\xa5Q" +
"/b\xb2\xc5J;\xa7\xa7\xd1\xfa\x90|C\xa15|" +
"\xe6\x1f\x1e4\xd6t\xbf0\x8d\xd6\xef\xc8\xd6\xc7)\xd2" +
":\xa4\xde\xf46\xbf\xe5\xba\xf3\xd3h]&\xadw\x84" +
"\xd6G\xff\xf2\xadWn\xbeu\xd7\xc5\xc9\xab\xa2\x90\xde" +
"\x0b\xa99\xa8]\xa6\xb9\xb6\xbf\x98\x8a\xd3\xaa\xac\x1e\xd8" +
"\x9e\xb5_\xfb\xd1\xbfO7t/\x0d-\x1c|\xf9\xe0" +
"\xa3\x99\xff}\xe3\xfb\x97\xa7\x1b\x9a\xb4\xde\x11Z\x8b/" +
"\xa4\xdf|38\xf8\xca\x94\x10\xbf\xd0\xbb\x0e\xb5\xcb\xbd" +
"b\xd8^\x91\x0c\x1d\x1dg\x1e\xbbt\xef\xff\xfc\x9a\xbc" +
"T'o\xac\xcd\x9bP\xbb\xbc\x99\x16\xe4\xc5\xcd\xef\x01" +
"\x16V%\xbb\xbfsl\xfb\xf7\xdf\x98f\xf4\x93};" +
"P;\xd7G\xa3w|\xe7\xa5\x1f\xfe\xa0\xe6\x07\xffA" +
"&\x95Ij\xc7\xfb\xd6\xa1v\xb2\x8fL>\xdd7\x06" +
"X\xb8\xfe\x95_\x7ftC\xcf\xb3\x7f\x9e\xb2c\x9a\xf5" +
"]\xa8\xb5\xe8\xa4\xb9X\xcf\x00V6\xdfD\xb3r+" +
"n$\xed\x9d\xfa<\x80v\xae\x87)m\x17\x1c?\xbe" +
"\xb1\xfe\x83\xab>\x99\xc6\xd7\x91\x81\x1d\xa8\xdd=@\xbe" +
">\x11\xca~\xbe\xe6\xd0}\x7f\x99Fk'i\xed\x11" +
"Z\xcb\xde_\xda\xfb\xde\x9d\xdf\xfa\xeb\x94x\xa6\x06\x06" +
"Qc\x03\xe4\xe4\xce\x81\xfd\x80\x85\xc7\xfd\xbe\x8b/\xed" +
"|\xe2\xaf\x93\x9d\x14\x8b~|\xe0 j?\x1b\x10\xe1" +
"\x1a\x10\xd1\x8f\xfe\xeb\xd8\x91\x0f\xbb\x06\xff6\xcd\xf0m" +
"w\x0c\xa2\xd6u\x07\x0d\xbf\xff\xd8\xa9\xf7\x8ccG\x0a" +
"\x933I\xcc|\xf1\x1d\xcf\xa3\xb6\xea\x0era\xc5\x1d" +
"?\x85\xc2\xdf\xfd\xf7P!\xcd=\xce\xeco\xa4C9" +
"?pG\xbe\x91\x16\x1f7\xa6Y\xd6\xc9\xaeN\x88\x1f" +
"\xfd\xdc\xe7\xde(W\xcd\x9b\xfa\x10g\xa2\xbf\xfcJ\xfa" +
")\x9657:\xd9\\\xb0%\x9f\xe5\x00}\x88\xfa\x19" +
"T\x00\xb46e\x13\x00\xce\xd2Z\x95\x9f\x03`Dk" +
"U\x1e\x07\xc0\xd9Z\xab\xf2c\x00\x8cj\xad\xcay\x00" +
"\x9c\xa3\xb5*o\x00`\xa3\xd6\xa6\x0c\x02\xa0\xa6\xb5*" +
"/\x01`Lk\x13\x9f\xa8\xadP\xf6\x02\xa0\xa2\xb5)" +
"\xbb\x00p\xae\xd6*~_\xa5-U\xfe\x08\x80\xf3\xb4" +
"V\xe5W\x008_kS\xde\x05\xc0\x05\xda\x0a\xf1\xfb" +
"jm\x95\xf2C\x00\\\xa8\xad\x12\xe3.\xd2V\x09{" +
"\x8b\xb5\x0e\xf1\xfb\x1a\xadC\xf8\xa5\x16\x7f\x87\xb4\x0e\xe1" +
"O\\\xeb\x10v\xaf\xd5n\x15\xf6Z\xda\xbb\x94\xd5\x08" +
"\x805\xdaF\xe5y\x00\xac\xd56\x0a\x07\x9a\xb5\x1ee" +
"\x07\x006i]\xc2\xb1%\xda\xad\xe2\xc1\xafh]\xc2" +
"\xf0u\xc5\xcf\xa5\xed]\xca\x1c2\xd0\xa0mT\xee\x05" +
"\xc0\xafj\x1b\x95?\x03\xe0\xd7\xdaS\xca\x12\x12\\\xaf" +
"m\x15!hm\x1fP\x14\x02\x96\xb5\xef\x94_\xbe\xae" +
"1\xe5{\x00x\x83\xc6\xc4\xa3m\x1a\x13\xc1\x0b\x17\x7f" +
"\xd7iL9\x08\x80\xf5\xdaN\xf1y\xa36@>\x14" +
"Lw\xcc\xb1]f\x02@\xc1\xe7\xc1\x16\xe6e8\x06" +
"I\x16p\x8f\xd9\xf1\xaet\x9a\xdb\x84\x1bY\xceML" +
"Z#V\xb0yh(\xec\xf3`\x12\x9ap\x9dH\xe0" +
"\xb9B9\xc5\xb2\x89\\\x8d7\xca\x85<\xe1:$\x00" +
"\x9f\x07\xdb,\xdfr\x9dDn\x82H\x95\x0f%\xddL" +
"\x92CxT\x8e'4\x15\xa9*|\"\x97\xba\xa4\x8f" +
"\xd5\xb2\x94\xe5H\xf16\x80\x82\xc7i&\x06\x87\xce " +
"\xb0\x9c\x8c_\xf0\xd9(7x\x10@D\xfe\xe4A\x8f" +
"\xc3\x06m\xe8\x94\xc3O6\xb6\xd5\xe7B\xce\x8dHI" +
",\xa6\xa2L\x90e9G\xb3<{E\xcc\xbeJ\x1a" +
".>y\x9bk\x9bI\x85\xf9\x81\xc1\xb9#TI\x13" +
"\x83\xaa(\x0bt\x13W\xbd\xdd\x93\xc1\xaet\xb8\x18x" +
"\x81*\x12\xddb\x8d\xf0\xcdCC>\x0fd \xba\xf9" +
"\x10\xcb\xa1\x1d$\x99\xc3\xb7[a3\x18.\xbb\x8c\xa5" +
"\xb8\xc5E\xe0\x0a\x14\x18R\xc7\x9c\x1dPD\xac0\x05" +
"\x84\xd0~\x9evkFF\xb8crSH\x9c\x8cO" +
"ke\xd8\xeeX\xb7;\xe6\xacw\xbd^>.\x1dH" +
"Fh\xb2\x95\xb9o\xcdN\x90Z\xe1\xa2\x94\xe6n\xa8" +
"\xa59\x07\xdb\x87-\x9b'\x86\x99\x93\xb1\x9c\x8c\xc1;" +
"\xa5\xba\x18\xbd\x8f{>Z~\xc0\x9d\x80\x04r\xd9\xd2" +
"\xccIs\xbb\xdb\x85N\x99\x9b\xc5\xf4\xd8\xe4\x83\xea:" +
"\xc5\x1f\x86\x0b\x91\x9c\x97\xe6bQ\xc7\x03\xee)\x0e\xb3" +
"\xcba\x9e\x90\x8eB\x8c%q<9a\x0e2{\xfb" +
"<+\xeezV\x90/\xe3\xaa4CN\xf3~\xbe'" +
"gy\xdc\xa7\xdd\x90\xc5\xa0\xc0\xe830\xb2X\x1aM" +
".G\x9f\xc7}_\xd9\xc0\xfc-nWQc\xc2x" +
"]\xe6\xae\x9c\xafR\xf8\xe5jVkUb'@%" +
"\xa8L\x85V\xddUsAy\x88z1\xc4\xe6Q\xee" +
"y\x96\xc9+\x8a\xb4j\x09\xd71\xad\xc0r'\x07\xa3" +
"\xb4\x03\x8daf\xbac\x09\xe6\x19\x01\x0bPDO@" +
"8\x96rMno[)\xa7R\xc46d\xfd\xa4\x9b" +
"f\x112H\xf0&\xdfu\xfa\x90\x05\xc3\xebm\x97\x15" +
"g-\xb0Z\x16\x0co\xe1\xe3\xc2\x05\x01\xb0`x\x9d" +
"[=d\xd1\x14Y\xa2\xf5\x88x\x0e\xb3\xcb\x87E\xcd" +
"4\x87\x85\x110\xaf\xcf\xb2\xdd\xa0\xe8,\xbfqC\xd6" +
"\x97\x87\xc6Mj\x08 \x84t\xe0\xe2^\x00\xe3NT" +
"\xd1\x18F\x05\xa3\x881$\x9c\xe3&\x00\xc3$<K" +
"\xb8\xa2\xc4\xc4A3\x82\xfd\x00\x86M\xf88\xe1\xaa\x1a" +
"C\x15@\xcb\x09\xfd\x80\xf0\x03\x84\x87\xeab\x18\x02\xd0" +
"\xee\xc2\x95\x00\xc68\xe1\x87\x08\xaf\xa9\x8fa\x0d\xf5\xef" +
"\xb8\x03\xc08@\xf8Q\xc2k\x1bbX\x0b\xa0\xdd\x83" +
"?\x040\x8e\x12~\x8c\xf0pc\x8c\x0eh\xed!\xbc" +
"\x17\xc08F\xf8\x09\xc2\xeb\x9abX\x07\xa0=&\xf4" +
"O\x10~\x8a\xf0\xfa\xe6\x18\xd6\x03h'\xd1\x030\x9e" +
"!\xfc4\xe1\x0d\xe1\x186\x00h\xcf\xe1\xe3\x00\xc6i" +
"\xc2/\xa0\x82-\x8dJ\x0c\x1b\x01\xb4s\xb8\x1a\xc08" +
"C\xf8ET\x10\x9bb\xd8\x04\xa0\xfd\x12\x97\x01\x18g" +
"\x09~\x13\x15,\xf8.m\x99\x94\x0b\x9d\x8eKi\x85" +
"\xf5\xa0`=`\xc1f\x81\x15\xe4L\x0et\xbc\x82\x82" +
"\x8d\x84\xb9N\x86@@^\xc6\x98=E/\xee\x8bm" +
"\xd4\x00\x0a6\x00\x16\x069\xf3,'\xd3\x0d*\xcf\x94" +
"\xc1a\xd7\xb3\xf6\xbaN\x80\xcc\xeeJ\xa7s\x1eS\xd3" +
"\xf9\xb2p\x94{\x81\x95f6JQ:O\x07\xe0D" +
"k]X\x14uW[\xf5e\xa5LC\\\xc8\xcax" +
"\xce\xb1\xc6\xc5\xec\xfc\x80\x8ddS\x96\x1d\xb6-\x1fk" +
"@\xc1\x1a\xc0\xcea\xe6\xaf\xb7\xc6\x11AA\x04\x8c\x8c" +
"\xf6\xf6t\xe3,\xc0>\x15\x85\x81Y\x80_\x98\x96\xd4" +
"\xc3l\xce\x057\x1al$ksJ\xcc\x9c/\x92r" +
">%X\xb4k\x1d5\"\xd1\x8e\x95\xd4\x87DW\xd0" +
"\xa9\xafF\xdb\x08\x0cE\x97R/P\x13m\xd9\x05\xb0" +
"?\xe7\xecv\xdc1'\xee\xb8\x1b\xb2~\xc1q\x13\xee" +
"(\xf7\x18\xa8\x19\xbe\xdfqS,H\x0f\x17F\xe8/" +
"7{\xa1\xd3\x95%\xa4\x08$AV\xe1/\xdd\x99\x85" +
"\xcd\x15+g\xd8\xcau|\x99V\x8e\xf61\x9d\x1a\x9b" +
"\xd5\\ \"P\xda\x96\xd1\x87\xef\x05\xd0\x1fQQ\x7f" +
"\xaa\xb2'\xa3On\x02\xd0O\xa8\xa8\x9f\xaal\xc8\xe8" +
"\xc9e\x00\xfaS*\xea\x17*\xbb1z\x8e4\xcf\xaa" +
"\xa8_R\x10Cb'F_<\x08\xa0_TQ\x7f" +
"\x95\xb6!\x8am\x18}e\x10@\x7fYE\xfdM\x05" +
"\xcb\x9d\x0c\xf6yn\x86\xea$\xb5\x90\x95f\x1c\x10g" +
"S\xd2\x94\x8e8\xea\xc7@\xc1&\xc0H\x96\x05\xc3\xa5" +
"\x1c\x98]aC\x80\"\x1b\xb2\xae/**\x08{e" +
"bS\xb4g\xbbn\xb6\x9f\x05\x1c\xbbh\x013\xbc\x92" +
"\xbb%\x09\x84S\x96SFKAU\xff^n\xa9\xb9" +
"@\xaf\xc3\xeak\x84\xfa]U\x0c\xa9\xbe\xbfPJ=" +
"\x88P\xf2\x156d}\x83\xf65 \xd7\x8f\x94+\xe3" +
"\xd3\xea:\xaa,*U\x16\xb5\xaa2\x9eT\xa9R<" +
"E\xf8\xb3jUe\xfc\x99J\x15\xf0\x14\xe1gT\x05" +
"\xb1X\x18\x7f\xa1R\xa1;M\xf0\x05R\x0f\xa1,\x8c" +
"\xe7T*\xbcg\x09\xbfDx\x8d\"\x0b\xe3\x8b\xea\xf3" +
"\x00\xc6%\xc2_'\xbcV\x95\x85\xf151\xec\xcb\x84" +
"\xbfIx8$\x0b\xe3o\x84\xfd\xd7\x09\xff=\xe1u" +
"\xaa,\x8c\xef\xa8T\x18\x7fO\xf8\x9f\x08\xaf\x0f\xc9\xc2" +
"\xf8\xa1J\x85\xf1\x03\xc2?#\xbc\xa1F\x16\xc6O\xd5" +
"\xef\x01\x18\x9f\x11\x1e\x0a)\x18m\xac\x95\x85\x11C\xbf" +
"\x020\xeaB*\x1a1\xc2\x9b\xde\x96\x951\x1a\"\x7f" +
"\x9a\x08\x9fOx\xf3\xe2\x186\x03hsCT\xf0g" +
"\x13\xbe\x88\xf0Y\xef\xc4p\x16\x80\xb6 D~\xce'" +
"\xfc:\xc2#u1\x8c\x00h-\xa1\x97\x00\x8c\xeb\x09" +
"\xbf\x89\xf0\xd9\xf51\x9cM4,D\xf1YN\xf8-" +
"\x84G\x1bb\x18\x05\xd0:B4\xaf[\x08\xbf\x8d\xf0" +
"9\x91\x18\xce\x01\xd0zB\x83\x00F7\xe1}\x84k" +
"\x8d1\xd4\x00\xb4T\xe8\xe7\x00F\x1f\xe1w\x12\x1ek" +
"\x8aa\x0c@\x1b\x08\xd1\x81r'\xe1\xc3\x84\xcfm\x8e" +
"\xe1\\:\xf8B\x14\x1f\x93\xf0,\xe1W-\x8a\xe1U" +
"t\xf0\x09\xfd,\xe1\xfb\x08\x9f\xf7n\x0c\xe7\x01hy" +
"\xe1\xcf>\xc2\x8f\x10>\x7fq\x0c\xe7\x03h\x87C\xbb" +
"\x00\x8cC\x84\xdfO\xf8\x82\xba\x18.\x00\xd0\xee\x13\xf1" +
"9B\xf8\x83\x84_]\x13\xc3\xab\x01\xb4\x07\x84\x9f\x0f" +
"\x12\xfe(\xe1\x0b\xaf\x89\xe1B\x00\xed\xb8\xf0\xe7\x11\xc2" +
"\x9f\"|Q<\x86\x8b\x00\xb4'E<O\x10~\x8a" +
"\xf0\xc5\xd7\xc5p1\xa5g\x88\x0e\xe8g\x08?M\xf8" +
"5\x0d1\xbc\x86\x0e>\x11\x9fg\x09?Kx\xbc1" +
"\x86q\x00\xed\x051\xaf\xb3\x84_\"\xfc\xda\xa6\x18^" +
"Ky(\xf0K\x84\xbfNxKs\x0c[(\x0fC" +
"\x07\x01\x8cW\x09\x7f;\xa4\xe0\xfe1\x96\xefe#\xbc" +
"T\x0a:\xc7X\xbe\x9f\x0f\x95~\x16<\x97\x99$\xaf" +
"\xaa\x16\xf2\xd8IZ#\xa0ZAy[;\xc5&\x18" +
":e\xcb5E\x80\x12\xef\xb6:\xfd\x80\xda\xdb\x92B" +
"\xe70\xdb\xcb<\xb3l\x9d\xf4oc{\x19\xa8\xd3\x80" +
"\xe8\x99\xdd\x16=\xafV\x0c\x14\x989j\xf9\xae\x97\x87" +
"\xb81\xe1$\xa6\x87\xba\xccQ\x0bI(]\x98\"S" +
"J\xb2\xa2\xdd4V\x1cs\x1d\xbe\x9d\xe5K\x07e\xdc" +
"f\x0e\xf7\xb1\x16\x14\xac\x05,\x04\x96\xcd\x93D\x1bU" +
"n\x96T\xca\x91Q\xac\xc0\xc8e2\xdc\x0f\xb8)\x8c" +
"W\x9d\xe8~Q\x00\x9d\xe6Dw\xb9\x1fX#TH" +
"\xcd~\x97\x99\xdb-S\x0d\x86\xcbBZ\x07\xeab!" +
"\xcc\xc7\x03\x8cT\xee\x0f\x011\x02X0\xadbT\xd7" +
"{\xee\xc8v\x96O\xc4\xb9CM\x7f\xb9\xc7(\x12O" +
",1\xcf*\x8fF\x88/y\xa3|r\xfc\xc6X\xde" +
"\xe06O#\x15\x7fyc\x81\x91\xca5Pq\xe4\xd2" +
"\x9c\xd1\x92\x9d{P\x1d\x90a+3<\xc6\xf2\x09\x88" +
"\xd8\xcc\xf71R\xb9\x94\x93O\xc7\xc7X~\xa3Yj" +
"M\x0a\xe9b\xf3>\x89\xabT2O\x14\xfem\x1c\xe2" +
"\x1eM\x07\xc3\xa0`\xb8\x18\x1d\xeaD@\xcd\xd1 \xe5" +
"\x93\xa3\xe8b\xa6r@`\xa4r\x94T\xa4)\xd7q" +
"\xb7@\xb8\xba!L\xbb#\xd9\\\xc0M\x142\x8bv" +
"@Y&\xbb\xc8\x0d\x1c\x1d\xee1y2\x96eY\xcf" +
"5si\xee\xa1\xc1}\xf2\xb1\"\xf9\xc2^\xbfLU" +
"$\xbd\x15\xd1\xa6\x96\xa2N4\x09\xd1\xd5\xa2\xa9\xaa_" +
"\x07@\xbb'\xb0\xd2\xfb\xb3\xdcKs'\x98IO\xb3" +
"\xaa\xba\xa7\x99\xee\xf8\xa5\xbcKt\xbaN\xc0\xc7E?" +
"\xd3$\x06_,;\xba\xb9\xcbDG\xd7\xbc\x0e`\xff" +
"\x90\xc7\xf9\x18\xcbG\xd2V\x90/ur3\xf1d\xc5" +
"\x8c\xba\xb1\xb0\xb9b\xa67q\xdf\x9c\xe9\x00\xabf\xfa" +
"\xc0\x8a+\x05S\xdc\xf5\xa1Cq\x8c\x95\xfb\xc2\xbb\xa8" +
"\xdb\x1bWQ?T\xd5\x17\xde\xbd\x12@\xdf\xa7\xa2~" +
"DA,\xb6\x85\x87\x97\x00\xe8\x07T\xd4\x8fR[8" +
"[\xb6\x85\xf7\xd0\xd3\x87T\xd4\xef\xaf4\"\xd1\xfb\xa8" +
"W<\xaa\xa2~L\xc1H\x90\xcfR\x8a\x97\xdf\xed\x14" +
"w\xd9\x10\xb1\xd5\xd2\xbe\x0e\xfb\x81W\xee\xfc\x06]\xd7" +
".\xef\xd6]E\xe2Z]\xecg\x12\x93\xe53\x0db" +
"\xfb\x95\x1e\xb8\xadX?\xa8z\x88\xfdp\xb3\x88\xcec" +
"2%\x1f\xde$R\xf2\xa1]\x82d<\xb0R\x90\x8c" +
"{\xfa\x05\xc98L*\xb5\xd1\xbb\x06\x010\x1c\xcd\x13" +
"X\x17\xcdy\xb4S\xa3{\xe8\xb9\x86\xe8\x08=\xd7\x18" +
"\xb5\xe8\xa3)\xcaI\xb39\xca\xaa\xc8Ia\xc4\x0d\\" +
"o\x8c\xe5\x01\xa0\xf2=\x92\xb4\x9c\xdd\xf1\xc0\xcb9\xbb" +
"\x0b\xe2o\xd2r\x00w\xef\xcfz\xd6\x08\xf3\xf2\x85\xe2" +
"g\x12\xc2\x96\xb3\xbb\xe0s*j\xcc\x03\xccW\xbe\xc7" +
"\xf3d\xa3\x10\x10\xf1c\x9e0_\xfe.\xcc\x17rN" +
"\x9a\xe6lAd\xc8\xe2f\xc1\xe3\xbeer*\xff\x16" +
"\xb3\x0b\xb65j9\x19\xea\x7f=\xce\x83+\xd2\x14Z" +
"\xd2>\xd7r\x02yy0\xbb\x9c\x8d\x8cR\xe7\xdb*" +
"\xeavU6Z\xfd\x00\xfa\xb0\x8az@\xcdqH\xa6" +
"\xe3\x1e\x02\xb3*\xea\xfb(\x1dkd:\xe6\xf7V\x92" +
"\xf9K\x13\xe8t\xce\x1beA\xce\x83\xcaA[\x08\xe4" +
"\x05&\x87N\xdb\xa5\x922\x85+|\x89\x1d\xdf\xfee" +
"\x08[_\x89\xc9\x88\xd2Z\x8eC+\xc5\xe1z\x15\xf5" +
"\x9b\xaa\xe2\xb0\x82\xa6\xbc\\E\xfd\x96\x99\xcc\xee\x0a\x0e" +
"\x10q\x16tE\\\xdd\x89\xd5\x10\xf1m]&\x12\xba" +
"E&\xf4\xe2M\"\xa1\x17,\x01\x888\xae\xc3\x0b\x16" +
"\x9d\xe5\x0e\xb3)Q\xf8x\xf9{8\xcd\xbc/\x1cr" +
"\xc2\x15R$`\x01\xd7CX\xf5>7\x8aK\xc2\x1b" +
"\xb2\xbe~\xa0\xcc\x9a\xf6\xa8\xd4\xf6f\x89F\xec\xabf" +
"MyAk\xf6\x11~\xa4\x9a5\x1dV\xa9-=D" +
"\xf8\xfd\x84\xab(i\xd3}\xea\xe3\x00\xc6\xfd\x84?\"" +
"h\x93*i\xd3\xc3\xc2\xfe1\xc2O\x08\xda\x14\x92\xb4" +
"\xe91\x95\xda\xd2G\x09\x7fF\xd0\xa6\x1aI\x9b\x9e\x16" +
"v\x9e!\xfc\xb4\xa0M\xb5\x926=\xa7\x9e\x9f@\xcb" +
"\xea\xc2\x926\x9d\x13\xac\xef\x0c\xe1\x17\x05m\xaa\x93\xb4" +
"\xe9\x97\x82f] \xfceA\x9b\xea%m\xba,X" +
"_\x85\xae56H\xda\xf4\x9a\xf0\xf3U\xc2\xdf&\xbc" +
"\xa9Q\xd2\xa6\xdf\x09\x9a\xf56\xe1\x1f\x10\xde\xdc$i" +
"\xd3\x1fTj\xdb\xdf'\xfc\x13\xc2g5K\xda\xf4\xb1" +
"\xa0q\x9f\xa8*\xf6\x0b\xd64K\xb2\xa6\xcf\xc5\xb0\x7f" +
"#\xf5:\xc1\x9a\"\x925\xd5\x88.?D\xdd\xf9l" +
"\xc1\x9afK\xd6\xd4,XD\x85\xad\xcd\x89J\xd64" +
"7\xf4\xfc\x04V\xa6\xa9\x925\xb5\x84\xc8\xcd\xeb\x08_" +
".X\xd3\x1c\xc9\x9a\xda\x84\x9d\x1b\x08\xbfY\xb0&M" +
"\xb2\xa6UB\xfff\xc2\xbb\x05k\x8aI\xd6\xd4%X" +
"M\x85\x95\xcd\x9b+YSJ\xd8I\x12~\xbb`M" +
"WI\xd6\xb4U\xb0\x8b-\x84\x7f[\xb0\xa6y\x925" +
"\xed\x14l\xb0\xc2\xd6\xae^+Y\x13\x17\xe3\x0e\x13\x1e" +
"\x08\xd6\xd4%Y\xd3\x1ea\xa7\xc2\xd6\x16\xad\x93\xac)" +
"/\xf0q\xc2\x0f\x09\xd6\x94\x90\xac\xe9n\x81\x1f \xfc" +
"\xa8`M\xdd\x925\xdd#\xfc,\xb35\x8cK\xd2\xf4" +
"@h\x09\x80q\x94\xe0c!\x05\xc5}\xb6\xdd\xe7q" +
"\x88\xf8~U\xf7\xca\xec1\x96\xf77;X|\x1b\xd4" +
"\xd3)^qT\x14\x06=\xb6\x9b'\xad\x0c\x84\x87\x03" +
"\xbf\x8c\x9a\xcc\x1f\x1et\x99\x87f\xd5\xcdv\xb9\xa6\x99" +
"|\xda\xb1\xca\x0d\xbc\xb8\xe1\xe6&L\x95$]'C" +
"\xd2\xf0t\xcf)\xdb\xb8\x97/iT?\xbf\x9f\xa7\xdd" +
"\x0d\x9cy\xe5'\x86\\/\xcd\x13.\x03\xd5\x0f\xca\xa0" +
"\xe5\xf71o7\xd1\x82\xca\xc0Y\x96\xf3y\x92\x05\x10" +
"\xa1\xc9O\x82]\x07E\xf5\xb3\x1c\x86v\x15\x01r\xbd" +
"`\x03g\x80\x95\xf1\x02\x8f\x0d\x0dY\xe9\x14\xba\xa6|" +
"GTM\x102\xcc7\x02\x96\xde]=\xee\x88kr" +
"\x9a\x05L\x98\xa8,l}\x1e\xc4\xf9\x17.RW\xa7" +
"m\xbbc\xd5\x11\xaa,G\xe0f\x0d+\x83N\x99\xc5" +
"\xc9\x17-S\x8dJ<\xe9b)\x9e8Y\xb6\x8dc" +
")\xde\x93\x9e\xcdr\x93\xd9)6\x0e\xf1~\x9e\xe1\xce" +
"D\\\xc4\xad+\x1dX\xa3\xbc2\xe1\x80\xfb6K$" +
"z\xa0\xd3\xc9\xb0L\x95\xa9\xa2\xa0\x1b-\x9f\x0b\x11N" +
"\x91\xf5\xa2\x1bty#\xd5\x09#\xb2\xf96\x9ap\xc2" +
"\xcbY~\xd5@\"\xf7\xa6\x95ds\xb6\xcf\xbb\x1c\x13" +
"\xe2\x1bl\xcb\xe4%<\x9c\xc9\xfa8\xbbr`\x14\xef" +
"\xfcfp.\xdf<\xc3\xce\xfd\xff]I\x7f{\x91\x95" +
"\x0aR\x1a\xceg\xc5)*\xbb\x94U\xb2-l\xeb\x17" +
"\xa7h\xab<E\x97n\x12ma\xcb2\x80\xfd\xe9\x9c" +
"\xe7\x11i\xcaz\xdc\xb4\xd2\x01\x074\x0bY\xd7\xf7\xad" +
"A\x9b\x97\xceV\xc7\x14\xbb 2\xc4,\xfb\x8a\x17\xe1" +
"\xdd\xc5+\xd7\xf2\x8d\xeb\xa4k\xe0\xd5\x00\xfa\x83*\xea" +
"\x8fV5\x16\xc7\xfb\xab\xee\x86\x15\x94\xae?\xb9\xa3\xea" +
"nXUd\x83u\xf2 \x80\xfe\x8c\x8a\xfa\xe9\xca5" +
"\xf0s\xf4\xf4\xb3*\xea/W]\x03_&\xc5K*" +
"\xea\xef+\xd8\xc9DvMJW\x9b\xe6Z\xc9\x1d7" +
"`\xf6z\xcb\x06\x95\xfbX\x07\x0a\xd6A\xd5\xf517" +
"\xd7[6\xf7\xa1,\xb1\x8b\xef\xad\x00\xfd\xd2-qS" +
"\xf1MAI\x84\xdd<`\x96\xedC\xe5\x1a\xb9\xfc\x1f" +
"6\x8a\xd7\xc83!\x06\x13\xb2\xe0J\xc1/\xbdV\xeb" +
"\xee\x94>\x08\xeaZ^\x83\x1ej\xee\xbaU\xd4\xfb\x14" +
",-A\x8a\xa2\x9dTQ\xbf\xbdj\x09\xb6R\x10\xb7" +
"\xa8\xa8\x7f[\xa9\x9ar\x15\x15\x9aY\xd4\xfe/\x00\x00" +
"\xff\xff\x00\xd1\x99X"
func RegisterSchema(reg *schemas.Registry) {
reg.Register(&schemas.Schema{
+13 -113
View File
@@ -1,11 +1,8 @@
package cereal
import (
"encoding/json"
"log/slog"
"math"
"os"
"regexp"
"capnproto.org/go/capnp/v3"
"pfeifer.dev/mapd/cereal/custom"
@@ -18,8 +15,6 @@ const (
externalFixMaxAge = 500_000_000 // 10 Hz source: 500 ms
internalFixMaxAge = 2_000_000_000 // 1 Hz source: 2 s
carFixMaxAge = 2_500_000_000 // Optional CAN observation: 2.5 s
phoneFixMaxAge = 10_000_000_000 // Companion app in the background sends sparsely: 10 s
gpsModeRefresh = 1_000_000_000 // Galaxy navigation setting reread interval
maxHorizontalAccuracy = 50.0 // input sanity ceiling, not road-match qualification
maxClockPairSkew = 1_000_000 // an interrupted pair cannot date a source event
maxClockOffsetDrift = 1_000_000 // a larger BOOTTIME/MONOTONIC step fences queued fixes
@@ -44,53 +39,8 @@ const (
GpsSourceInternal
GpsSourceExternal
GpsSourceCar
GpsSourcePhone
)
// Galaxy navigation's GPS source setting: backup uses the phone only without
// comma or car GPS, comma never uses it, phone prefers it whenever it has a fix.
const (
GpsModeBackup = "backup"
GpsModeComma = "comma"
GpsModePhone = "phone"
)
var storagePrefix = regexp.MustCompile(`^[A-Za-z0-9_-]{1,64}$`)
func navigationSettingsPath() string {
prefix := os.Getenv("OPENPILOT_PREFIX")
if prefix == "" {
return "/data/starpilot/navigation/settings.json"
}
if !storagePrefix.MatchString(prefix) {
return ""
}
return "/data/starpilot-" + prefix + "/navigation/settings.json"
}
// ReadGpsMode returns the saved choice, or backup when it is missing or invalid.
func ReadGpsMode() string {
path := navigationSettingsPath()
if path == "" {
return GpsModeBackup
}
raw, err := os.ReadFile(path)
if err != nil || len(raw) > 1<<20 {
return GpsModeBackup
}
var settings struct {
GpsSource string `json:"gpsSource"`
}
if json.Unmarshal(raw, &settings) != nil {
return GpsModeBackup
}
switch settings.GpsSource {
case GpsModeComma, GpsModePhone:
return settings.GpsSource
}
return GpsModeBackup
}
type GpsSample struct {
Location log.GpsLocationData
Source GpsSource
@@ -110,12 +60,7 @@ type GpsSub struct {
gpsLocation Subscriber[log.GpsLocationData]
gpsLocationExternal Subscriber[log.GpsLocationData]
carGps *Subscriber[custom.StarPilotCarState_Gps]
phoneGps *Subscriber[custom.StarPilotCarState_Gps]
car gpsCandidate
phone gpsCandidate
mode func() string
modeValue string
modeReadAt uint64
internal gpsCandidate
external gpsCandidate
selected GpsSource
@@ -138,8 +83,6 @@ func GpsFixFreshAt(source GpsSource, fixMonoTime, now uint64) bool {
return now-fixMonoTime <= externalFixMaxAge
case GpsSourceCar:
return now-fixMonoTime <= carFixMaxAge
case GpsSourcePhone:
return now-fixMonoTime <= phoneFixMaxAge
case GpsSourceInternal:
return now-fixMonoTime <= internalFixMaxAge
default:
@@ -191,35 +134,6 @@ func (s *GpsSub) clearCandidates() {
s.internal = gpsCandidate{}
s.external = gpsCandidate{}
s.car = gpsCandidate{}
s.phone = gpsCandidate{}
}
func (s *GpsSub) gpsMode(now uint64) string {
if s.modeValue == "" || now < s.modeReadAt || now-s.modeReadAt >= gpsModeRefresh {
read := s.mode
if read == nil {
read = ReadGpsMode
}
s.modeValue, s.modeReadAt = read(), now
}
return s.modeValue
}
// updateWrapped admits a StarPilotCarState.Gps-shaped fix dated by its own source time.
func (c *gpsCandidate) updateWrapped(event DecodedEvent[custom.StarPilotCarState_Gps], sensor log.GpsLocationData_SensorSource,
clock clockSample, barrierMono, maxAge uint64) bool {
sourceTime := event.Value.SourceMonoTime()
if sourceTime == 0 || sourceTime > event.LogMonoTime || event.LogMonoTime > clock.monoAfter {
return false
}
location, err := carGpsLocation(event.Value)
if err != nil {
return false
}
location.SetSource(sensor)
valid := event.Valid && !math.IsNaN(float64(location.Speed())) && !math.IsInf(float64(location.Speed()), 0) && location.Speed() >= 0 &&
!math.IsNaN(location.Altitude()) && !math.IsInf(location.Altitude(), 0)
return c.updateWithAge(DecodedEvent[log.GpsLocationData]{Value: location, Valid: valid, LogMonoTime: sourceTime}, clock, barrierMono, maxAge)
}
func (s *GpsSub) clockReady(clock clockSample) bool {
@@ -252,7 +166,7 @@ func (s *GpsSub) ReadSample() (sample GpsSample, success bool) {
clock = s.clock()
}
ready := s.clockReady(clock)
internalNew, externalNew, carNew, phoneNew := false, false, false, false
internalNew, externalNew, carNew := false, false, false
if event, ok := s.gpsLocation.ReadEvent(); ok && ready {
internalNew = s.internal.update(event, clock, s.barrierMono)
}
@@ -262,29 +176,23 @@ func (s *GpsSub) ReadSample() (sample GpsSample, success bool) {
if s.carGps != nil {
if event, ok := s.carGps.ReadEvent(); ok && ready {
carNew = s.car.updateWrapped(event, log.GpsLocationData_SensorSource_car, clock, s.barrierMono, carFixMaxAge)
}
}
if s.phoneGps != nil {
if event, ok := s.phoneGps.ReadEvent(); ok && ready {
// The enum has no phone value; android is the closest.
phoneNew = s.phone.updateWrapped(event, log.GpsLocationData_SensorSource_android, clock, s.barrierMono, phoneFixMaxAge)
sourceTime := event.Value.SourceMonoTime()
if sourceTime > 0 && sourceTime <= event.LogMonoTime && event.LogMonoTime <= clock.monoAfter {
location, err := carGpsLocation(event.Value)
if err == nil {
carNew = s.car.updateWithAge(DecodedEvent[log.GpsLocationData]{Value: location, Valid: event.Valid && !math.IsNaN(float64(location.Speed())) && !math.IsInf(float64(location.Speed()), 0) && location.Speed() >= 0 && !math.IsNaN(location.Altitude()) && !math.IsInf(location.Altitude(), 0), LogMonoTime: sourceTime}, clock, s.barrierMono, carFixMaxAge)
}
}
}
}
mode := s.gpsMode(clock.boot)
phoneFresh := ready && mode != GpsModeComma && GpsFixFreshAt(GpsSourcePhone, s.phone.fixMonoTime, clock.boot)
source := GpsSourceNone
if phoneFresh && mode == GpsModePhone {
source = GpsSourcePhone
} else if ready && GpsFixFreshAt(GpsSourceExternal, s.external.fixMonoTime, clock.boot) {
if ready && GpsFixFreshAt(GpsSourceExternal, s.external.fixMonoTime, clock.boot) {
source = GpsSourceExternal
} else if ready && GpsFixFreshAt(GpsSourceInternal, s.internal.fixMonoTime, clock.boot) {
source = GpsSourceInternal
} else if ready && GpsFixFreshAt(GpsSourceCar, s.car.fixMonoTime, clock.boot) {
source = GpsSourceCar
} else if phoneFresh {
source = GpsSourcePhone
}
sample.SourceChanged = source != s.selected
if sample.SourceChanged {
@@ -307,10 +215,6 @@ func (s *GpsSub) ReadSample() (sample GpsSample, success bool) {
sample.Location = s.car.location
sample.FixMonoTime = s.car.fixMonoTime
sample.NewFix = carNew
case GpsSourcePhone:
sample.Location = s.phone.location
sample.FixMonoTime = s.phone.fixMonoTime
sample.NewFix = phoneNew
default:
return sample, false
}
@@ -330,28 +234,24 @@ func (s *GpsSub) Close() {
if s.carGps != nil {
s.carGps.Sub.Msgq.Close()
}
if s.phoneGps != nil {
s.phoneGps.Sub.Msgq.Close()
}
}
func GetGpsSub() (gpsSub GpsSub) {
return GpsSub{
carGps: optionalWrappedGpsSubscriber("starpilotCarState", CarGpsReader),
phoneGps: optionalWrappedGpsSubscriber("starpilotNavigation", PhoneGpsReader),
carGps: optionalCarGpsSubscriber(),
gpsLocation: NewSubscriber("gpsLocation", GpsLocationReader, true, ms.Settings.SubscriberSettings.ShadowGpsLocation),
gpsLocationExternal: NewSubscriber("gpsLocationExternal", GpsLocationExternalReader, true, ms.Settings.SubscriberSettings.ShadowGpsLocationExternal),
}
}
func optionalWrappedGpsSubscriber(service string, reader func(log.Event) (custom.StarPilotCarState_Gps, error)) (subscriber *Subscriber[custom.StarPilotCarState_Gps]) {
func optionalCarGpsSubscriber() (subscriber *Subscriber[custom.StarPilotCarState_Gps]) {
defer func() {
if recover() != nil {
subscriber = nil
slog.Warn("Optional GPS subscriber unavailable", "service", service)
slog.Warn("Optional car GPS subscriber unavailable")
}
}()
value := NewSubscriber(service, reader, true, false)
value := NewSubscriber("starpilotCarState", CarGpsReader, true, false)
return &value
}
+1 -1
View File
@@ -2623,7 +2623,7 @@ struct Event {
# DO change the name of the field and struct
# DON'T change the ID (e.g. @107)
# DON'T change which struct it points to
starpilotNavigation @107 :Custom.StarPilotCarControl;
customReserved0 @107 :Custom.CustomReserved0;
customReserved1 @108 :Custom.CustomReserved1;
starpilotCarState @109 :Custom.StarPilotCarState;
customReserved3 @110 :Custom.CustomReserved3;
File diff suppressed because it is too large Load Diff
-125
View File
@@ -1,125 +0,0 @@
package cereal
import (
"capnproto.org/go/capnp/v3"
"pfeifer.dev/mapd/cereal/custom"
"pfeifer.dev/mapd/cereal/log"
"testing"
)
func phoneGpsWire(t *testing.T, source, envelope uint64) []byte {
t.Helper()
message, segment, err := capnp.NewMessage(capnp.SingleSegment(nil))
if err != nil {
t.Fatal(err)
}
event, err := log.NewRootEvent(segment)
if err != nil {
t.Fatal(err)
}
event.SetLogMonoTime(envelope)
event.SetValid(true)
navigation, err := event.NewStarpilotNavigation()
if err != nil {
t.Fatal(err)
}
gps, err := navigation.NewPhoneGps()
if err != nil {
t.Fatal(err)
}
gps.SetSourceMonoTime(source)
gps.SetHasFix(true)
gps.SetLatitude(41)
gps.SetLongitude(-111)
gps.SetAltitude(100)
gps.SetSpeed(12)
gps.SetBearingDeg(90)
gps.SetHorizontalAccuracy(5)
gps.SetVerticalAccuracy(5)
gps.SetBearingAccuracyDeg(10)
gps.SetSpeedAccuracy(1)
raw, err := message.Marshal()
if err != nil {
t.Fatal(err)
}
return raw
}
func attachPhone(s *GpsSub, mode *string) *[][]byte {
queue := [][]byte{}
s.phoneGps = &Subscriber[custom.StarPilotCarState_Gps]{reader: PhoneGpsReader, maxBytes: 250 * 1024, readBytes: func() []byte {
if len(queue) == 0 {
return nil
}
value := queue[0]
queue = queue[1:]
return value
}}
s.mode = func() string { return *mode }
return &queue
}
func TestPhoneGpsFollowsTheGalaxySetting(t *testing.T) {
now := uint64(10_000_000_000)
mode := GpsModeBackup
s, internal, _ := testGpsSub(&now)
car := attachCar(s)
phone := attachPhone(s, &mode)
*phone = append(*phone, phoneGpsWire(t, now-300_000_000, now))
sample, ok := s.ReadSample()
if !ok || sample.Source != GpsSourcePhone || sample.FixMonoTime != now-300_000_000 || sample.Location.Longitude() != -111 {
t.Fatalf("backup without comma or car GPS: %+v %v", sample, ok)
}
*car = append(*car, carGpsWire(t, now-1, now, true, true))
if sample, ok = s.ReadSample(); !ok || sample.Source != GpsSourceCar {
t.Fatal("car ranks above the phone in backup")
}
*internal = append(*internal, gpsWire(t, GpsSourceInternal, now, true, true, 1, 2, 5))
if sample, ok = s.ReadSample(); !ok || sample.Source != GpsSourceInternal {
t.Fatal("comma ranks above the phone in backup")
}
mode = GpsModePhone
now += gpsModeRefresh
*phone = append(*phone, phoneGpsWire(t, now-100_000_000, now))
*internal = append(*internal, gpsWire(t, GpsSourceInternal, now, true, true, 1, 2, 5))
if sample, ok = s.ReadSample(); !ok || sample.Source != GpsSourcePhone {
t.Fatal("prefer phone")
}
now += phoneFixMaxAge
*internal = append(*internal, gpsWire(t, GpsSourceInternal, now, true, true, 1, 2, 5))
if sample, ok = s.ReadSample(); !ok || sample.Source != GpsSourceInternal {
t.Fatal("prefer phone falls back to comma once the phone fix expires")
}
mode = GpsModeComma
now += gpsModeRefresh
*phone = append(*phone, phoneGpsWire(t, now, now))
if sample, ok = s.ReadSample(); !ok || sample.Source != GpsSourceInternal {
t.Fatal("comma and car only keeps comma GPS")
}
now += internalFixMaxAge + 1
*phone = append(*phone, phoneGpsWire(t, now, now))
if _, ok = s.ReadSample(); ok {
t.Fatal("comma and car only must never use the phone")
}
}
func TestPhoneGpsModeIsRereadAtMostOnceASecond(t *testing.T) {
now := uint64(10_000_000_000)
reads := 0
s, _, _ := testGpsSub(&now)
s.mode = func() string { reads++; return GpsModeBackup }
s.ReadSample()
now += gpsModeRefresh - 1
s.ReadSample()
if reads != 1 {
t.Fatalf("mode reread early: %d", reads)
}
now++
s.ReadSample()
if reads != 2 {
t.Fatalf("mode not reread: %d", reads)
}
}
-8
View File
@@ -45,11 +45,3 @@ func CarGpsReader(evt log.Event) (custom.StarPilotCarState_Gps, error) {
}
return state.Gps()
}
func PhoneGpsReader(evt log.Event) (custom.StarPilotCarState_Gps, error) {
navigation, err := evt.StarpilotNavigation()
if err != nil {
return custom.StarPilotCarState_Gps{}, err
}
return navigation.PhoneGps()
}
-1
View File
@@ -1 +0,0 @@
{"description":"Synthetic Go-produced v2 current-road and data-only preview fixture; no real road data.","event_base64":"AAAAACQAAAAAAAAAAgABAADyBSoBAAAAjwAAAAAAAAAAAAAAEAAHAAAAoEEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIABQABAAAAAAAAAAIAAAAAAHBBgAELJwEAAAAA8gUqAQAAAAEAAAAAAAAAKQAAAAAAAAAAAHBCAAAAAAIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAoCAABhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhAAAAAAAAAAA="}
+2 -52
View File
@@ -1,6 +1,7 @@
package cereal
import (
"bytes"
"capnproto.org/go/capnp/v3"
"encoding/base64"
"encoding/json"
@@ -60,58 +61,7 @@ func TestMapdV1HostWireFixture(t *testing.T) {
if err != nil {
t.Fatal(err)
}
actualMessage, err := capnp.Unmarshal(raw)
if err != nil {
t.Fatal(err)
}
oldMessage, err := capnp.Unmarshal(expected)
if err != nil {
t.Fatal(err)
}
actualRoot, err := actualMessage.Root()
if err != nil {
t.Fatal(err)
}
oldRoot, err := oldMessage.Root()
if err != nil {
t.Fatal(err)
}
// Appended default fields can enlarge storage without changing old values.
equal, err := capnp.Equal(actualRoot, oldRoot)
if err != nil || !equal {
if !bytes.Equal(raw, expected) {
t.Fatal("provider wire differs from shared host fixture; review both schemas")
}
}
func TestPreviewHostWireFixture(t *testing.T) {
data, err := os.ReadFile("testdata/mapd_preview_wire.json")
if err != nil {
t.Fatal(err)
}
var fixture struct {
EventBase64 string `json:"event_base64"`
}
if err := json.Unmarshal(data, &fixture); err != nil {
t.Fatal(err)
}
raw, err := base64.StdEncoding.DecodeString(fixture.EventBase64)
if err != nil {
t.Fatal(err)
}
msg, err := capnp.Unmarshal(raw)
if err != nil {
t.Fatal(err)
}
event, err := log.ReadRootEvent(msg)
if err != nil {
t.Fatal(err)
}
out, err := event.MapdOut()
if err != nil {
t.Fatal(err)
}
boundary, err := out.PreviewBoundaryId()
if err != nil || !event.Valid() || out.SampleVersion() != 2 || out.SpeedLimit() != 20 || out.PreviewSpeedLimit() != 15 || out.PreviewDistance() != 60 || len(boundary) != 64 || out.PreviewWayId() != 2 {
t.Fatal("provider preview differs from shared host fixture")
}
}
-82
View File
@@ -1,82 +0,0 @@
package main
import (
"crypto/sha256"
"fmt"
"math"
"pfeifer.dev/mapd/cereal/custom"
"pfeifer.dev/mapd/maps"
)
const previewHorizonM = 500
const previewMaxWays = 64
type LimitPreview struct {
Speed float32
Distance float32
BoundaryID string
WayID int64
}
// A preview follows only a unique legal continuation, never a guessed turn.
func (s *State) previewLimit() LimitPreview {
if !s.ShadowOnly || s.SnapshotID == "" || s.CurrentWay.SelectionType != custom.WaySelectionType_current || s.MatchedLimitMps <= 0 {
return LimitPreview{}
}
way, forward, position := s.CurrentWay.Way, s.CurrentWay.OnWay.IsForward, s.Position
distance := float32(0)
seen := map[int64]bool{way.Id(): true}
for range previewMaxWays {
_, end := way.GetStartEnd(forward)
if distance+position.DistanceTo(end) > previewHorizonM {
return LimitPreview{}
}
segment, found, err := way.DistanceToNode(position, forward, end)
if err != nil || !found || segment < 0 || math.IsNaN(float64(segment)) || math.IsInf(float64(segment), 0) {
return LimitPreview{}
}
distance += segment
box := s.Data.OverlapBox()
if distance <= 0 || distance > previewHorizonM || !box.PosInside(end) {
return LimitPreview{}
}
matches, err := way.MatchingWays(&s.Data, end)
if err != nil {
return LimitPreview{}
}
legal := map[int64]maps.Way{}
for _, next := range matches {
first, last := next.GetStartEnd(true)
if first.Equals(last) && !next.OneWay() {
return LimitPreview{} // A two-way loop has two possible entry directions.
}
if next.Id() > 0 && (next.IsForwardFrom(end) || !next.OneWay()) {
legal[next.Id()] = next
}
}
if len(legal) != 1 {
return LimitPreview{}
}
var next maps.Way
for _, candidate := range legal {
next = candidate
}
if seen[next.Id()] {
return LimitPreview{}
}
nextForward := next.IsForwardFrom(end)
road := CurrentWay{Way: next, OnWay: maps.OnWayResult{IsForward: nextForward}}
speed := road.EffectiveMaxSpeed()
if speed <= 0 || math.IsNaN(speed) || math.IsInf(speed, 0) || speed > math.MaxFloat32 {
return LimitPreview{}
}
if math.Abs(speed-float64(s.MatchedLimitMps)) > .02 {
key := fmt.Sprintf("%s:%d:%d:%t:%.7f:%.7f", s.SnapshotID, way.Id(), next.Id(), nextForward, end.Lat(), end.Lon())
return LimitPreview{float32(speed), distance, fmt.Sprintf("%x", sha256.Sum256([]byte(key))), next.Id()}
}
seen[next.Id()] = true
way, forward, position = next, nextForward, end
}
return LimitPreview{}
}
-200
View File
@@ -1,200 +0,0 @@
package main
import (
"crypto/sha256"
"fmt"
"math"
"os"
"path/filepath"
"strings"
"testing"
"time"
"capnproto.org/go/capnp/v3"
"pfeifer.dev/mapd/cereal"
"pfeifer.dev/mapd/cereal/custom"
"pfeifer.dev/mapd/cereal/offline"
"pfeifer.dev/mapd/maps"
m "pfeifer.dev/mapd/math"
)
func previewState(t *testing.T, specs []syntheticWay, index int, forward bool, latitude float64) State {
t.Helper()
tile := packedRoadTile(t, specs)
return State{ShadowOnly: true, SnapshotID: "verified-snapshot", Data: tile,
Position: m.NewPosition(latitude, -97.9), MatchedLimitMps: float32(specs[index].speed),
CurrentWay: CurrentWay{Way: tile.Ways.At(index), OnWay: maps.OnWayResult{IsForward: forward}, SelectionType: custom.WaySelectionType_current}}
}
func previewRoads() []syntheticWay {
return []syntheticWay{
{1, 20, 35.1, -97.9, 35.101, -97.9, false, 2},
{2, 20, 35.101, -97.9, 35.102, -97.9, false, 2},
{3, 10, 35.102, -97.9, 35.103, -97.9, false, 2},
}
}
func TestPreviewRawDistanceAndStableBoundaryAcrossApproachWays(t *testing.T) {
s := previewState(t, previewRoads(), 0, true, 35.1005)
a := s.previewLimit()
s = previewState(t, previewRoads(), 1, true, 35.1015)
b := s.previewLimit()
if a.Speed != 10 || a.WayID != 3 || a.BoundaryID == "" || a.BoundaryID != b.BoundaryID || math.Abs(float64(a.Distance-b.Distance)-111.2) > 1 {
t.Fatalf("unexpected road preview: %+v %+v", a, b)
}
s.Position = m.NewPosition(35.1014, -97.9)
if s.previewLimit().Distance <= b.Distance {
t.Fatal("raw distance was held at a previous minimum")
}
s.SnapshotID = "changed-snapshot"
if s.previewLimit().BoundaryID == b.BoundaryID {
t.Fatal("boundary identity survived a different snapshot")
}
}
func TestPreviewDirectionUnknownLimitsBranchesAndHorizon(t *testing.T) {
s := previewState(t, previewRoads(), 2, false, 35.1025)
if p := s.previewLimit(); p.Speed != 20 || p.WayID != 2 || p.Distance <= 0 {
t.Fatalf("reverse traversal failed: %+v", p)
}
for _, mode := range []string{"branch", "unknown", "oneway", "horizon", "unqualified", "unverified"} {
t.Run(mode, func(t *testing.T) {
roads := previewRoads()
index, forward, latitude := 0, true, 35.1005
switch mode {
case "branch":
roads = append(roads, syntheticWay{4, 30, 35.101, -97.9, 35.102, -97.899, false, 2})
case "unknown":
roads[1].speed = 0
case "oneway":
roads[1].oneWay = true
index, forward, latitude = 2, false, 35.1025
case "horizon":
roads[0].lat1 = 35.09
latitude = 35.091
}
s := previewState(t, roads, index, forward, latitude)
if mode == "unqualified" {
s.CurrentWay.SelectionType = custom.WaySelectionType_possible
}
if mode == "unverified" {
s.SnapshotID = ""
}
if p := s.previewLimit(); p != (LimitPreview{}) {
t.Fatalf("uncertain preview escaped: %+v", p)
}
})
}
}
func TestPreviewClosedWayRequiresOneLegalDirection(t *testing.T) {
for _, tc := range []struct {
name string
oneWay, branch, wantPreview bool
}{
{"one-way loop", true, false, true},
{"two-way loop", false, false, false},
{"two-way loop plus continuation", false, true, false},
} {
t.Run(tc.name, func(t *testing.T) {
roads := []syntheticWay{
{1, 20, 35.1, -97.9, 35.101, -97.9, true, 2},
{2, 10, 35.101, -97.9, 35.102, -97.9, tc.oneWay, 2},
}
if tc.branch {
roads = append(roads, syntheticWay{3, 15, 35.101, -97.9, 35.102, -97.899, false, 2})
}
decoded, err := capnp.UnmarshalPacked(packedRoadTileBytes(t, roads))
if err != nil {
t.Fatal(err)
}
root, err := decoded.Root()
if err != nil {
t.Fatal(err)
}
msg, _, err := capnp.NewMessage(capnp.SingleSegment(nil))
if err != nil {
t.Fatal(err)
}
if err := msg.SetRoot(root); err != nil {
t.Fatal(err)
}
raw, err := offline.ReadRootOffline(msg)
if err != nil {
t.Fatal(err)
}
ways, err := raw.Ways()
if err != nil {
t.Fatal(err)
}
loop := ways.At(1)
loop.SetMaxLon(-97.898)
nodes, err := loop.NewNodes(4)
if err != nil {
t.Fatal(err)
}
for i, p := range [][2]float64{{35.101, -97.9}, {35.102, -97.9}, {35.102, -97.899}, {35.101, -97.9}} {
nodes.At(i).SetLatitude(p[0])
nodes.At(i).SetLongitude(p[1])
}
data, err := msg.MarshalPacked()
if err != nil {
t.Fatal(err)
}
tile := maps.ReadOffline(data)
if !tile.Loaded {
t.Fatal("closed road tile rejected")
}
s := State{ShadowOnly: true, SnapshotID: "verified-snapshot", Data: tile,
Position: m.NewPosition(35.1005, -97.9), MatchedLimitMps: 20,
CurrentWay: CurrentWay{Way: tile.Ways.At(0), OnWay: maps.OnWayResult{IsForward: true}, SelectionType: custom.WaySelectionType_current}}
p := s.previewLimit()
if tc.wantPreview {
if p.Speed != 10 || p.WayID != 2 || p.Distance <= 0 || p.BoundaryID == "" {
t.Fatalf("legal loop preview missing: %+v", p)
}
} else if p != (LimitPreview{}) {
t.Fatalf("ambiguous loop produced a preview: %+v", p)
}
})
}
}
func TestShadowPreviewSharesFixFreshnessWithoutControlOutputs(t *testing.T) {
roads := []syntheticWay{{1, 20, 35.149, -97.9, 35.151, -97.9, false, 2}, {2, 10, 35.151, -97.9, 35.153, -97.9, false, 2}}
data := packedRoadTileBytes(t, roads)
id := strings.Repeat("a", 64)
dir := filepath.Join(t.TempDir(), id)
area := maps.Area{Box: m.Box{MinPos: m.NewPosition(35, -98), MaxPos: m.NewPosition(35.25, -97.75)}}
path := maps.GenerateBoundsFileName(area, maps.OfflineSettings{OutputDirectory: dir})
if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(path, data, 0644); err != nil {
t.Fatal(err)
}
rel, err := filepath.Rel(dir, path)
if err != nil {
t.Fatal(err)
}
load := maps.SnapshotLoader(dir, maps.SnapshotReceipt{Tiles: []maps.SnapshotTile{{Path: rel, Size: int64(len(data)), SHA256: fmt.Sprintf("%x", sha256.Sum256(data))}}})
s := State{ShadowOnly: true, SnapshotID: id}
s.Init()
boot := uint64(10_100_000_000)
s.bootNow = func() uint64 { return boot }
sample := syntheticSample(t, cereal.GpsSourceExternal, 10_000_000_000, 1, true, true)
s.ProcessGps(sample, true, load, time.Unix(0, 0))
sample.SourceChanged, sample.FixMonoTime = false, 10_050_000_000
s.ProcessGps(sample, true, load, time.Unix(0, 1))
event, output := decodedOutput(t, &s)
boundary, _ := output.PreviewBoundaryId()
if !event.Valid() || output.SpeedLimit() != 20 || output.PreviewSpeedLimit() != 10 || boundary == "" || output.PreviewDistance() <= 0 || output.NextSpeedLimit() != 0 || output.SuggestedSpeed() != 0 {
t.Fatalf("shadow preview: valid=%v status=%v way=%v limit=%v preview=%+v", event.Valid(), output.RoadStatus(), output.WaySelectionType(), output.SpeedLimit(), s.LimitPreview)
}
boot = 10_600_000_000
event, output = decodedOutput(t, &s)
boundary, _ = output.PreviewBoundaryId()
if event.Valid() || output.PreviewSpeedLimit() != 0 || boundary != "" {
t.Fatal("expired GPS retained an upcoming limit")
}
}
+1 -12
View File
@@ -11,7 +11,6 @@ import (
"os"
"reflect"
"runtime"
"slices"
"strconv"
"strings"
"syscall"
@@ -163,6 +162,7 @@ func GenerateOffline(s OfflineSettings) error {
MaxSpeedBackward: ParseMaxSpeed(tags["maxspeed:backward"]),
MaxSpeedAdvisory: ParseMaxSpeed(tags["maxspeed:advisory"]),
Lanes: uint8(lanes),
OneWay: tags["oneway"] == "yes",
Id: int64(way.ID),
HighwayClass: HighwayClassFromTag(tags["highway"]),
@@ -191,17 +191,6 @@ func GenerateOffline(s OfflineSettings) error {
tmpWay.Nodes[i].Latitude = n.Lat
tmpWay.Nodes[i].Longitude = n.Lon
}
switch tags["oneway"] {
case "yes", "1":
tmpWay.OneWay = true
case "-1":
tmpWay.OneWay = true
slices.Reverse(tmpWay.Nodes)
tmpWay.MaxSpeedForward, tmpWay.MaxSpeedBackward = tmpWay.MaxSpeedBackward, tmpWay.MaxSpeedForward
tmpWay.MaxSpeedForwardConditional, tmpWay.MaxSpeedBackwardConditional = tmpWay.MaxSpeedBackwardConditional, tmpWay.MaxSpeedForwardConditional
case "":
tmpWay.OneWay = tags["junction"] == "roundabout" || tags["highway"] == "motorway"
}
tmpWay.Box.MinPos = m.NewPosition(minLat, minLon)
tmpWay.Box.MaxPos = m.NewPosition(maxLat, maxLon)
scannedWays = append(scannedWays, tmpWay)
-78
View File
@@ -1,78 +0,0 @@
package maps
import (
"math"
"os"
"path/filepath"
"testing"
m "pfeifer.dev/mapd/math"
)
func TestGeneratorPreservesFixedOneWayDirectionAndSpeedTags(t *testing.T) {
for _, tc := range []struct {
name, oneWay, highway, junction string
wantOneWay, reverse bool
}{
{"ordinary", "", "residential", "", false, false},
{"yes", "yes", "residential", "", true, false},
{"numeric", "1", "residential", "", true, false},
{"reverse", "-1", "residential", "", true, true},
{"roundabout", "", "residential", "roundabout", true, false},
{"motorway", "", "motorway", "", true, false},
{"roundabout explicit no", "no", "residential", "roundabout", false, false},
{"roundabout explicit zero", "0", "residential", "roundabout", false, false},
{"motorway explicit no", "no", "motorway", "", false, false},
{"motorway explicit zero", "0", "motorway", "", false, false},
{"motorway link", "", "motorway_link", "", false, false},
{"reversible", "reversible", "residential", "roundabout", false, false},
{"alternating", "alternating", "motorway", "", false, false},
} {
t.Run(tc.name, func(t *testing.T) {
forwardRule, backwardRule := "15 @ (Mo-Fr 08:00-09:00)", "25 @ (Sa 10:00-11:00)"
tags := []string{"highway", tc.highway, "maxspeed", "30 mph",
"maxspeed:forward", "10", "maxspeed:backward", "20",
"maxspeed:forward:conditional", forwardRule, "maxspeed:backward:conditional", backwardRule}
if tc.oneWay != "" {
tags = append(tags, "oneway", tc.oneWay)
}
if tc.junction != "" {
tags = append(tags, "junction", tc.junction)
}
root := t.TempDir()
pbf := filepath.Join(root, "road.osm.pbf")
if err := os.WriteFile(pbf, syntheticPBF(tags...), 0600); err != nil {
t.Fatal(err)
}
output := filepath.Join(root, "tiles")
if err := GenerateOffline(OfflineSettings{InputFile: pbf, OutputDirectory: output, Overlap: .001,
Box: m.Box{MinPos: m.NewPosition(35, -98), MaxPos: m.NewPosition(35.25, -97.75)}}); err != nil {
t.Fatal(err)
}
tile, err := FindWaysAroundPositionIn(m.NewPosition(35.15, -97.9), output)
if err != nil || !tile.Loaded || tile.Ways.Len() != 1 {
t.Fatalf("generated road not loaded: %v", err)
}
way := tile.Ways.At(0)
if way.Nodes.Len() != 2 {
t.Fatalf("generated road has %d nodes", way.Nodes.Len())
}
first, last := 35.1, 35.2
forwardSpeed, backwardSpeed := 10./3.6, 20./3.6
if tc.reverse {
first, last = last, first
forwardSpeed, backwardSpeed = backwardSpeed, forwardSpeed
forwardRule, backwardRule = backwardRule, forwardRule
}
firstNode, lastNode := way.Nodes.At(0), way.Nodes.At(1)
if way.Id() != 42 || way.OneWay() != tc.wantOneWay ||
math.Abs(firstNode.Lat()-first) > 1e-9 || math.Abs(lastNode.Lat()-last) > 1e-9 ||
math.Abs(way.MaxSpeed()-13.4112) > 1e-6 ||
math.Abs(way.MaxSpeedForward()-forwardSpeed) > 1e-5 || math.Abs(way.MaxSpeedBackward()-backwardSpeed) > 1e-5 ||
way.ConditionalMaxSpeedRaw(true) != forwardRule || way.ConditionalMaxSpeedRaw(false) != backwardRule {
t.Fatalf("generated road lost direction or speed metadata: oneWay=%v forward=%v backward=%v",
way.OneWay(), way.MaxSpeedForward(), way.MaxSpeedBackward())
}
})
}
}
+4 -12
View File
@@ -309,25 +309,17 @@ func pbfBlock(kind string, raw []byte) []byte {
data = append(data, header...)
return append(data, blob...)
}
func syntheticPBF(tags ...string) []byte {
func syntheticPBF() []byte {
header := pbfBytesField(nil, 4, []byte("OsmSchema-V0.6"))
header = pbfBytesField(header, 5, []byte("LocationsOnWays"))
if len(tags) == 0 {
tags = []string{"highway", "residential", "maxspeed", "30 mph"}
}
var table []byte
for _, value := range append([]string{""}, tags...) {
for _, value := range []string{"", "highway", "residential", "maxspeed", "30 mph"} {
table = pbfBytesField(table, 1, []byte(value))
}
var keys, values []uint64
for i := 0; i < len(tags); i += 2 {
keys = append(keys, uint64(i+1))
values = append(values, uint64(i+2))
}
var way []byte
way = pbfVarintField(way, 1, 42)
way = pbfBytesField(way, 2, pbfPacked(keys...))
way = pbfBytesField(way, 3, pbfPacked(values...))
way = pbfBytesField(way, 2, pbfPacked(1, 3))
way = pbfBytesField(way, 3, pbfPacked(2, 4))
way = pbfBytesField(way, 8, pbfPacked(protowire.EncodeZigZag(1), protowire.EncodeZigZag(1)))
way = pbfBytesField(way, 9, pbfPacked(protowire.EncodeZigZag(351000000), protowire.EncodeZigZag(1000000)))
way = pbfBytesField(way, 10, pbfPacked(protowire.EncodeZigZag(-979000000), protowire.EncodeZigZag(0)))
+6 -9
View File
@@ -149,12 +149,8 @@ func (w *Way) IsForwardFrom(matchNode m.Position) bool {
return true
}
lastNode := w.Nodes.At(w.Nodes.Len() - 1)
if lastNode.Equals(matchNode) {
// A closed one-way can be entered at its repeated endpoint in stored order.
return w.OneWay() && matchNode.Equals(w.Nodes.At(0))
}
return true
lastNode := w.Nodes.At(w.Nodes.Len()-1)
return !lastNode.Equals(matchNode)
}
func IsForward(lineStart m.Position, lineEnd m.Position, bearing float64) bool {
@@ -435,7 +431,7 @@ func (w *Way) DistanceFrom(pos m.Position) (DistanceResult, error) {
minIdx := 0
for i := 0; i < w.Nodes.Len()-1; i++ {
nodeStart := w.Nodes.At(i)
nodeEnd := w.Nodes.At(i + 1)
nodeEnd := w.Nodes.At(i+1)
line := m.Line{Start: nodeStart, End: nodeEnd}
linePosition := line.NearestPosition(pos)
distance := pos.DistanceTo(linePosition.Pos)
@@ -451,7 +447,7 @@ func (w *Way) DistanceFrom(pos m.Position) (DistanceResult, error) {
onWayDistance := minNodeStart.DistanceTo(minLinePosition.Pos)
for i := range minIdx {
nodeStart := w.Nodes.At(i)
nodeEnd := w.Nodes.At(i + 1)
nodeEnd := w.Nodes.At(i+1)
onWayDistance += nodeStart.DistanceTo(nodeEnd)
}
@@ -495,7 +491,8 @@ func (w *Way) MatchingWays(offlineMaps *Offline, matchNode m.Position) ([]Way, e
continue
}
if way.Id() == w.Id() {
box := way.Box()
if box.Equals(w.Box()) {
continue
}
-45
View File
@@ -55,48 +55,3 @@ func TestBearingAlignmentIsAnUndirectedNonnegativePenalty(t *testing.T) {
}
}
}
func TestWayEntryDirectionForOpenAndClosedWays(t *testing.T) {
start, end := m.NewPosition(35.15, -97.9), m.NewPosition(35.151, -97.9)
for _, tc := range []struct {
name string
closed, oneWay, fromEnd, wantForward bool
}{
{"open start", false, true, false, true},
{"open end", false, true, true, false},
{"closed one-way", true, true, false, true},
{"closed two-way", true, false, false, false},
} {
t.Run(tc.name, func(t *testing.T) {
_, seg, err := capnp.NewMessage(capnp.SingleSegment(nil))
if err != nil {
t.Fatal(err)
}
raw, err := offline.NewRootWay(seg)
if err != nil {
t.Fatal(err)
}
raw.SetOneWay(tc.oneWay)
positions := []m.Position{start, end}
if tc.closed {
positions = append(positions, start)
}
nodes, err := raw.NewNodes(int32(len(positions)))
if err != nil {
t.Fatal(err)
}
for i, p := range positions {
nodes.At(i).SetLatitude(p.Lat())
nodes.At(i).SetLongitude(p.Lon())
}
from := start
if tc.fromEnd {
from = end
}
way := NewWay(raw)
if got := way.IsForwardFrom(from); got != tc.wantForward {
t.Fatalf("entry direction: got %v want %v", got, tc.wantForward)
}
})
}
}
+1 -7
View File
@@ -24,7 +24,7 @@ type syntheticWay struct {
// The actual offline Capnp representation is packed, decoded, and passed to
// State; tests do not mock GetCurrentWay or BuildMessage.
func packedRoadTileBytes(tb testing.TB, specs []syntheticWay) []byte {
func packedRoadTile(tb testing.TB, specs []syntheticWay) maps.Offline {
tb.Helper()
msg, seg, err := capnp.NewMessage(capnp.SingleSegment(nil))
if err != nil {
@@ -65,12 +65,6 @@ func packedRoadTileBytes(tb testing.TB, specs []syntheticWay) []byte {
if err != nil {
tb.Fatal(err)
}
return data
}
func packedRoadTile(tb testing.TB, specs []syntheticWay) maps.Offline {
tb.Helper()
data := packedRoadTileBytes(tb, specs)
parsed := maps.ReadOffline(data)
if !parsed.Loaded {
tb.Fatal("packed tile rejected")
-1
View File
@@ -61,7 +61,6 @@ var ServiceQueueSize = map[string]int64{
"selfdriveState": QUEUE_SIZE_SMALL,
"gpsLocation": QUEUE_SIZE_SMALL,
"starpilotCarState": QUEUE_SIZE_SMALL,
"starpilotNavigation": QUEUE_SIZE_MEDIUM,
"gpsLocationExternal": QUEUE_SIZE_SMALL,
"liveLocationKalman": QUEUE_SIZE_SMALL,
"gpsNMEA": QUEUE_SIZE_SMALL,
+1 -10
View File
@@ -46,7 +46,6 @@ type State struct {
SourceGeneration uint64
ProducerSession uint64
MatchedLimitMps float32
LimitPreview LimitPreview
lastMapLoadAttempt time.Time
bootNow func() uint64
// The fix the current road result was computed from. The loop runs at
@@ -91,7 +90,6 @@ func (s *State) clearRoadDerived() {
s.TargetVelocities = nil
s.MapCurveSpeed = 0
s.MatchedLimitMps = 0
s.LimitPreview = LimitPreview{}
s.NextHazard.Reset()
s.NextAdvisorySpeed.Reset()
s.clearSpeedLimitEvidence()
@@ -178,7 +176,7 @@ func (s *State) ProcessGps(sample cereal.GpsSample, success bool, load MapLoader
pos := m.PosFromLocation(location)
s.Position = pos
// Unknown CAN direction or speed uncertainty cannot create confident road evidence.
if (sample.Source == cereal.GpsSourceCar || sample.Source == cereal.GpsSourcePhone) && (math.IsNaN(float64(location.BearingAccuracyDeg())) || math.IsInf(float64(location.BearingAccuracyDeg()), 0) || location.BearingAccuracyDeg() <= 0 || location.BearingAccuracyDeg() >= 180 || math.IsNaN(float64(location.SpeedAccuracy())) || math.IsInf(float64(location.SpeedAccuracy()), 0) || location.SpeedAccuracy() >= 100) {
if sample.Source == cereal.GpsSourceCar && (math.IsNaN(float64(location.BearingAccuracyDeg())) || math.IsInf(float64(location.BearingAccuracyDeg()), 0) || location.BearingAccuracyDeg() <= 0 || location.BearingAccuracyDeg() >= 180 || math.IsNaN(float64(location.SpeedAccuracy())) || math.IsInf(float64(location.SpeedAccuracy()), 0) || location.SpeedAccuracy() >= 100) {
s.clearRoadDerived()
s.roadFixMonoTime = 0
s.RoadStatus = custom.MapdOut_SampleStatus_noMatch
@@ -257,7 +255,6 @@ func (s *State) ProcessGps(sample cereal.GpsSample, success bool, load MapLoader
s.MatchedLimitMps = float32(limit)
s.RoadStatus = custom.MapdOut_SampleStatus_matchedLimit
}
s.LimitPreview = s.previewLimit()
}
func (s *State) SuggestedSpeed() float32 {
@@ -364,12 +361,6 @@ func (s *State) buildMessageAt(now uint64) (*capnp.Message, error) {
output.SetRoadName(s.CurrentWay.Way.Name())
output.SetSpeedLimit(s.MatchedLimitMps)
if s.LimitPreview.BoundaryID != "" {
output.SetPreviewSpeedLimit(s.LimitPreview.Speed)
output.SetPreviewDistance(s.LimitPreview.Distance)
output.SetPreviewBoundaryId(s.LimitPreview.BoundaryID)
output.SetPreviewWayId(s.LimitPreview.WayID)
}
output.SetConditionalSpeedLimit(s.CurrentWay.ConditionalMaxSpeedRaw())
@@ -1 +0,0 @@
.github export-ignore
@@ -1 +0,0 @@
__pycache__/
@@ -1,53 +1,35 @@
# Credits
# BluePilot angle source
The BluePilot Ford lateral library: Ford's four-signal lateral control in curvature and angle
modes, the CAN messages that carry it, and the panda safety that checks it. Everything here is
under the MIT terms in [LICENSE](LICENSE).
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.
## Contributors
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.
- **Alan Polk (`alan-polk`)**: principal author of the curvature and angle controllers, the
human-turn behavior, the angle-mode side channel and its panda safety, and the lane centering
trim.
- **tonesto7**: the CAN message builders and BluePilot's early releases.
- **John Christman**: lateral integration, platform data, and the angle-mode anti-stall work.
- **Jacob Neulight**: the steering-pinion curvature measurement and its panda safety, and the
shadow-curvature measurement.
- **Blue Genie (`blue-genie`)**: the split of BluePilot's lateral control into opendbc that this
library grew from.
- **ghbarker**: the lane centering trim's confidence blend, fallback, filter and rate limit.
- **Nathan Ingraham**: the angle-mode high-speed damping adjustment.
- **Praeuner**: the angle-mode damping range.
- **OneFast440**: the early Ford safety declarations.
- **nitrobass24**: the library's structure, its inputs and settings plumbing, and the safety tests
and CI.
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.
## Third-party code
### comma.ai's opendbc
MIT, Copyright (c) 2020, Comma.ai, Inc.
- `can/fordcan_ext.py`: `create_lat_ctl_msg` and `create_lat_ctl2_msg`, comma's Ford lateral
message builders from `opendbc/car/ford/fordcan.py`, with ramp-type and precision parameters
added.
- `safety/lateral.h`: the measured-table rate check, curvature-error band and lateral-accel cap,
from comma's earlier checks in `opendbc/safety/lateral.h`, and `ford_bp_curvature_cmd_checks`,
adapted from comma's `steer_curvature_cmd_checks`.
- `safety/ford.h`: the rate-of-change shape of the path angle and path offset checks, the
curvature-error band in the shadow-curvature check, and the message-rate formula.
- `core/lateral_curv_ext.py`: `apply_ford_curvature_limits_ext`, adapted from comma's
`apply_ford_curvature_limits`, with its road-roll and lateral-accel constants.
- Small pieces: the message packing and the yaw-rate curvature measurement in
`core/carcontroller_ext.py`, and the model time-index formula in `core/values_ext.py`.
- The BluePilot safety tests start from comma's Ford safety test skeletons.
### StarPilot
MIT, Copyright (c) 2026, firestar5683 and StarPilot contributors
- `core/lane_center_trim.py`: the lane-centering core (the correction formula, lookahead clip,
lane-line probability, std and width gates, the 0.004 correction limit and the lane-line
handling), ported from StarPilot's `selfdrive/controls/lib/lane_centering.py`
(`LaneCenteringController`, originally by jc01rho). The confidence blend, fallback, filter and
rate limit are BluePilot's.
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.
@@ -1,83 +0,0 @@
# Bringing BluePilot lateral to a fork
How an openpilot fork takes BluePilot's Ford lateral control. There are two ways to do it:
1. **Use a release on your own** (preferred). Pin a release of this library and write your own hooks and settings against [HOSTS.md](HOSTS.md). BluePilot isn't in the loop and nothing waits on BluePilot: you consume lateral code that has been driven on Fords.
2. **Work with BluePilot.** BluePilot helps develop your hooks, keeps them in this repo, and tests the library on your fork in its CI, every PR and every night.
Either way the library is the same, and the same rules apply to it (below).
**This is a modified Ford safety model.** The panda safety allows signals and ranges that upstream's Ford safety blocks. Your fork decides whether to ship it, and whether BluePilot lateral is on or off by default for your users.
## The rules for either way
- **Pin a release, unmodified.** The library sits at `<pkg>/bluepilot_lateral/` in your opendbc (`<pkg>` is its package name) as one of:
- a **git submodule** pointing at a release tag, if your fork uses submodules; updating is moving the pointer;
- a **stamped copy** made with `tools/vendor.sh`, if it doesn't (see "The stamp tools").
- **Don't edit inside the library folder**, carry it as a git subtree with its history, or copy parts of it elsewhere. A fix to the library is a PR to this repo; once it's released, every fork gets it.
- **Everything else is yours:** the hooks in your opendbc, the code in your openpilot that fills the library's inputs every frame, and your settings UI.
## Option 1: use a release on your own
1. Pick a release from this repo's releases. Each one says what changed in the lateral control, the CAN messages and the panda safety, and what was validated on a car.
2. Mount it (submodule or stamped copy, above).
3. Write the hooks in your opendbc. [HOSTS.md](HOSTS.md) has the contract: the hook sites, the per-frame inputs and settings, the startup safety bits, and the host bindings to define if your safety function names differ from upstream opendbc's. Each release attaches the hook patch for sunnypilot/opendbc as a worked example.
4. Write your adapter: the small module that hands the library your fork's types (`hosts/sunnypilot/` is the example to copy). It lives in your fork, outside the library folder.
5. Run the library's tests in your tree ([HOSTS.md](HOSTS.md), "Running the tests") and drive it before you ship it.
6. To update, move to a newer release and rerun your tests.
BluePilot doesn't review or approve any of it. Questions and bugs in the library are welcome as issues in this repo.
## Option 2: work with BluePilot
For a fork that wants BluePilot to help with the hooks and keep them working. Open an issue in this repo, "Host: <fork>": where the fork's source and integration branch are, how it carries its opendbc, and how it takes outside changes. From there, this repo keeps for that fork:
- **its adapter**, `hosts/<fork>/`, plus host bindings if its safety names differ from upstream's;
- **its hooks**, `hosts/<fork>/hooks.patch`, until the fork carries them;
- **`hosts/<fork>/host.sh`**: `tree <dir>` builds the fork's opendbc at a pinned commit with the hooks and the library, placed by `vendor.sh`; `test <dir>` runs the library tests, the fork's safety suite with the BluePilot safety tests, and coverage; `make <dir>` writes `hooks.patch` back after a hook is edited in `<dir>/host`;
- **a CI job** that runs `host.sh tree` and `test` on every PR to this repo, so a library change that would break the fork fails here first;
- **a nightly check** that tries the fork's latest integration branch: a pass moves the pinned commit, a failure opens one issue saying which step broke. Once the fork carries the hooks it tests the fork's tree as it is, and runs `check_vendored.sh` on its copy.
The steps:
1. Develop and test the hooks and the fork's side in the fork, together.
2. Add the adapter, `hooks.patch`, `host.sh`, the CI job and the nightly check here, in one PR.
3. Release the library with them.
4. BluePilot opens the PR to the fork: the hooks, its settings UI and the library at that release. Later releases arrive the same way, as PRs the fork takes when it chooses.
An adapter lives in this repo only if this repo's CI tests the library on that fork.
## The stamp tools
For a fork that takes no submodules. Both run from a clone of this repo that has the release tag (`git fetch --tags`).
**`tools/vendor.sh <tag> <folder>`** makes `<folder>` exactly the library at `<tag>`:
- it empties the folder first, so files a release removed don't linger;
- it copies the release's files, without the library's own CI (`.github/`);
- it writes `<folder>/VERSION`: the tag and the commit, e.g. `v1.2.3 0a1b2c3d...`.
```bash
git clone https://github.com/BluePilotDev/bluepilot-lateral.git
cd bluepilot-lateral
tools/vendor.sh <tag> <fork checkout>/<path to its opendbc package>/bluepilot_lateral
```
Commit the folder in the fork. To update, run it again with the new tag: the diff shows exactly what changed between the two releases.
**`tools/check_vendored.sh <folder>`** reads `<folder>/VERSION` and compares the folder with that release, file by file (Python caches ignored). It lists every added, removed or changed file, and exits non-zero if there is one:
```bash
tools/check_vendored.sh <fork checkout>/<path to its opendbc package>/bluepilot_lateral
```
Run it in your CI to catch an edit to the copy. For a fork working with BluePilot, this repo's nightly check runs it too.
## Installer note: nested submodule
A fork that embeds the library as a *nested* submodule (Option 2 — e.g. `fork → opendbc → opendbc/bluepilot_lateral`) can end up with the library missing after an end-user install. Some installers run a non-recursive `git submodule update --init`, which checks out the first-level submodule but not the library nested inside it, and the build then fails to import it. Installs that use `git submodule update --init --recursive` are unaffected.
If your fork is installed that way, self-heal on launch: before the build imports the library, when its directory is empty, run a recursive submodule update scoped to the embedding submodule — guard on the library's `__init__.py`, retry, and fail soft so an offline boot is no worse than before.
## How BluePilot releases
- Lateral changes and changes to the library's safety headers are driven on a car before they're released.
- Every release says what changed in the lateral control, the CAN messages and the panda safety, and what was validated.
@@ -1,129 +0,0 @@
# Hosting the BluePilot lateral
A host is an opendbc fork with this library at `<pkg>/bluepilot_lateral/` and the hook patch applied, plus the openpilot on top of it that fills the library's inputs each frame. `<pkg>` is the fork's opendbc package: `opendbc` on sunnypilot/opendbc (ford-op/opendbc, under bp-sunnypilot), `iqdbc` on IQ.Pilot, `opendbc` on StarPilot. This page is what a host provides and what it gets back.
## Mounting the library
A host mounts this repo at `<pkg>/bluepilot_lateral/`, directly inside its opendbc package, as a git submodule (ford-op/opendbc) or, in a host that takes no submodules (IQPilot, at `artifacts/package_sources/iqdbc/iqdbc/bluepilot_lateral/`), as a stamped copy of a release. Updating is a bump of the submodule's commit, or vendoring the new release (below). The hook patch below carries every file ford-op/opendbc adds or changes outside the library, so since it mounts the library it also carries the mount's `.gitmodules` entry.
The library never names its host's package. Python imports are relative: the library's own modules by `.`/`..`, the host's opendbc by one more level (`from ...car.ford.values import CarControllerParams` in `core/`), and `tests/test_core_imports.py` fails on any absolute `opendbc`/`iqdbc`/`openpilot` import. Safety headers include each other as `../safety/<file>.h` and the host's declarations as `../../safety/declarations.h`, relative to the including file. The host includes the library's safety as `"<pkg>/bluepilot_lateral/safety/ford.h"`.
### Without submodules: a stamped copy
From a clone of this repo, `tools/vendor.sh <release tag> <host>/<pkg>/bluepilot_lateral` makes the folder exactly the library at that tag (files it no longer has are removed), without `.github/` (`.gitattributes`), plus a `VERSION` file: the tag and the commit. Nothing inside the folder is ever edited: a change goes into this repo, gets released, and the host vendors the new tag. `tools/check_vendored.sh <folder>` lists anything in the folder that differs from the release in its `VERSION` and fails if there is something; a host can run it in its CI, and this repo's IQPilot checks run it on IQPilot's copy.
### Host bindings
The safety headers are written against upstream opendbc's names. A host whose names differ defines these before it includes `safety/ford.h` (`safety/lateral_declarations.h` has the defaults):
| macro | default (upstream, sunnypilot) | IQ.Pilot |
|---|---|---|
| `BP_HOST_CURVATURE_LIMITS` | `CurvatureSteeringLimits` | `NativeCurvatureSteeringLimits` |
| `BP_HOST_CURVATURE_STATE` | `curvature_state` | `native_curvature_state` |
| `BP_HOST_RT_CURVATURE_RATE_CHECK` | `rt_curvature_rate_limit_check` | `rt_native_curvature_rate_limit_check` |
| `BP_HOST_LAT_ALLOWED()` | `(controls_allowed \|\| controls_allowed_lateral)` | `is_lat_active()` |
| `BP_HOST_SPEED_MISMATCH_CHECK()` | `speed_mismatch_check(vehicle_speed_2 ...)` | `((void)0)`: IQ's `ford_rx_hook` runs it |
The limits struct needs only `max_curvature`, `curvature_to_can`, `frequency`, `max_curvature_error` and `curvature_error_min_speed`.
## The hook patch
`tools/make_hook_patch.sh` prints it: every file outside the library that ford-op/opendbc changes from `master`, minus its own `.github/` (its CI). It fails unless the edited files are exactly the non-`.github` entries of `.github/bluepilot-hooks.txt`.
| file | what the hook does |
|---|---|
| `opendbc/car/ford/carcontroller.py` | Builds one `BluePilotLateral(CP, CP_SP, packer, CAN)`, the sunnypilot adapter (`hosts/sunnypilot/lateral.py`, below). Each frame `bp.update(CC_SP, frame)` says whether BluePilot lateral is active; if it is, `bp.step_lateral` sends the steering message at `STEER_STEP` (and returns the curvature to pass back next time) and `bp.step_lka` sends Lane_Assist_Data1 at `LKA_STEP`. Otherwise the stock path runs. |
| `opendbc/car/structs.py` | Imports `LateralInputs` from `host_types.py` and adds `CarControlSP.lateralInputs` and `CarParamsSP.lateralInputsRequired`. |
| `opendbc/sunnypilot/car/interfaces.py` | Calls `init_ford_safety_param_sp(CP, CP_SP, params_dict)` (`hosts/sunnypilot/safety_param.py`) at car init: the startup safety bits below, and `lateralInputsRequired` for every Ford. |
| `opendbc/safety/modes/ford.h` | Includes `safety/ford.h` and makes one call per hook site: counter and quality checks for the pinion message, the yaw measurement skipped while the pinion source is on, `ford_bp_rx_hook` (pinion measurement), `ford_bp_lka_tx` (angle-mode state from Lane_Assist_Data1), `ford_bp_lmc_tx` in place of the stock steering check when `BP_LATERAL` is set (the stock check runs unchanged when it isn't), and the pinion RX check list from `ford_bp_init`. |
| `opendbc/safety/tests/test_bluepilot_lateral.py` | New: hands the library's `safety/tests/` to upstream's test discovery, so upstream's `test.sh` and `mutation.py` run the BluePilot safety tests. |
## Every frame: inputs
A host fills these and the settings below for a car whose `CarParamsSP.lateralInputsRequired` is set: every Ford, BluePilot lateral on or off (`init_ford_safety_param_sp`).
`CarControlSP.lateralInputs` (`host_types.LateralInputs`):
| fields | from |
|---|---|
| `pathYawRate`, `pathX`, `pathY` | `modelV2.orientationRate.z`, `modelV2.position.x`, `.y` (33 points) |
| `laneLineLeftX/Y`, `laneLineRightX/Y` | `modelV2.laneLines[1]`, `[2]` |
| `laneLineProbs`, `laneLineStds` | `modelV2.laneLineProbs`, `.laneLineStds` |
| `laneChangeState`, `laneChangeDirection` | `modelV2.meta` |
| `steerRatio`, `stiffnessFactor`, `roll`, `angleOffsetDeg` | the learned vehicle parameters (`vehicleParameters`, paramsd) |
| `lateralDelay` | `lateralDelay.lateralDelay` |
| `valid` | true only when both the model and the vehicle parameters have been seen and every field above is filled |
Each path array has `host_types.MODEL_PATH_POINTS` (33) entries at the times in `host_types.MODEL_T_IDXS` (openpilot's `ModelConstants.T_IDXS`): the core interpolates over that grid. On a frame that isn't valid, or whose arrays aren't the full shape or contain a non-finite value, the library keeps the previous inputs.
## Every frame: settings
Every key in `opendbc.bluepilot_lateral.core.values_ext.BP_LATERAL_PARAMS` (the per-frame settings in `params/manifest.py`; hosts import the list from there), every frame, as (key, value) with the value as bytes (sunnypilot: `CarControlSP.params` entries): bools `"1"`/`"0"`, numbers as text. A missing, empty or unparsable value gives the manifest default. A host publishes its own registry default for a key nobody has set, so a host can carry its own defaults (BP7 uses 3.0 for `LC_PID_gain_UI_curv`). `python -m <pkg>.bluepilot_lateral.params.manifest` prints the keys as `params_keys.h` lines (IQ.Pilot drops `BACKUP`, which its params don't have).
## At startup: the safety bits
`values_ext.ford_safety_param(CP, params_dict)` reads the startup settings (`disable_BP_lat_UI`, `FordPrefSteerAngleCurvature`) and returns the bits. The host sends them to the panda in its second safety param (sunnypilot: the adapter ORs them into `CP_SP.safetyParam`). StarPilot has no second param: its adapter shifts them into bits 9-14 of its Ford `safetyParam` (`hosts/starpilot/safety_param.py`, clear of the bits StarPilot's Ford safety reads), and its `ford_init` hands `(param >> 9) & 0x3F` to `ford_bp_init`:
| bit | |
|---|---|
| 5 `BP_LATERAL` | the panda runs the BluePilot steering checks; the car controller sends the 4-signal messages only when it's set |
| 0 `STEER_ANGLE_CURVATURE`, 1-4 geometry index | the pinion angle replaces the yaw rate as the curvature measurement, on platforms with a row in the pinion table |
The panda keeps what it was given at init: changing `disable_BP_lat_UI` while driving takes full effect at the next init.
## Reading status
`BluePilotLateral.status()` returns `host_types.LateralStatus`, this frame's values for a BluePilot UI, under the names BP7's `controllerStateBP` publisher reads off its car controller:
| field | |
|---|---|
| `lateralUncertainty` | from whichever strategy ran |
| `angleRateLimited` | angle mode: the path angle soft rate limit bit this frame |
| `curvatureRateLimited` | angle mode: the equivalent curvature would have been rate-limited |
| `curvatureDeviationLimited` | either mode: the current-curvature error clip constrained the command |
| `humanTurnLateralPaused` | angle mode: lateral sent inactive during a manual turn |
| `stallBlipActive` | angle mode: the brief mode-0 pulse after a post-override stall |
| `disable_BP_lat_UI` | BluePilot lateral off: the setting, or the panda bit not set at init |
| `primary_lateral_control` | 0 = curvature, 1 = angle |
The four angle-mode values read false outside angle mode. bp-sunnypilot doesn't read status; it has no BluePilot UI.
## What the library uses from the host's opendbc
Every host is an opendbc fork, so the library uses these directly:
- `<pkg>.car`: `structs`, `DT_CTRL`, `ACCELERATION_DUE_TO_GRAVITY`, `scale_rot_inertia_per_mass` and `scale_tire_stiffness_per_mass` (or, on an opendbc from before the per-mass vehicle model, `scale_rot_inertia` and `scale_tire_stiffness`, at unit mass), `common.pid.PIDController`, `vehicle_model.VehicleModel` (either signature), `lateral` (`AngleSteeringLimits`, `apply_std_steer_angle_limits`, `ISO_LATERAL_ACCEL`), `ford.fordcan.CanBus`, `ford.values` (`CarControllerParams`, `FordFlags`).
- `can/fordcan_ext.py` sets LateralMotionControl2's checksum itself: upstream's packer fills Ford checksums (and overwrites it with the same value), IQ.Pilot's doesn't.
- The safety headers use `modes/ford.h`'s Ford constants and upstream's safety helpers, through the bindings above. `safety/lateral.h` and `can/fordcan_ext.py` copy four upstream functions, pinned per host package by `tests/test_bluepilot_upstream_copies.py`, so a host where one changed fails that test (a host with no pins skips it).
- The safety tests use the host's test harness: `<pkg>.safety.tests.test_ford`, `common` and `libsafety.libsafety_py`. `tests/host.py` names the host's own structs, adapter and libsafety setters for the tests that touch them.
## The core's API, and the host adapters
The core takes only the library's types:
- `core.carcontroller_ext.BluePilotLateral(CP, safety_param, packer, CAN)`: `safety_param` is the startup bits (`ford_safety_param`).
- `update(inputs, params, frame)`: `inputs` is a `host_types.LateralInputs`, `params` a `params.param_store.ParamStore` built from the frame's (key, value) settings. Then `step_lateral`, `step_lka` and `status()` as above.
Nothing under `core/`, `can/`, `params/` or `safety/` imports a host (`tests/test_core_imports.py`). `hosts/sunnypilot/`:
- `lateral.py`: a `BluePilotLateral` subclass with sunnypilot's types, `(CP, CP_SP, packer, CAN)` and `update(CC_SP, frame)`. It passes `CP_SP.safetyParam`, `CC_SP.lateralInputs` and the `CC_SP.params` entries as (key, value) pairs.
- `safety_param.py`: `init_ford_safety_param_sp(CP, CP_SP, params_dict)` ORs `ford_safety_param` into `CP_SP.safetyParam`. Its own module, so car init imports only `values_ext`.
`hosts/iqpilot/`, the same for IQ.Pilot's types:
- `lateral.py`: `BluePilotLateral(CP, CP_IQ, packer, CAN)` and `update(CC_IQ, frame)`, passing `CP_IQ.iqSafetyFlags`, `CC_IQ.lateralInputs` and the `CC_IQ.params` entries.
- `safety_param.py`: `init_ford_safety_param_iq(CP, CP_IQ, params_dict)` ORs `ford_safety_param` into `CP_IQ.iqSafetyFlags` (the panda's `current_safety_param_iq`) and sets `CP_IQ.lateralInputsRequired`.
`hosts/starpilot/`, for StarPilot, which has neither a second safety param nor CarControl / CarParams extension structs:
- `lateral.py`: `BluePilotLateral(CP, packer, CAN)`, reading the startup bits back out of the Ford `safetyParam`, and `update(frame_inputs, frame)`. `FrameInputs` carries `lateralInputs` and the `params` entries; StarPilot's openpilot side fills one each frame and hands it to the Ford CarController, in place of a CarControl extension.
- `safety_param.py`: `init_ford_safety_param_starpilot(CP, params_dict)` ORs `ford_safety_param << 9` into `CP.safetyConfigs[-1].safetyParam`; `bp_safety_param(CP)` reads them back; `lateral_inputs_required(CP)` says whether to fill `FrameInputs`. StarPilot's Transit (`FordFlags.LKA_STEERING`, steering through Lane_Assist_Data1 alone) gets neither.
Another host writes its own adapter against the same API.
## Running the tests
- Python tests: `python -m unittest discover -s <pkg>/bluepilot_lateral/tests -t .`, from the directory that holds `<pkg>`.
- Safety tests: the host's `<pkg>/safety/tests/test.sh` runs them, through a loader (ford-op/opendbc's `test_bluepilot_lateral.py`) or by naming `../../bluepilot_lateral/safety/tests` (IQ.Pilot: its cross-mode TX sweep reads `TX_MSGS` off every `Test*` class in its directory, so a loader there breaks it). Coverage of the BluePilot headers and `modes/ford.h`: `safety/tests/bluepilot_coverage.sh`, which runs the library's tests itself where the host has no loader; mutation: `safety/tests/bluepilot_mutation.py` (needs the host's `mutation.py`, which IQ.Pilot doesn't have).
- On a clean sunnypilot/opendbc checkout: `tools/test_on_host.sh <checkout>`, from a ford-op/opendbc checkout. It copies the library as committed and applies the hook patch to a temporary clone, then runs both.
- On IQPilot: `hosts/iqpilot/host.sh tree <dir>` builds iqdbc from IQ.Lvbs's repo at the pinned commit with `hosts/iqpilot/hooks.patch` (IQPilot's hooks, kept here until IQPilot carries them) and the library, vendored; `host.sh test <dir>` runs the library tests, IQPilot's safety suite with the BluePilot ones (minus `known_failures.txt`, IQPilot's own) and coverage; `host.sh make <dir>` writes the hook patch back after editing the hooks in `<dir>/host`. CI's `iqpilot` job runs tree and test. Every night `iqpilot pin check` tries IQ.Lvbs's latest `beta`: green moves the pin in a PR it merges itself (dropping `hooks.patch` once IQPilot carries the hooks), red keeps one issue open saying which step failed.
@@ -1,6 +1,4 @@
Copyright (c) 2020, Comma.ai, Inc.
Copyright (c) 2026, firestar5683 and StarPilot contributors
Copyright (c) 2024-2026, BluePilot contributors
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:
@@ -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 <support@sunnypilot.ai> for permission requests.
---
Haibin Wen, SUNNYPILOT LLC
@@ -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
Can't render this file because it contains an unexpected character in line 14 and column 85.
@@ -1,14 +1,81 @@
# BluePilot lateral
# BluePilot Ford angle control
BluePilot's Ford lateral control as a library an opendbc fork mounts at `opendbc/bluepilot_lateral/`: both modes (curvature and angle), the CAN messages that carry them, the panda safety that checks them, and a settings manifest.
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.
**This is a modified Ford safety model.** The panda safety allows signals and ranges that upstream's Ford safety blocks. A fork chooses whether to ship it.
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.
**Status:** `v0.2.0`. It runs on bp-sunnypilot, a sunnypilot fork, through ford-op/opendbc (sunnypilot's opendbc plus the hooks).
`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.
- [FORKS.md](FORKS.md): how a fork takes BluePilot lateral and works with BluePilot: carrying the library (a submodule or a stamped copy), the stamp tools, and adding a fork.
- [HOSTS.md](HOSTS.md): what a host provides, the hook patch, and how to run the tests.
- [can/LANE_ASSIST_DATA1.md](can/LANE_ASSIST_DATA1.md): the Lane_Assist_Data1 bits angle mode uses.
- [CREDITS.md](CREDITS.md) and [LICENSE](LICENSE) (MIT).
## Admission
History before 2026-09-15 lives in [BluePilotDev/bluepilot](https://github.com/BluePilotDev/bluepilot).
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.
@@ -1 +0,0 @@
v0.2.1 2b9dc6cc784faac47a1885d0bda0561f7b76f74d
@@ -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]
@@ -1,60 +0,0 @@
# Lane_Assist_Data1: BluePilot's angle-mode side channel
In angle mode the curvature signal in `LateralMotionControl2` is held at 0 and path angle does the
steering, so the panda has no commanded curvature to check against the car's measured curvature.
BluePilot sends that curvature, the *shadow curvature*, plus an "angle mode engaged" flag, in bits of
`Lane_Assist_Data1` (0x3CA) that carry no DBC signal. openpilot sends this message itself at 33 Hz,
and the panda reads it in the TX hook as it goes out. A separate message was tried first: the panda
never receives its own TX, and an RX check for it blocked controls car-wide (2026-07-09).
Packed by `create_lka_msg` in `fordcan_ext.py`; read by `ford_bp_lka_tx` in `../safety/ford.h`. The
byte positions, mask and scale are named once on each side (`BP_LKA_*` in `fordcan_ext.py`,
`FORD_BP_LKA_*` in `../safety/ford_declarations.h`), and `../tests/test_lane_assist_data1.py` checks
that they agree with each other and with the DBC.
## Layout
Bit numbers are within the byte, 7 = most significant. Stock signals are from `ford_lincoln_base_pt.dbc`.
| byte | bits | stock Ford signal | BluePilot |
|---|---|---|---|
| 0 | 7-5 | `LkaActvStats_D2_Req` | |
| 0 | 4-2 | `LdwActvStats_D_Req` | |
| 0 | 1-0 | `LdwActvIntns_D_Req` | |
| 1-2 | 12 bits | `LaCurvature_No_Calc` | |
| 2-3 | 12 bits | `LaRefAng_No_Req` | |
| 4 | 7 | `LaRampType_B_Req` | |
| 4 | 6-5 | `LkaDrvOvrrd_D_Rq` | |
| 4 | 4-1 | none | free |
| 4 | 0 | none | **angle mode engaged** |
| 5-6 | all | none | **shadow curvature** |
| 7 | all | none | free |
## Fields
- **Angle mode engaged** (byte 4 bit 0): 1 while angle mode is the selected lateral mode and
BluePilot lateral is on.
- **Shadow curvature** (bytes 5-6): int16, big-endian, 1e-6 1/m per unit, clamped to
-32768..32767 (about ±0.0328 1/m). It is the curvature angle mode's path angle was derived from,
after the same error clip curvature mode applies; while the driver is pressing, inactive, or
during a human-turn or stall-blip pulse, it is the car's measured curvature instead. It is sent
negated, in Ford's sign convention, like the curvature and path angle in `LateralMotionControl2`.
## What the panda does
- It latches both fields from every `Lane_Assist_Data1` frame that goes through its TX hook,
including one it blocks for another reason.
- **Angle mode engaged widens the path-angle range.** While the flag is set, the lateral command's
path angle may use the DBC's full range (-0.5 to 0.5235 rad); otherwise it is held to ±0.25 rad
(`ford_lmc_checks`). The flag alone does it: curvature 0 without the flag keeps the tight range.
- **The shadow curvature check.** For a lateral command (`LateralMotionControl` on CAN or
`LateralMotionControl2` on CAN FD) with curvature 0, steering enabled and the flag set, the
panda scales the shadow curvature by 0.05 to curvature CAN units (2e-5 1/m, truncated toward
zero) and, above 10 m/s, blocks the frame if it is outside the measured curvature ± the curvature
error band + 1 (`ford_shadow_curvature_error_check`). It has no rate limit: path angle has its own.
- `ford_bp_init` clears the flag.
## Not here yet
A protocol-version byte and a shared bit allocation for other forks (StarPilot) are Phase 3 (the StarPilot host issue, #16):
they change bytes on the wire.
@@ -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)
@@ -1,128 +0,0 @@
"""
BluePilot Ford CAN message builder extensions (lateral only).
Extended versions of the stock fordcan.py lateral builders:
- Dynamic ramp_type and precision_type for the 4-signal lateral commands
- Lane_Assist_Data1 carries the angle-mode side channel read by bluepilot_lateral/safety/ford.h
Trimmed for the lateral proof-of-concept: the longitudinal, HUD and ICBM builders from
BluePilot's fordcan_ext.py are out of scope here.
"""
from ...car.ford.fordcan import CanBus
# BluePilot: the Lane_Assist_Data1 side channel, see LANE_ASSIST_DATA1.md. ford_declarations.h has the
# same values (tests/test_lane_assist_data1.py).
BP_LKA_ANGLE_MODE_BYTE = 4
BP_LKA_ANGLE_MODE_MASK = 0x1
BP_LKA_SHADOW_MSB_BYTE = 5 # shadow curvature: int16, big-endian, bytes 5-6
BP_LKA_SHADOW_LSB_BYTE = 6
BP_LKA_SHADOW_CURVATURE_SCALE = 1e-6 # 1/meter per raw unit
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 (Ford sign) in bits with no DBC signal: the
layout and what the panda does with them are in LANE_ASSIST_DATA1.md.
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[BP_LKA_ANGLE_MODE_BYTE] |= BP_LKA_ANGLE_MODE_MASK if angle_mode_engaged else 0
dat[BP_LKA_SHADOW_MSB_BYTE] = (shadow_curvature_raw >> 8) & 0xFF
dat[BP_LKA_SHADOW_LSB_BYTE] = 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]
}
# Computed here, not left to the packer: upstream's packer fills Ford checksums itself (and overwrites
# this with the same value), but a host's packer may not (IQ.Pilot's doesn't), and the PSCM drops a
# frame whose checksum is wrong.
dat = packer.make_can_msg("LateralMotionControl2", CAN.main, values)[1]
values["LatCtlPath_No_Cs"] = lat_ctl2_checksum(mode, counter, dat)
return packer.make_can_msg("LateralMotionControl2", CAN.main, values)
def lat_ctl2_checksum(mode: int, counter: int, dat: bytes) -> int:
"""LatCtlPath_No_Cs of a packed LateralMotionControl2: upstream's ford_checksum over the message's
checksum fields (mode, counter, curvature, curvature rate, path angle, path offset)."""
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)
@@ -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)
@@ -1,234 +0,0 @@
"""
BluePilot Ford lateral: the one object the Ford CarController calls.
Holds the two strategies, LateralCurvExt and LateralAngleExt, with the inputs and state they
share, and does the strategy dispatch and message assembly. Lives above both strategy modules
(rather than inside either) so it can call into both without the circular import that would
result from one depending on the other.
The CarController owns apply_curvature_last, which the stock and BluePilot paths share: it is
passed into step_lateral and the result returned, so switching BluePilot lateral off mid-drive
continues from the last command, as before.
"""
import math
from types import SimpleNamespace
try:
from ...car import scale_rot_inertia_per_mass, scale_tire_stiffness_per_mass
except ImportError:
# a host on opendbc from before the per-mass vehicle model (IQ.Pilot): its mass-scaled helpers at unit
# mass are the per-mass values
from ...car import scale_rot_inertia, scale_tire_stiffness
def scale_rot_inertia_per_mass(wheelbase):
return scale_rot_inertia(1.0, wheelbase)
def scale_tire_stiffness_per_mass(wheelbase, center_to_front, tire_stiffness_factor):
return scale_tire_stiffness(1.0, wheelbase, center_to_front, tire_stiffness_factor)
from ...car.ford.values import CarControllerParams, FordFlags
from ...car.vehicle_model import VehicleModel
from ..can import fordcan_ext
from .lateral_angle_ext import LateralAngleExt
from .lateral_curv_ext import LateralCurvExt, PrimaryLateralControl
from ..params.manifest import value
from ..params.param_store import ParamStore
from .values_ext import FORD_PINION_WHEELBASE, FordSafetyFlagsSP
from .human_turn import HumanTurnDetector
from ..host_types import LateralInputs, LateralStatus
from .lateral_inputs import ModelView, VehicleParamsView, lateral_inputs_complete
def pinion_vehicle_model(CP):
"""Vehicle model for the pinion-angle curvature measurement: CarSpecs, except where BluePilot's
pinion geometry uses another wheelbase (FORD_PINION_WHEELBASE, the same value as the C table),
keeping the platform's weight split and tire model."""
wheelbase = FORD_PINION_WHEELBASE.get(CP.carFingerprint)
if wheelbase is None:
return VehicleModel(CP)
center_to_front = wheelbase * CP.centerToFront / CP.wheelbase
front, rear = scale_tire_stiffness_per_mass(wheelbase, center_to_front, CP.tireStiffnessFactor)
inertia = scale_rot_inertia_per_mass(wheelbase)
# Both VehicleModel signatures: upstream's per-mass fields, and the mass-scaled ones an older host's
# model reads, at unit mass (mass cancels out of the model, so the two are the same model).
return VehicleModel(SimpleNamespace(
rotationalInertiaPerMass=inertia, wheelbase=wheelbase,
centerToFront=center_to_front, steerRatio=CP.steerRatio,
tireStiffnessFrontPerMass=front, tireStiffnessRearPerMass=rear,
mass=1.0, rotationalInertia=inertia, tireStiffnessFront=front, tireStiffnessRear=rear, steerRatioRear=0.))
class InputTracker:
"""The model / vehicle-parameter inputs both strategies read, and the car's measured curvature.
Owned by BluePilotLateral and updated once per frame from the host's LateralInputs, before either
strategy runs."""
def __init__(self, CP, safety_param: int):
# Model / vehicle-parameter inputs arrive per frame from the host (see update)
self.VM = pinion_vehicle_model(CP) # used only for the pinion-angle curvature measurement
self.model = None
self.lp = None
self.lateral_delay = 0.0
# BluePilot: steering-angle curvature measurement (bad-yaw-sensor workaround).
# Mirrors the STEER_ANGLE_CURVATURE flag the safety firmware reads from
# current_safety_param_sp -- both layers must always agree, so this is init-time
# state from the startup safety bits (values_ext.ford_safety_param), never a live settings read:
# a live flip against stale firmware would fight the panda.
self.bp_pinion_curvature_enabled = bool(safety_param & FordSafetyFlagsSP.STEER_ANGLE_CURVATURE)
def get_current_curvature(self, CS):
"""Measured curvature of the car right now (OP sign convention).
The single measurement source for every BluePilot lateral consumer: the deviation
clip, the stall detector, and the shadow curvature published to ford.h's angle-mode
deviation check. The default source is the RCM yaw rate -- the same family stock
ford.h derives its angle_meas from. The shadow value judged against that check must
always come from the same measurement as the check's own reference, so route all
reads through here.
With the steering-angle curvature measurement enabled (FordPrefSteerAngleCurvature
toggle -> FordSafetyFlagsSP.STEER_ANGLE_CURVATURE), the pinion angle via the vehicle
model is used instead: some vehicles (e.g. a 2021 Explorer with a faulty RCM)
broadcast implausible VehYaw_W_Actl (sign-inverted vs IMU and steering geometry)
while its CAN quality flag still reads OK. The pinion angle (SteeringPinion_Data,
PSCM) is an equivalent measurement, independently validated against the comma IMU
(corr +0.99), and the panda safety angle_meas switches to the same source (see
bluepilot_lateral/safety/ford.h) -- the layers always agree. angleOffsetDeg/roll come from
liveParameters (paramsd, IMU-derived, not the car yaw sensor).
"""
if self.bp_pinion_curvature_enabled:
angle_offset_deg = self.lp.angleOffsetDeg if self.lp is not None else 0.0
roll = self.lp.roll if self.lp is not None else 0.0
return -self.VM.calc_curvature(math.radians(CS.out.steeringAngleDeg - angle_offset_deg),
CS.out.vEgoRaw, roll)
return -CS.out.yawRate / max(CS.out.vEgoRaw, 0.1)
def update(self, li: LateralInputs):
"""Take this frame's model / vehicle-parameter inputs from the host and update the vehicle model.
A frame is used only if it has the full modelV2 shape this code indexes into (33 path points,
both inner lane lines, 3+ probs/stds); anything else is ignored and the previous inputs are
kept, exactly as a stale SubMaster message was. That also makes fuzzed or partial inputs
safe: the producer's valid flag is necessary but not trusted on its own."""
if li.valid and lateral_inputs_complete(li):
self.model = ModelView(li)
self.lp = VehicleParamsView(li)
self.lateral_delay = li.lateralDelay
if self.lp is not None:
x = max(self.lp.stiffnessFactor, 0.1)
sr = max(self.lp.steerRatio, 0.1)
self.VM.update_params(x, sr)
class SharedLateralState:
"""The values both strategies read and write, so either mode sees what the other left, as when
the strategies were mixins on one object. bp_curvature_deviation_limited is the BluePilot UI's
deviation flag, from whichever mode ran."""
def __init__(self):
self.path_angle_last = 0.0
self.precision_type = 1 # 1=Precise, 0=Comfortable
self.bp_curvature_deviation_limited = False
self.human_turn_detector = HumanTurnDetector()
class BluePilotLateral:
def __init__(self, CP, safety_param: int, packer, CAN):
"""safety_param: the startup safety bits the panda was given (values_ext.ford_safety_param)."""
self.CP = CP
self.frame = 0
self.inputs = InputTracker(CP, safety_param)
self.shared = SharedLateralState()
self.curv = LateralCurvExt(self.inputs, self.shared)
self.angle = LateralAngleExt(CP, self.inputs, self.shared)
self.packer = packer
self.CAN = CAN
self.disable_BP_lat_UI = False
self.lateral_uncertainty = 0.0 # from whichever strategy ran last, for status()
# the panda only accepts 4-signal messages when this bit was set at init
self.bp_lateral_allowed = bool(safety_param & FordSafetyFlagsSP.BP_LATERAL)
def update(self, inputs: LateralInputs, params: ParamStore, frame):
"""Every frame: take this frame's model / vehicle-parameter inputs and settings, both from the host
(HOSTS.md). Returns whether BluePilot lateral is active."""
self.frame = frame
self.inputs.update(inputs)
self.curv.update_lateral_params(params)
self.angle.update_angle_params(params)
# One flag for every BP consumer (LatCtl dispatch, LKA angle-mode bits, mode reporting): the UI
# toggle, and the panda bit that was set at init. No 4-signal traffic to a stock-configured panda.
self.disable_BP_lat_UI = value(params, "disable_BP_lat_UI") or not self.bp_lateral_allowed
return not self.disable_BP_lat_UI
def step_lateral(self, CC, CS, actuators, apply_curvature_last):
"""At STEER_STEP: the steer message(s). Returns (can_sends, apply_curvature): the CarController
keeps it and passes it back next time as apply_curvature_last."""
# BluePilot: select the BP lateral strategy by primary control variable.
# angle -> LateralAngleExt: kappa -> path_angle (c1), apply_curvature held at 0.
# curvature -> LateralCurvExt: full 4-signal curvature-primary (default).
# Both return a LateralResult packed identically below.
# Do not run the stock curvature limits here or overwrite apply_curvature_last before the
# strategy runs. Panda rate-checks desired_curvature vs the last TX on the bus; that must match
# the prior frame's lat.apply_curvature only (not an intermediate stock-limited value).
angle_mode = self.curv.primary_lateral_control == PrimaryLateralControl.angle
if angle_mode:
lat = self.angle.update_angle_strategy(CC, CS, actuators)
else:
lat = self.curv.update(CC, CS, actuators, apply_curvature_last, self.CP)
apply_curvature = float(lat.apply_curvature)
self.lateral_uncertainty = float(lat.lateralUncertainty)
# BluePilot: angle-mode human-turn override -- send lateral inactive (mode 0) while the
# driver manually turns, so the PSCM releases cleanly instead of stalling 2-3 s on
# re-engage (observed on Mach-E). Panda-clean: every ford.h check has a legitimate
# !steer_control_enabled branch for the zeroed frames; on release, path_angle ramps back
# from 0 through the soft ROC. Curvature mode keeps its own reset_steering path (zeroed
# signals with mode still active) in LateralCurvExt.
# The stall blip (lateral_angle_ext.py) rides the same mode-0 path: a short pulse that
# resets the PSCM's post-override attenuation when the deviation clip deadlocks hands-free.
lat_active = CC.latActive and not (angle_mode and (self.angle.angle_human_turn_active or self.angle.angle_stall_blip_active))
can_sends = []
if self.CP.flags & FordFlags.CANFD:
mode = 1 if lat_active else 0
counter = (self.frame // CarControllerParams.STEER_STEP) % 0x10
can_sends.append(fordcan_ext.create_lat_ctl2_msg(
self.packer, self.CAN, mode, lat.ramp_type, lat.precision_type,
-lat.path_offset, -lat.path_angle, -lat.apply_curvature, -lat.curvature_rate, counter
))
else:
can_sends.append(fordcan_ext.create_lat_ctl_msg(
self.packer, self.CAN, lat_active, lat.ramp_type, lat.precision_type,
-lat.path_offset, -lat.path_angle, -lat.apply_curvature, -lat.curvature_rate
))
return can_sends, apply_curvature
def status(self) -> LateralStatus:
"""This frame's values for a BluePilot UI (HOSTS.md), as BP7 sets them on its car controller."""
angle_mode = self.curv.primary_lateral_control == PrimaryLateralControl.angle
return LateralStatus(
lateralUncertainty=self.lateral_uncertainty,
angleRateLimited=bool(angle_mode and self.angle.bp_angle_rate_limited),
curvatureRateLimited=bool(angle_mode and self.angle.bp_curvature_rate_limited),
curvatureDeviationLimited=bool(self.shared.bp_curvature_deviation_limited),
humanTurnLateralPaused=bool(angle_mode and self.angle.angle_human_turn_active),
stallBlipActive=bool(angle_mode and self.angle.angle_stall_blip_active),
disable_BP_lat_UI=bool(self.disable_BP_lat_UI),
primary_lateral_control=int(self.curv.primary_lateral_control),
)
def step_lka(self, CC, hud_control):
"""At LKA_STEP: the Lane_Assist_Data1 message."""
# BluePilot: tell bluepilot_lateral/safety/ford.h whether angle mode is engaged, packed into
# Lane_Assist_Data1's unused bits. shadow_curvature is negated to match the
# path_angle/apply_curvature wire convention that ford.h's angle_meas is calibrated against.
# Only called while BluePilot lateral is active (update returned True this frame), so the mode
# alone decides.
angle_mode_engaged = self.curv.primary_lateral_control == PrimaryLateralControl.angle
shadow_curvature = -self.angle.bp_kappa_cmd if angle_mode_engaged else 0.0
return fordcan_ext.create_lka_msg(
self.packer, self.CAN, CC.latActive, hud_control, angle_mode_engaged, shadow_curvature
)
@@ -1,448 +0,0 @@
"""
BluePilot Ford lateral curvature extension.
Implements Ford's 4-signal lateral control (curvature, curvature_rate, path_offset, path_angle)
using predicted curvature from modelV2, PID-based lane centering, and laneline-aware path offset.
Held by BluePilotLateral (carcontroller_ext.py) as LateralCurvExt.
Ford uses four signals to control steering:
- curvature: primary steering command (also used in upstream, limited to 0.02 m^-1)
- curvature_rate: always 0, like upstream and stock Ford
- path_offset: lateral offset for lane centering (blends model + laneline data)
- path_angle: heading angle correction via PID controller
A detailed explanation of Ford's control protocol:
https://www.f150gen14.com/forum/threads/introducing-bluepilot-a-ford-specific-fork-for-comma3x-openpilot.24241/#post-457706
"""
from collections import namedtuple, deque
from enum import IntEnum
import numpy as np
from numpy import clip, interp
from ...car.common.pid import PIDController
from ...car import ACCELERATION_DUE_TO_GRAVITY
from ...car.lateral import ISO_LATERAL_ACCEL, apply_std_steer_angle_limits
from ...car.ford.values import CarControllerParams, FordFlags
from .values_ext import BP_ANGLE_LIMITS, CURVATURE_MAX, LANE_CHANGE_FACTOR_BP, LANE_CHANGE_FACTOR_LOW
from .values_ext import MODEL_T_IDXS
from ..params.manifest import default, value
# the settings curvature mode reads (params/manifest.py), each kept as an attribute of the same name
CURV_SETTINGS = ("enable_human_turn_detection_curv", "lane_change_factor_high_curv", "pc_blend_ratio_high_C_UI_curv",
"pc_blend_ratio_low_C_UI_curv", "enable_lane_positioning_curv", "custom_path_offset_curv",
"enable_lane_full_mode_curv", "custom_profile_curv", "LC_PID_gain_UI_curv")
class PrimaryLateralControl(IntEnum):
curvature = 0
angle = 1
# CAN FD lateral-accel cap (match opendbc/car/ford/carcontroller.py apply_ford_curvature_limits)
AVERAGE_ROAD_ROLL = 0.06 # ~3.4 degrees, 6% superelevation
MAX_LATERAL_ACCEL = ISO_LATERAL_ACCEL - (ACCELERATION_DUE_TO_GRAVITY * AVERAGE_ROAD_ROLL)
# Result namedtuple returned by LateralCurvExt.update()
LateralResult = namedtuple('LateralResult', [
'apply_curvature',
'curvature_rate',
'path_offset',
'path_angle',
'ramp_type',
'precision_type',
'lateralUncertainty',
])
def apply_ford_curvature_limits_ext(apply_curvature, apply_curvature_last, current_curvature,
v_ego_raw, steering_angle, lat_active, CP):
"""Extended version of apply_ford_curvature_limits that returns
(apply_curvature, max_curvature, curvature_deviation_limited).
The max_curvature value is used by _calculate_lateral_uncertainty() for the steering
torque bar visualization. Stock version returns only apply_curvature.
curvature_deviation_limited (BluePilot): True when the current_curvature +- CURVATURE_ERROR
clip below actually constrained the commanded curvature this frame -- i.e. the desired
maneuver was limited by deviation from measured current curvature, not by rate-of-change
(apply_std_steer_angle_limits below is a separate limiter with its own telemetry).
"""
max_curvature = 1 # large initial value
curvature_deviation_limited = False
# No blending at low speed due to lack of torque wind-up and inaccurate current curvature
if v_ego_raw > 9:
apply_curvature_pre_error_clip = apply_curvature
apply_curvature = np.clip(apply_curvature, current_curvature - CarControllerParams.CURVATURE_ERROR,
current_curvature + CarControllerParams.CURVATURE_ERROR)
curvature_deviation_limited = bool(abs(apply_curvature - apply_curvature_pre_error_clip) > 1e-9)
max_curvature = abs(current_curvature) + CarControllerParams.CURVATURE_ERROR
# Curvature rate limit after driver torque limit (same inputs/order as apply_ford_curvature_limits)
apply_curvature_before_std = apply_curvature
apply_curvature = apply_std_steer_angle_limits(apply_curvature_before_std, apply_curvature_last, v_ego_raw,
steering_angle, lat_active, BP_ANGLE_LIMITS)
# Max one-step envelope for UI: steer_up must use pre-limit curvature (see apply_std_steer_angle_limits)
steer_up = (apply_curvature_last * apply_curvature_before_std >= 0.0
and abs(apply_curvature_before_std) > abs(apply_curvature_last))
rate_limits = BP_ANGLE_LIMITS.ANGLE_RATE_LIMIT_UP if steer_up else BP_ANGLE_LIMITS.ANGLE_RATE_LIMIT_DOWN
std_steer_angle_rate_limit = np.interp(v_ego_raw, rate_limits[0], rate_limits[1])
std_steer_angle_limit = abs(apply_curvature_last) + abs(std_steer_angle_rate_limit)
max_curvature = np.minimum(max_curvature, std_steer_angle_limit)
# Ford CAN FD lateral acceleration limit (more torque available than CAN)
if CP.flags & FordFlags.CANFD:
curvature_accel_limit = MAX_LATERAL_ACCEL / (max(v_ego_raw, 1) ** 2)
apply_curvature = float(np.clip(apply_curvature, -curvature_accel_limit, curvature_accel_limit))
max_curvature = np.minimum(max_curvature, abs(curvature_accel_limit))
return apply_curvature, max_curvature, curvature_deviation_limited
class LateralCurvExt:
"""
BluePilot lateral control extension for Ford vehicles.
Held by BluePilotLateral (carcontroller_ext.py), which calls
update() during the lateral control loop (20Hz) to get the full
4-signal steering command instead of the upstream curvature-only approach.
"""
def __init__(self, inputs, shared):
# BluePilotLateral's LateralInputs (read) and SharedLateralState (read and written), common to both strategies
self.inputs = inputs
self.shared = shared
# Primary lateral control variable: consumed by BluePilotLateral's lateral dispatch.
self.primary_lateral_control = PrimaryLateralControl.curvature
# Settings (updated from the host's params each frame), at their defaults until then
for key in CURV_SETTINGS:
setattr(self, key, default(key))
# Precision/ramp control (precision_type is in the shared state)
self.lateralUncertainty = 0.0
# Predicted curvature blending
self.curvature_lookup_time = 0.2 # seconds into the future for curvature extraction
self.pc_blend_ratio = 0.5
self.pc_blend_ratio_bp = [0.0, 0.001] # curvature breakpoints (1/m)
self.pc_blend_ratio_low = 0.40
self.pc_blend_ratio_high = 0.40
self.pc_blend_ratio_low_C = 0.40 # from UI when custom_profile_curv == 1
self.pc_blend_ratio_high_C = 0.40 # from UI when custom_profile_curv == 1
# Lane change smoothing
self.lane_change = False
self.lane_change_last = False
# Post lane change transition
self.post_lane_change_timer = 0
self.post_lane_change_active = False
self.pre_lane_change_values = {'path_angle': 0.0, 'path_offset': 0.0}
self.max_path_angle_change = 0.00125
self.max_path_offset_change = 0.00125
# Human turn detection (the detector is in the shared state, used by both modes)
self.human_turn = False
self.post_reset_ramp_active = False
self.reset_steering_last = False
# Path offset
self.path_offset_lookup_time = 0.2 # seconds
self.min_laneline_confidence_bp = [0.6, 0.8]
# PID-based path angle for lane centering
self.path_angle_filter_samples = 3
self.path_angle_deque = deque(maxlen=self.path_angle_filter_samples)
self.LC_PID_k_p = 0.25
self.LC_PID_k_i = 0.05
self.LC_PID_controller = PIDController(k_p=self.LC_PID_k_p, k_i=self.LC_PID_k_i, rate=20)
self.LC_PID_speed_bp = [0.0, 9.0, 15.0] # m/s
self.LC_PID_speed_v = [0.0, 0.0, 1.0]
self.LC_path_angle_ROC_bp = [5, 15, 25] # m/s
self.LC_path_angle_ROC_v = [0.003, 0.0015, 0.002] # match panda limits
self.LC_path_angle_reset_counter = 0
self.LC_path_angle_reset_duration = 1.5 # seconds
# DBC signal max limits
self.path_angle_max = 0.5
self.path_offset_max = 2.0
self.curvature_max = CURVATURE_MAX # 0.02
# Previous frame values
self.path_offset_last = 0.0
def update_lateral_params(self, params):
"""Read lateral-related Params from the UI. Called each frame."""
for key in CURV_SETTINGS:
setattr(self, key, value(params, key))
try:
self.primary_lateral_control = PrimaryLateralControl(value(params, "FordPrefLateralControl"))
except ValueError: # a mode other than 0 or 1: curvature mode, the default (#66)
self.primary_lateral_control = PrimaryLateralControl.curvature
def update(self, CC, CS, actuators, apply_curvature_last, CP):
"""
Compute lateral steering signals for the current frame.
Called at 20Hz from BluePilotLateral.step_lateral() when inside the STEER_STEP block.
Args:
CC: CarControl with latActive, hudControl
CS: CarState with vEgoRaw, yawRate, steeringPressed, steeringAngleDeg
actuators: CC.actuators with desired curvature from planner
apply_curvature_last: previous frame's applied curvature
CP: CarParams with flags for CANFD etc.
Returns:
LateralResult namedtuple with all signals needed for CAN message construction.
"""
apply_curvature = 0.0
path_offset = 0.0
path_angle = 0.0
reset_steering = 0
ramp_type = 2
lateralUncertainty = 0.0
curvature_deviation_limited = False
if CC.latActive:
self.shared.precision_type = 1
steeringPressed = CS.out.steeringPressed
steeringAngleDeg_PV = CS.out.steeringAngleDeg
# Select tuning profile
if self.custom_profile_curv == 1:
self.pc_blend_ratio_low_C = self.pc_blend_ratio_low_C_UI_curv
self.pc_blend_ratio_high_C = self.pc_blend_ratio_high_C_UI_curv
self.pc_blend_ratio_v = [self.pc_blend_ratio_low_C, self.pc_blend_ratio_high_C]
# Current and desired curvature
current_curvature = self.inputs.get_current_curvature(CS)
desired_curvature = actuators.curvature
# Extract predicted curvature from modelV2
if self.inputs.model is not None and len(self.inputs.model.orientationRate.z) >= 17:
curvatures = np.array(self.inputs.model.orientationRate.z) / max(0.01, CS.out.vEgoRaw)
predicted_curvature = interp(self.curvature_lookup_time, MODEL_T_IDXS, curvatures)
else:
predicted_curvature = 0.0
# Blend predicted and desired curvature
self.pc_blend_ratio = interp(abs(desired_curvature), self.pc_blend_ratio_bp, self.pc_blend_ratio_v)
requested_curvature = (predicted_curvature * self.pc_blend_ratio) + (desired_curvature * (1 - self.pc_blend_ratio))
# Lane change detection
if self.inputs.model is not None:
self.lane_change = self.inputs.model.meta.laneChangeState in (1, 2, 3)
else:
self.lane_change = False
# Lane change curvature smoothing
lane_change_factor = interp(CS.out.vEgoRaw, LANE_CHANGE_FACTOR_BP,
[LANE_CHANGE_FACTOR_LOW, self.lane_change_factor_high_curv])
if self.lane_change and self.inputs.model is not None:
if self.inputs.model.meta.laneChangeDirection == 1 and requested_curvature < 0:
requested_curvature *= lane_change_factor
self.shared.precision_type = 0
elif self.inputs.model.meta.laneChangeDirection == 2 and requested_curvature > 0:
requested_curvature *= lane_change_factor
self.shared.precision_type = 0
# Human turn: sustained hands-on + large angle (not just a nudge) — see HumanTurnDetector
self.human_turn = self.shared.human_turn_detector.update(
self.enable_human_turn_detection_curv, steeringPressed, steeringAngleDeg_PV)
# Steering reset logic
if self.human_turn or (CS.out.vEgoRaw < 0.1):
reset_steering = 1
if reset_steering == 1:
requested_curvature = 0.0
# Apply curvature limits (extended version returning max_curvature)
apply_curvature, max_curvature, curvature_deviation_limited = apply_ford_curvature_limits_ext(
requested_curvature, apply_curvature_last, current_curvature,
CS.out.vEgoRaw, 0, CC.latActive, CP)
# Lateral uncertainty for torque bar visualization
lateralUncertainty = self._calculate_lateral_uncertainty(requested_curvature, apply_curvature, max_curvature)
# Human turn / standstill reset: after apply_ford_curvature_limits_ext (for torque-bar max_curvature),
# force κ=0 and (below) path_angle=0 on the bus. ford.h accepts that frame (curvature 0 skips the
# curvature checks), but checks the frames after it as usual: a ramp back that exceeds the rate
# limit or sits outside the curvature error band is blocked.
if reset_steering == 1:
apply_curvature = 0.0
self.post_reset_ramp_active = False
else:
# Detect transition from reset to normal
if self.reset_steering_last and not reset_steering:
self.post_reset_ramp_active = True
apply_curvature_last = 0.0 # Reset to ensure clean ramp from 0
# Post-reset ramp: gradually ramp from 0 to avoid safety limit trips
if self.post_reset_ramp_active:
apply_curvature = apply_std_steer_angle_limits(
requested_curvature, apply_curvature_last,
CS.out.vEgoRaw, 0, CC.latActive, BP_ANGLE_LIMITS)
curvature_error = abs(requested_curvature - apply_curvature)
curvature_threshold = max(abs(requested_curvature) * 0.1, 0.001)
if curvature_error < curvature_threshold:
self.post_reset_ramp_active = False
self.reset_steering_last = (reset_steering == 1)
# Path offset: blend model position with laneline data
if self.inputs.model is not None:
path_offset_position = interp(self.path_offset_lookup_time, MODEL_T_IDXS, self.inputs.model.position.y)
path_offset_lanelines = (self.inputs.model.laneLines[1].y[0] + self.inputs.model.laneLines[2].y[0]) / 2
# Laneline width tolerance (prevents jumps when lanes merge/diverge)
laneline_width = self.inputs.model.laneLines[2].y[0] + (-self.inputs.model.laneLines[1].y[0])
laneline_width_tolerance = interp(laneline_width, [3.75, 4.25], [0.81, 0.59])
# Laneline confidence
laneline_confidence = min(self.inputs.model.laneLineProbs[1], self.inputs.model.laneLineProbs[2], laneline_width_tolerance)
if not self.enable_lane_full_mode_curv:
laneline_confidence = 0.0
laneline_path_offset_scale = interp(laneline_confidence, self.min_laneline_confidence_bp, [0.0, 1.0])
path_offset = ((path_offset_position * (1 - laneline_path_offset_scale)) +
(path_offset_lanelines * laneline_path_offset_scale)) + self.custom_path_offset_curv
# No path offset during lane changes
if self.lane_change:
path_offset = 0
# PID-based path angle for lane centering
path_offset_error = path_offset * (self.LC_PID_gain_UI_curv / 100)
LC_PID_speed_factor = interp(CS.out.vEgoRaw, self.LC_PID_speed_bp, self.LC_PID_speed_v)
path_offset_error_adj = path_offset_error * LC_PID_speed_factor
if not self.enable_lane_positioning_curv:
path_offset_error_adj = 0.0
path_angle_low_c = self.LC_PID_controller.update(path_offset_error_adj)
if not self.enable_lane_positioning_curv:
path_angle_low_c = 0.0
if reset_steering == 1:
path_angle_low_c = 0.0
# Rate limit path angle for comfort
path_angle_roc = interp(abs(CS.out.vEgoRaw), self.LC_path_angle_ROC_bp, self.LC_path_angle_ROC_v)
path_angle_low_c = clip(path_angle_low_c, self.shared.path_angle_last - path_angle_roc, self.shared.path_angle_last + path_angle_roc)
# Reset PID if driver applies consistent steering pressure
if steeringPressed:
self.LC_path_angle_reset_counter += 1
else:
self.LC_path_angle_reset_counter = 0
if self.LC_path_angle_reset_counter > self.LC_path_angle_reset_duration * 20:
self.LC_PID_controller.reset()
path_angle = path_angle_low_c # path_angle_high_c not used currently
# Post lane change transition smoothing
path_angle, path_offset = self._handle_post_lane_change_transition(path_angle, path_offset)
# Final reset handling
if reset_steering == 1:
path_angle = 0.0
# Clip all signals to DBC limits
# float() is required: numpy's clip returns np.float64, and capnp rejects that type when
# apply_curvature reaches actuators.curvature via apply_curvature_last in carcontroller.py.
# The cast is exact (both are IEEE 754 doubles), so no output value changes.
apply_curvature = float(clip(apply_curvature, -self.curvature_max, self.curvature_max))
path_offset = float(clip(path_offset, -self.path_offset_max, self.path_offset_max))
path_angle = float(clip(path_angle, -self.path_angle_max, self.path_angle_max))
# Zero path_offset before CAN send (path_offset and path_angle can conflict, causing discomfort)
path_offset = 0.0
# Ramp type selection
if reset_steering == 1:
ramp_type = 3 # Immediate
self.path_angle_deque.clear()
self.LC_PID_controller.reset()
else:
ramp_type = 2 # Fast
else:
# Lateral control off — zero everything
apply_curvature = 0.0
path_offset = 0.0
path_angle = 0.0
self.path_angle_deque.clear()
self.LC_PID_controller.reset()
ramp_type = 0
lateralUncertainty = 0.0
# Update state for next frame
self.lateralUncertainty = lateralUncertainty
self.path_offset_last = path_offset
self.shared.path_angle_last = path_angle
# BluePilot: did the current_curvature +- CURVATURE_ERROR clip constrain the commanded
# curvature this frame (deviation from measured, not rate-of-change)? The BluePilot UI's deviation flag.
self.shared.bp_curvature_deviation_limited = curvature_deviation_limited
return LateralResult(
apply_curvature=apply_curvature,
curvature_rate=0.0, # always 0, like stock Ford
path_offset=path_offset,
path_angle=path_angle,
ramp_type=ramp_type,
precision_type=self.shared.precision_type,
lateralUncertainty=lateralUncertainty,
)
def _handle_post_lane_change_transition(self, path_angle, path_offset):
"""Smooth transition of control variables after lane change completes.
Rate-limits path_angle and path_offset back to target values
over 160 frames (~8 seconds at 20Hz).
"""
# Detect lane change completion (True → False transition)
if self.lane_change_last and not self.lane_change:
self.post_lane_change_active = True
self.post_lane_change_timer = 0
self.pre_lane_change_values = {'path_angle': 0.0, 'path_offset': 0.0}
self.lane_change_last = self.lane_change
if self.post_lane_change_active:
self.post_lane_change_timer += 1
new_path_angle = clip(path_angle,
self.pre_lane_change_values['path_angle'] - self.max_path_angle_change,
self.pre_lane_change_values['path_angle'] + self.max_path_angle_change)
new_path_offset = clip(path_offset,
self.pre_lane_change_values['path_offset'] - self.max_path_offset_change,
self.pre_lane_change_values['path_offset'] + self.max_path_offset_change)
self.pre_lane_change_values = {
'path_angle': new_path_angle,
'path_offset': new_path_offset,
}
if self.post_lane_change_timer >= 160:
self.post_lane_change_active = False
return (new_path_angle, new_path_offset)
return (path_angle, path_offset)
def _calculate_lateral_uncertainty(self, requested_curvature, apply_curvature, max_curvature):
"""Compute ratio of requested to max achievable curvature for the torque bar UI."""
max_curvature = np.clip(max_curvature, apply_curvature, self.curvature_max)
return float(requested_curvature / max_curvature)
@@ -1,54 +0,0 @@
"""
BluePilot: views over the host's LateralInputs (host_types.py) in the modelV2 / vehicleParameters shape
the lateral code reads, and the check that a frame is complete. The host fills LateralInputs once per frame.
"""
import math
from itertools import chain
from types import SimpleNamespace
from ..host_types import MODEL_PATH_POINTS
def lateral_inputs_complete(li) -> bool:
"""True when every array the lateral indexes into has the shape modelV2 always provides, and
every value is finite. A NaN from the model doesn't raise in the lateral math; it reaches the
CAN encoders, which do, so the whole frame is dropped here and the previous inputs are kept."""
return (len(li.pathYawRate) == MODEL_PATH_POINTS and len(li.pathX) == MODEL_PATH_POINTS and len(li.pathY) == MODEL_PATH_POINTS
and len(li.laneLineLeftX) == MODEL_PATH_POINTS and len(li.laneLineLeftY) == MODEL_PATH_POINTS
and len(li.laneLineRightX) == MODEL_PATH_POINTS and len(li.laneLineRightY) == MODEL_PATH_POINTS
and len(li.laneLineProbs) >= 3 and len(li.laneLineStds) >= 3
and all(map(math.isfinite, chain(li.pathYawRate, li.pathX, li.pathY, li.laneLineLeftX, li.laneLineLeftY,
li.laneLineRightX, li.laneLineRightY, li.laneLineProbs, li.laneLineStds,
(li.steerRatio, li.stiffnessFactor, li.roll, li.angleOffsetDeg, li.lateralDelay)))))
class _LaneLine:
def __init__(self, x, y):
self.x = x
self.y = y
class ModelView:
"""The subset of modelV2 the lateral code uses, with the same attribute paths."""
def __init__(self, li):
self.orientationRate = SimpleNamespace(z=li.pathYawRate)
self.position = SimpleNamespace(x=li.pathX, y=li.pathY)
# indices match modelV2.laneLines: 1 = left, 2 = right; 0 and 3 are not used
self.laneLines = [_LaneLine([], []),
_LaneLine(li.laneLineLeftX, li.laneLineLeftY),
_LaneLine(li.laneLineRightX, li.laneLineRightY),
_LaneLine([], [])]
self.laneLineProbs = li.laneLineProbs
self.laneLineStds = li.laneLineStds
self.meta = SimpleNamespace(laneChangeState=li.laneChangeState, laneChangeDirection=li.laneChangeDirection)
class VehicleParamsView:
"""The subset of vehicleParameters the lateral code uses."""
def __init__(self, li):
self.steerRatio = li.steerRatio
self.stiffnessFactor = li.stiffnessFactor
self.roll = li.roll
self.angleOffsetDeg = li.angleOffsetDeg
@@ -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
@@ -1,156 +0,0 @@
from ...car import structs
from ...car.lateral import AngleSteeringLimits
from .. import host_types
from ..params.manifest import PER_FRAME_KEYS, startup_value
class FordSafetyFlagsSP:
"""BluePilot's Ford safety flags: the bits of the second safety param a host sends the panda
(current_safety_param_sp, USB control 0xdf), not the main safetyConfigs[].safetyParam (HOSTS.md).
ford_bp_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: the param must stay a plain int
through the host's serialization.
"""
# Bit layout of the SP safety param (mirrored in ford_bp_init, bluepilot_lateral/safety/ford.h; pinned by
# tests/test_safety_param_bits.py):
# bit 0 STEER_ANGLE_CURVATURE (pinion-sourced curvature measurement)
# bits 1-4 pinion geometry index (FORD_PINION_GEOMETRY_SHIFT / FORD_PINION_GEOMETRY_INDEX)
# bit 5 BP_LATERAL: the panda runs the 4-signal checks (ford_lmc_checks) instead of
# upstream's stock curvature-only checks. Clear = upstream safety, verbatim.
STEER_ANGLE_CURVATURE = 1
BP_LATERAL = 1 << 5
# Geometry-table index for the steering-angle curvature measurement, packed into
# the startup safety bits 1-4 when STEER_ANGLE_CURVATURE is set. Must match the
# ford_pinion_geometry table in bluepilot_lateral/safety/ford.h row for row.
# 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.
# Platforms with no row are in FORD_NO_PINION_PLATFORMS. Indices stay aligned with the C table.
# BluePilot: the per-platform tables key on the platform name (CP.carFingerprint), not the CAR enum,
# so a row for a platform some host lacks never breaks import there; it just never matches.
# FORD_HOST_ONLY_PLATFORMS lists the names with rows here that upstream opendbc's CAR doesn't have; any
# name a host's CAR lacks must be on it (tests/test_platform_tables.py).
FORD_HOST_ONLY_PLATFORMS: frozenset[str] = frozenset({
"FORD_EDGE_MK2", # StarPilot
"FORD_MONDEO_MK5", # BP7, StarPilot
"FORD_TRANSIT_MK5", # StarPilot
})
# No pinion geometry row, so no STEER_ANGLE_CURVATURE (the setting no-ops and the yaw source is kept):
FORD_NO_PINION_PLATFORMS: frozenset[str] = frozenset({
# ALT_STEER_ANGLE: reads a RELATIVE pinion angle (SteeringPinion_Data_Alt + learned offset) and lacks the
# absolute measurement this needs
"FORD_EDGE_MK2",
# LKA steering through Lane_Assist_Data1 alone: no BluePilot lateral at all
"FORD_TRANSIT_MK5",
})
FORD_PINION_GEOMETRY_SHIFT = 1
FORD_PINION_GEOMETRY_INDEX = {
"FORD_BRONCO_SPORT_MK1": 1,
"FORD_ESCAPE_MK4": 2,
"FORD_ESCAPE_MK4_5": 3,
"FORD_EXPEDITION_MK4": 4,
"FORD_EXPLORER_MK6": 5,
"FORD_FOCUS_MK4": 6,
"FORD_F_150_LIGHTNING_MK1": 7,
"FORD_F_150_MK14": 8,
"FORD_MAVERICK_MK1": 9,
"FORD_MONDEO_MK5": 10,
"FORD_MUSTANG_MACH_E_MK1": 11,
"FORD_RANGER_MK2": 12,
}
def ford_safety_param(CP: structs.CarParams, params_dict: dict[str, str]) -> int:
"""The startup safety bits for this car, from the startup settings (HOSTS.md). A host ORs them into the
second safety param it sends the panda (current_safety_param_sp, USB 0xdf) at car init."""
# Steering-angle curvature measurement (bad-yaw-sensor workaround): the STEER_ANGLE_CURVATURE flag +
# the platform geometry-table index; the control side mirrors the same flag
# (carcontroller_ext.InputTracker.get_current_curvature). Platforms without a geometry row silently
# keep stock yaw behavior -- the toggle no-ops rather than half-configuring.
bits = 0
if CP.brand == 'ford':
# BluePilot 4-signal lateral: tell the panda to run the BP checks. Read once here, at init;
# the carcontroller sends 4-signal messages only when this bit is set. Changing the setting
# while driving does not change the panda: stock messages are then judged by the BP
# envelope (which is not identical to the stock one), so the setting takes full effect at
# the next init. Same property as openpilot longitudinal.
bp_lateral = not startup_value(params_dict, "disable_BP_lat_UI")
if bp_lateral:
bits |= FordSafetyFlagsSP.BP_LATERAL
# The pinion-sourced measurement is a BP lateral feature: its wider error band and the
# Python side's yaw-vs-pinion handling only line up on the BP path, so it is off whenever
# BP lateral is off (ford_bp_init enforces the same on the panda).
steer_angle_curvature = bp_lateral and startup_value(params_dict, "FordPrefSteerAngleCurvature")
if steer_angle_curvature:
geometry_index = FORD_PINION_GEOMETRY_INDEX.get(CP.carFingerprint)
if geometry_index is not None:
bits |= FordSafetyFlagsSP.STEER_ANGLE_CURVATURE | (geometry_index << FORD_PINION_GEOMETRY_SHIFT)
return bits
# Pinion geometry wheelbase (m) where BluePilot deliberately differs from CarSpecs. Used by both the
# C table (ford_pinion_geometry in bluepilot_lateral/safety/ford.h) and the Python pinion path
# (carcontroller_ext.pinion_vehicle_model), so the two layers convert pinion angle the same way.
# FORD_F_150_MK14: the trucks with lane centering come in 3.68 and 3.99 m wheelbases and nothing on
# the car tells them apart; the average keeps either within about 4% (#21).
FORD_PINION_WHEELBASE = {
"FORD_F_150_MK14": 3.84,
}
# 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 ford_bp_curvature_cmd_checks. Safety firmware is looser than both: its
# up table is the control's down table, and its down table is 1% looser again — see
# bluepilot_lateral/safety/ford.h FORD_LIMITS.
_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,
)
# The model's prediction times, part of the host contract (host_types.py); the strategies read it from here.
MODEL_T_IDXS = host_types.MODEL_T_IDXS
# The per-frame settings a host publishes every frame (HOSTS.md; hosts import this name from here). The
# settings, their defaults and how they are read are in params/manifest.py.
BP_LATERAL_PARAMS = PER_FRAME_KEYS
# Lane change smoothing, both modes: speed breakpoints (m/s) and the low-speed factor
LANE_CHANGE_FACTOR_BP = (4.4, 40.23)
LANE_CHANGE_FACTOR_LOW = 0.95
# Angle mode's per-platform high-speed gain defaults (low curvature, high curvature); any other
# platform gets ANGLE_GAIN_CAN. Read by lateral_angle_ext.update_angle_params.
# CAN vehicles (Escape MK4, Bronco Sport, Explorer, Maverick, Edge)
ANGLE_GAIN_CAN = (1.00, 1.15)
# CAN-FD body-on-frame trucks (F-150, Lightning, Expedition, Ranger)
ANGLE_GAIN_CANFD_BOF = (0.95, 0.95)
# CAN-FD unibody SUVs (Mustang Mach-E, Escape MK4.5)
ANGLE_GAIN_CANFD_SUV = (1.00, 1.05)
ANGLE_GAIN_CANFD_BOF_CARS = frozenset({
"FORD_F_150_MK14",
"FORD_F_150_LIGHTNING_MK1",
"FORD_EXPEDITION_MK4",
"FORD_RANGER_MK2",
})
ANGLE_GAIN_CANFD_SUV_CARS = frozenset({
"FORD_MUSTANG_MACH_E_MK1",
"FORD_ESCAPE_MK4_5",
})
@@ -1,48 +0,0 @@
"""BluePilot: the types a host hands the library and reads back from it (HOSTS.md).
Standard library only: opendbc/car/structs.py imports LateralInputs for CarControlSP, so an import of
anything in opendbc here would be an import cycle."""
from dataclasses import dataclass, field
# The model's prediction grid: every path array in LateralInputs has MODEL_PATH_POINTS entries at these
# times, openpilot's ModelConstants.T_IDXS (t = 10 * (i / 32)^2). The core interpolates over it.
MODEL_PATH_POINTS = 33
MODEL_T_IDXS = [10.0 * (i / 32) ** 2 for i in range(MODEL_PATH_POINTS)]
@dataclass
class LateralInputs:
"""Per-frame model / vehicle inputs for the Ford 4-signal lateral control. The host fills them from
modelV2 / vehicleParameters / lateralDelay, so opendbc never subscribes to messaging."""
valid: bool = False # producer saw model + vehicle params and filled every field below
pathYawRate: list[float] = field(default_factory=list) # modelV2.orientationRate.z, 33 points over T_IDXS
pathX: list[float] = field(default_factory=list) # modelV2.position.x
pathY: list[float] = field(default_factory=list) # modelV2.position.y
laneLineLeftX: list[float] = field(default_factory=list) # modelV2.laneLines[1]
laneLineLeftY: list[float] = field(default_factory=list)
laneLineRightX: list[float] = field(default_factory=list) # modelV2.laneLines[2]
laneLineRightY: list[float] = field(default_factory=list)
laneLineProbs: list[float] = field(default_factory=list) # 4 entries
laneLineStds: list[float] = field(default_factory=list)
laneChangeState: int = 0 # modelV2.meta.laneChangeState
laneChangeDirection: int = 0 # modelV2.meta.laneChangeDirection
steerRatio: float = 0.0 # vehicleParameters
stiffnessFactor: float = 0.0
roll: float = 0.0
angleOffsetDeg: float = 0.0
lateralDelay: float = 0.0 # lateralDelay.lateralDelay
@dataclass
class LateralStatus:
"""This frame's values for a BluePilot UI, from BluePilotLateral.status(). The names are the ones
BP7's controllerStateBP publisher reads off its car controller; the four angle-mode values read
False outside angle mode, as BP7 sets them."""
lateralUncertainty: float = 0.0 # from whichever strategy ran last
angleRateLimited: bool = False # angle mode: the path_angle soft-ROC clip bit this frame
curvatureRateLimited: bool = False # angle mode: the equivalent curvature would have been rate-limited
curvatureDeviationLimited: bool = False # either mode: the current-curvature error clip constrained the command
humanTurnLateralPaused: bool = False # angle mode: lateral sent inactive during a manual turn
stallBlipActive: bool = False # angle mode: the brief mode-0 pulse after a post-override stall
disable_BP_lat_UI: bool = False # BluePilot lateral off: the UI toggle, or the panda bit not set at init
primary_lateral_control: int = 0 # 0 = curvature, 1 = angle
@@ -1,270 +0,0 @@
diff --git a/iqdbc/car/ford/carcontroller.py b/iqdbc/car/ford/carcontroller.py
index e00869f..cf8e4ba 100644
--- a/iqdbc/car/ford/carcontroller.py
+++ b/iqdbc/car/ford/carcontroller.py
@@ -5,6 +5,7 @@ from iqdbc.car import ACCELERATION_DUE_TO_GRAVITY, Bus, DT_CTRL, apply_hysteresi
from iqdbc.car.ford import fordcan
from iqdbc.car.ford.values import CarControllerParams, FordFlags, CAR
from iqdbc.car.interfaces import CarControllerBase, V_CRUISE_MAX
+from iqdbc.bluepilot_lateral.hosts.iqpilot.lateral import BluePilotLateral # BluePilot
LongCtrlState = structs.CarControl.Actuators.LongControlState
VisualAlert = structs.CarControl.HUDControl.VisualAlert
@@ -38,6 +39,7 @@ class CarController(CarControllerBase):
super().__init__(dbc_names, CP, CP_IQ)
self.packer = CANPacker(dbc_names[Bus.pt])
self.CAN = fordcan.CanBus(CP)
+ self.bp = BluePilotLateral(CP, CP_IQ, self.packer, self.CAN) # BluePilot
self.apply_curvature_last = 0
self.anti_overshoot_curvature_last = 0
@@ -52,6 +54,7 @@ class CarController(CarControllerBase):
def update(self, CC, CC_IQ, CS, now_nanos):
can_sends = []
+ bp_active = self.bp.update(CC_IQ, self.frame) # BluePilot
actuators = CC.actuators
hud_control = CC.hudControl
@@ -74,7 +77,10 @@ class CarController(CarControllerBase):
### lateral control ###
# send steer msg at 20Hz
- if (self.frame % CarControllerParams.STEER_STEP) == 0:
+ if bp_active and (self.frame % CarControllerParams.STEER_STEP) == 0: # BluePilot
+ lat_sends, self.apply_curvature_last = self.bp.step_lateral(CC, CS, actuators, self.apply_curvature_last)
+ can_sends.extend(lat_sends)
+ elif (self.frame % CarControllerParams.STEER_STEP) == 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):
@@ -108,7 +114,9 @@ class CarController(CarControllerBase):
can_sends.append(fordcan.create_lat_ctl_msg(self.packer, self.CAN, CC.latActive, 0., 0., -self.apply_curvature_last, 0.))
# send lka msg at 33Hz
- if (self.frame % CarControllerParams.LKA_STEP) == 0:
+ if bp_active and (self.frame % CarControllerParams.LKA_STEP) == 0: # BluePilot
+ can_sends.append(self.bp.step_lka(CC, hud_control))
+ elif (self.frame % CarControllerParams.LKA_STEP) == 0:
can_sends.append(fordcan.create_lka_msg(self.packer, self.CAN))
### longitudinal control ###
diff --git a/iqdbc/car/structs.py b/iqdbc/car/structs.py
index 520c7fc..5f95bbd 100644
--- a/iqdbc/car/structs.py
+++ b/iqdbc/car/structs.py
@@ -4,6 +4,7 @@ from typing import dataclass_transform, get_origin
import os
import capnp
from iqdbc.car.common.basedir import BASEDIR
+from iqdbc.bluepilot_lateral.host_types import LateralInputs # BluePilot: the per-frame inputs controlsd fills
try:
from iqpilot.cereal import car
except ImportError:
@@ -54,6 +55,7 @@ class IQCarParams:
longitudinalStoppingSpeedOverride: float = auto_field()
stoppingDecelRateOverride: float = auto_field()
longActiveWithGasOverride: bool = auto_field()
+ lateralInputsRequired: bool = auto_field() # BluePilot: controlsd fills IQCarControl.lateralInputs and params
iqLateralNet: 'IQCarParams.LateralNet' = field(default_factory=lambda: IQCarParams.LateralNet())
@@ -120,6 +122,7 @@ class IQCarControl:
useRadarAccel: bool = auto_field()
radarSetSpeedKph: float = auto_field()
radarGapBars: int = auto_field()
+ lateralInputs: 'LateralInputs' = field(default_factory=lambda: LateralInputs()) # BluePilot
@auto_dataclass
class Param:
diff --git a/iqdbc/lvbs/car/interfaces.py b/iqdbc/lvbs/car/interfaces.py
index 5ca575a..aafd822 100644
--- a/iqdbc/lvbs/car/interfaces.py
+++ b/iqdbc/lvbs/car/interfaces.py
@@ -8,6 +8,7 @@ from collections.abc import Callable
from iqdbc.car import structs
from iqdbc.car.can_definitions import CanRecvCallable, CanSendCallable
+from iqdbc.bluepilot_lateral.hosts.iqpilot.safety_param import init_ford_safety_param_iq # BluePilot
from iqdbc.car.subaru.values import SubaruFlags
from iqdbc.car.tesla.values import LEGACY_CARS
from iqdbc.lvbs.car.subaru.iq_values import SubaruFlagsIQ, SubaruSafetyFlagsIQ
@@ -80,6 +81,7 @@ def apply_iq_car_config(CI, CP: structs.CarParams, CP_IQ: structs.IQCarParams,
_apply_tesla_options(CP, CP_IQ, params_dict)
_apply_creep_assist(CP, CP_IQ, params_dict)
_apply_toyota_options(CP, CP_IQ, params_dict)
+ init_ford_safety_param_iq(CP, CP_IQ, params_dict) # BluePilot
def _apply_long_tuning(CI, CP: structs.CarParams, CP_IQ: structs.IQCarParams,
diff --git a/iqdbc/safety/modes/ford.h b/iqdbc/safety/modes/ford.h
index 26ec0af..5e5c0c4 100644
--- a/iqdbc/safety/modes/ford.h
+++ b/iqdbc/safety/modes/ford.h
@@ -9,6 +9,7 @@
#define FORD_BrakeSysFeatures 0x415U // RX from ABS, for vehicle speed
#define FORD_EngVehicleSpThrottle2 0x202U // RX from PCM, for second vehicle speed
#define FORD_Yaw_Data_FD1 0x91U // RX from RCM, for yaw rate
+#define FORD_SteeringPinion_Data 0x7EU // RX from PSCM, optional angle_meas source (BluePilot STEER_ANGLE_CURVATURE)
#define FORD_Steering_Data_FD1 0x083U // TX by OP, various driver switches and LKAS/CC buttons
#define FORD_ACCDATA 0x186U // TX by OP, ACC controls
#define FORD_ACCDATA_3 0x18AU // TX by OP, ACC/TJA user interface
@@ -29,6 +30,9 @@ static uint8_t ford_get_counter(const CANPacket_t *msg) {
} else if (msg->addr == FORD_Yaw_Data_FD1) {
// Signal: VehRollYaw_No_Cnt
cnt = msg->data[5];
+ } else if (msg->addr == FORD_SteeringPinion_Data) {
+ // Signal: StePinAn_No_Cnt (47|4@0+)
+ cnt = (msg->data[5] >> 4) & 0xFU;
} else {
}
return cnt;
@@ -74,6 +78,8 @@ static bool ford_get_quality_flag_valid(const CANPacket_t *msg) {
valid = ((msg->data[4] >> 5) & 0x3U) == 0x3U; // VehVActlEng_D_Qf
} else if (msg->addr == FORD_Yaw_Data_FD1) {
valid = ((msg->data[6] >> 4) & 0x3U) == 0x3U; // VehYawWActl_D_Qf
+ } else if (msg->addr == FORD_SteeringPinion_Data) {
+ valid = ((msg->data[5] >> 2) & 0x3U) == 0x3U; // StePinCompAnEst_D_Qf (3=OK)
} else {
}
return valid;
@@ -94,6 +100,16 @@ static const NativeCurvatureSteeringLimits FORD_STEERING_LIMITS = {
.curvature_error_min_speed = 10.0,
};
+// BluePilot: the Ford 4-signal lateral checks, pinion angle_meas source and angle-mode state, from the
+// bluepilot_lateral subtree. The bindings point the library at IQ's native-curvature names.
+#define BP_HOST_CURVATURE_LIMITS NativeCurvatureSteeringLimits
+#define BP_HOST_CURVATURE_STATE native_curvature_state
+#define BP_HOST_RT_CURVATURE_RATE_CHECK rt_native_curvature_rate_limit_check
+#define BP_HOST_LAT_ALLOWED() is_lat_active()
+#define BP_HOST_SPEED_MISMATCH_CHECK() ((void)0) // ford_rx_hook runs it on FORD_EngVehicleSpThrottle2
+// cppcheck-suppress misra-c2012-20.1; needs the Ford constants defined above
+#include "iqdbc/bluepilot_lateral/safety/ford.h"
+
static void ford_rx_hook(const CANPacket_t *msg) {
if (msg->bus == FORD_MAIN_BUS) {
// Update in motion state from standstill signal
@@ -117,7 +133,7 @@ static void ford_rx_hook(const CANPacket_t *msg) {
}
// Update vehicle yaw rate
- if (msg->addr == FORD_Yaw_Data_FD1) {
+ if ((msg->addr == FORD_Yaw_Data_FD1) && !ford_bp_pinion_curvature) { // BluePilot: pinion source replaces yaw
// Signal: VehYaw_W_Actl
// TODO: we should use the speed which results in the closest angle measurement to the desired angle
float ford_yaw_rate = (((msg->data[2] << 8U) | msg->data[3]) * 0.0002) - 6.5;
@@ -149,6 +165,8 @@ static void ford_rx_hook(const CANPacket_t *msg) {
aol_button_press = GET_BIT(msg, 40U) ? AOL_BUTTON_PRESSED : AOL_BUTTON_NOT_PRESSED;
}
}
+
+ ford_bp_rx_hook(msg); // BluePilot: pinion angle_meas source
}
static bool ford_tx_hook(const CANPacket_t *msg) {
@@ -223,6 +241,8 @@ static bool ford_tx_hook(const CANPacket_t *msg) {
if (action != 0U) {
tx = false;
}
+
+ ford_bp_lka_tx(msg); // BluePilot: angle-mode state from the frame's unused bits
}
// Safety check for LateralMotionControl action
@@ -234,12 +254,17 @@ 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
- violation |= steer_native_curvature_cmd_checks(desired_curvature, steer_control_enabled, FORD_STEERING_LIMITS);
+ bool violation = false;
+ if (ford_bp_lateral) { // BluePilot: 4-signal lateral
+ violation = ford_bp_lmc_tx(false, raw_curvature, raw_curvature_rate, raw_path_offset, raw_path_angle, steer_control_enabled);
+ } else {
+ // These signals are not yet tested with the current safety limits
+ 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
+ violation |= steer_native_curvature_cmd_checks(desired_curvature, steer_control_enabled, FORD_STEERING_LIMITS);
+ }
if (violation) {
tx = false;
@@ -255,12 +280,17 @@ 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_native_curvature_cmd_checks(desired_curvature, steer_control_enabled, FORD_STEERING_LIMITS);
+ bool violation = false;
+ if (ford_bp_lateral) { // BluePilot: 4-signal lateral
+ violation = ford_bp_lmc_tx(true, raw_curvature, raw_curvature_rate, raw_path_offset, raw_path_angle, steer_control_enabled);
+ } else {
+ // These signals are not yet tested with the current safety limits
+ 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_native_curvature_cmd_checks(desired_curvature, steer_control_enabled, FORD_STEERING_LIMITS);
+ }
if (violation) {
tx = false;
@@ -287,6 +317,20 @@ static safety_config ford_init(uint16_t param) {
{.msg = {{FORD_Steering_Data_FD1, 0, 8, 10U, .ignore_checksum = true, .ignore_counter = true, .ignore_quality_flag = true}, { 0 }, { 0 }}},
};
+ // BluePilot: ford_rx_checks plus the pinion message, enforced only while the pinion angle_meas source is
+ // on (ford_bp_init). Written out rather than shared through a macro: cppcheck's MISRA 5.8 check misreads one.
+ static RxCheck ford_rx_checks_pinion[] = {
+ {.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 }}},
+ {.msg = {{FORD_Steering_Data_FD1, 0, 8, 10U, .ignore_checksum = true, .ignore_counter = true, .ignore_quality_flag = true}, { 0 }, { 0 }}},
+ // StePinAn_No_Cs matches no Ford checksum pattern on real frames: integrity via counter (0-15) + quality flag + 100 Hz
+ {.msg = {{FORD_SteeringPinion_Data, 0, 8, 100U, .max_counter = 15U, .ignore_checksum = true}, { 0 }, { 0 }}},
+ };
+
#define FORD_COMMON_TX_MSGS \
{FORD_Steering_Data_FD1, 0, 8, .check_relay = false}, \
{FORD_Steering_Data_FD1, 2, 8, .check_relay = false}, \
@@ -331,6 +375,11 @@ static safety_config ford_init(uint16_t param) {
} else {
ret = BUILD_SAFETY_CFG(ford_rx_checks, FORD_LONG_TX_MSGS);
}
+
+ // BluePilot: IQ safety flags (BP lateral, pinion source); the pinion RX check applies only when it is consumed
+ if (ford_bp_init(current_safety_param_iq)) {
+ SET_RX_CHECKS(ford_rx_checks_pinion, ret);
+ }
return ret;
}
diff --git a/iqdbc/safety/tests/test.sh b/iqdbc/safety/tests/test.sh
index 1ff4ee8..9c8b425 100755
--- a/iqdbc/safety/tests/test.sh
+++ b/iqdbc/safety/tests/test.sh
@@ -10,8 +10,8 @@ source ../../../setup.sh
rm -f ./libsafety/*.gcda
scons -j$(nproc) -D
-# run safety tests and generate coverage data
-pytest -n8 --ignore-glob=misra/*
+# run safety tests and generate coverage data (and the BluePilot ones, from the bluepilot_lateral subtree)
+pytest -n8 --ignore-glob=misra/* . ../../bluepilot_lateral/safety/tests
if [ "$(uname)" = "Darwin" ]; then
GCOV_EXEC="/opt/homebrew/opt/llvm@18/bin/llvm-cov gcov"
@@ -1,92 +0,0 @@
#!/usr/bin/env bash
# BluePilot: IQPilot as a test host for this library (#18). Its opendbc, iqdbc, comes from IQ.Lvbs's own repo at the
# commit pinned below, with IQPilot's hooks (hooks.patch, the files they change outside the library) and this
# library at iqdbc/bluepilot_lateral/.
# host.sh tree <dir> [ref] <dir>/iq: the IQPilot folders iqdbc's code imports; <dir>/host: iqdbc on its own, a git
# repo with IQPilot as committed (first commit) and the hooks plus this library, placed by
# tools/vendor.sh (second). Writes <dir>/state: "not adopted" (the patch applied), "adopted"
# (IQPilot already carries it, or there's no patch), or "drifted: ..." (and fails): the hooks
# or IQPilot's copy of the library differ from what this repo has
# host.sh test <dir> build <dir>/host and run the library tests, IQPilot's safety suite with the BluePilot
# safety tests, and 100% line coverage of modes/ford.h and the library's safety headers
# host.sh make <dir> write hooks.patch from <dir>/host: every change outside the library since IQPilot's
# commit, committed or not. Change a hook: tree, edit <dir>/host, test, make.
set -euo pipefail
REPO=https://gitlvb.teallvbs.xyz/IQ.Lvbs/IQ.Pilot.git
PIN=cb6a1c1145b18e36bf5180ab13a4e7beda39c40a # beta, 2026-10-29
PROJECT=artifacts/package_sources/iqdbc # iqdbc's own project: setup.sh, pyproject.toml, uv.lock
IMPORTED="iqpilot/common iqpilot/cereal iqpilot/system iqpilot/selfdrive" # imported by iqdbc's code and tests
EXTRA_PACKAGES="pyserial setproctitle" # imported too, but only in IQPilot's top-level lock
HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
LIB="$(cd "$HERE/../.." && pwd)"
DIR="$(mkdir -p "$2" && cd "$2" && pwd)"
case "$1" in
tree)
REF=${3:-$PIN}
rm -rf "$DIR/iq" "$DIR/host"
GIT_LFS_SKIP_SMUDGE=1 git clone -q --filter=blob:none --no-checkout "$REPO" "$DIR/iq"
# shellcheck disable=SC2086 # a list of paths
git -C "$DIR/iq" sparse-checkout set $PROJECT $IMPORTED
GIT_LFS_SKIP_SMUDGE=1 git -C "$DIR/iq" checkout -q "$REF"
# iqdbc on its own: under IQPilot's root, uv takes it for a member of IQPilot's workspace
cp -R "$DIR/iq/$PROJECT" "$DIR/host"
cd "$DIR/host"
git init -q
git add -A
git -c user.name=ci -c user.email=ci@localhost commit -q -m "IQPilot $(git -C "$DIR/iq" rev-parse --short HEAD)"
state="adopted"
if [ -f "$HERE/hooks.patch" ]; then
if git apply --check "$HERE/hooks.patch" 2>/dev/null; then
git apply "$HERE/hooks.patch"
state="not adopted"
elif ! git apply --check --reverse "$HERE/hooks.patch" 2>/dev/null; then
state="drifted: hooks.patch neither applies nor is already in IQPilot (update it to what IQPilot carries: make)"
fi
fi
# IQPilot's own copy, once it carries one, has to be a release as vendored, before this library replaces it
if [ -f iqdbc/bluepilot_lateral/VERSION ] && ! "$LIB/tools/check_vendored.sh" iqdbc/bluepilot_lateral; then
state="drifted: IQPilot's copy of the library differs from the release in its VERSION"
fi
"$LIB/tools/vendor.sh" HEAD iqdbc/bluepilot_lateral
git add -A
git -c user.name=ci -c user.email=ci@localhost commit -q -m "hooks and library"
echo "$state" > "$DIR/state"
echo "IQPilot $(git -C "$DIR/iq" rev-parse --short HEAD), hooks: $state, library $(git -C "$LIB" rev-parse --short HEAD)"
[[ "$state" != drifted* ]]
;;
test)
cd "$DIR/host"
set +u
# shellcheck disable=SC1091 # IQPilot's: tools (clang-18 and mull on Linux, for the coverage build) and the venv
source setup.sh
set -u
export PYTHONPATH="$DIR/host:$DIR/iq" # setup.sh sets it to iqdbc alone; its code imports iqpilot too
# shellcheck disable=SC2086 # a list of packages
uv pip install -q $EXTRA_PACKAGES
scons -j"$(nproc 2>/dev/null || sysctl -n hw.ncpu)"
python -m unittest discover -s iqdbc/bluepilot_lateral/tests -t .
# IQPilot's safety suite as its test.sh runs it (pytest: unittest also collects its base classes), the BluePilot
# tests in the same run (its cross-mode TX sweep reads every Test* class it collects), minus IQPilot's own failures
deselect=()
# pytest names a test from its rootdir (iqdbc's project), not from the directory it runs in
while read -r t; do deselect+=("--deselect=iqdbc/safety/tests/$t"); done < <(grep -v -e '^#' -e '^$' "$HERE/known_failures.txt")
cd iqdbc/safety/tests
rm -f libsafety/*.gcda
pytest -q -n8 --ignore-glob='misra/*' "${deselect[@]}" . ../../bluepilot_lateral/safety/tests
if [ "$(uname)" = "Darwin" ]; then GCOV_EXEC="/opt/homebrew/opt/llvm@18/bin/llvm-cov gcov"; else GCOV_EXEC="llvm-cov-18 gcov"; fi
# two reports: modes/ford.h and the library's safety/ford.h share a file name (see bluepilot_coverage.sh)
gcovr -r .. --gcov-executable "$GCOV_EXEC" --fail-under-line=100 -f "$DIR/host/iqdbc/safety/modes/ford.h"
gcovr -r "$DIR/host" --gcov-executable "$GCOV_EXEC" -d --fail-under-line=100 -f "$DIR/host/iqdbc/bluepilot_lateral/safety/"
;;
make)
git -C "$DIR/host" diff HEAD~1 -- . ':(exclude)iqdbc/bluepilot_lateral' > "$HERE/hooks.patch"
echo "hooks.patch: $(grep -c '^diff --git' "$HERE/hooks.patch") files"
;;
*)
echo "usage: $0 tree|test|make <dir> [ref]" >&2
exit 2
;;
esac
@@ -1,4 +0,0 @@
# IQPilot's own failing tests at the pinned commit, skipped by host.sh test so they don't fail this library's CI.
# Each one fails on IQPilot without the hooks or the library too. Remove a line once IQPilot fixes it.
test_tesla_legacy.py::TestTeslaHW2ExternalPandaSafety::test_enable_control_allowed_with_manual_aol_button_state
test_tesla_legacy.py::TestTeslaHW3ExternalPandaSafety::test_enable_control_allowed_with_manual_aol_button_state
@@ -1,21 +0,0 @@
"""
BluePilot: the IQ.Pilot host adapter for the lateral (HOSTS.md). The Ford CarController builds this
with IQ.Pilot's types; it hands the core the library's types and nothing IQ-specific.
"""
from ...core import carcontroller_ext
from ...params.param_store import ParamStore
def params_from_cc_iq(CC_IQ) -> ParamStore:
"""The settings IQ.Pilot published this frame (IQCarControl.params entries) as (key, value) pairs."""
return ParamStore((p.key, p.value) for p in CC_IQ.params)
class BluePilotLateral(carcontroller_ext.BluePilotLateral):
def __init__(self, CP, CP_IQ, packer, CAN):
super().__init__(CP, CP_IQ.iqSafetyFlags, packer, CAN)
def update(self, CC_IQ, frame):
"""Every frame: the inputs and settings IQ.Pilot's controlsd put in IQCarControl. Returns whether
BluePilot lateral is active."""
return super().update(CC_IQ.lateralInputs, params_from_cc_iq(CC_IQ), frame)
@@ -1,14 +0,0 @@
"""
BluePilot: the startup safety bits onto IQ.Pilot's IQCarParams (HOSTS.md). Its own module, so car
init imports only values_ext, not the whole lateral.
"""
from ...core.values_ext import ford_safety_param
def init_ford_safety_param_iq(CP, CP_IQ, params_dict: dict[str, str]) -> None:
"""Called from IQ.Pilot's apply_iq_car_config at car init. CP_IQ.iqSafetyFlags reaches the panda as
current_safety_param_iq (USB 0xdf); lateralInputsRequired tells the host to fill
IQCarControl.lateralInputs and the per-frame settings, for every Ford (BluePilot lateral on or off)."""
CP_IQ.iqSafetyFlags |= ford_safety_param(CP, params_dict)
if CP.brand == 'ford':
CP_IQ.lateralInputsRequired = True
@@ -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)))
@@ -1,40 +0,0 @@
"""
BluePilot: the StarPilot host adapter for the lateral (HOSTS.md). StarPilot's Ford CarController builds this
from CarParams alone (the startup bits ride its Ford safetyParam, safety_param.py). StarPilot has no
CarControl extension: its openpilot side hands the CarController a FrameInputs each frame instead, carrying
what sunnypilot and IQ.Pilot carry in theirs.
"""
from dataclasses import dataclass, field
from ...core import carcontroller_ext
from ...host_types import LateralInputs
from ...params.param_store import ParamStore
from .safety_param import bp_safety_param
@dataclass
class FrameInputs:
"""This frame's model / vehicle-parameter inputs and settings, filled by StarPilot's openpilot side."""
@dataclass
class Param:
key: str = ""
value: bytes = b""
lateralInputs: LateralInputs = field(default_factory=LateralInputs)
params: list = field(default_factory=list)
def params_from_frame(frame_inputs: FrameInputs) -> ParamStore:
"""The settings StarPilot published this frame (FrameInputs.params entries) as (key, value) pairs."""
return ParamStore((p.key, p.value) for p in frame_inputs.params)
class BluePilotLateral(carcontroller_ext.BluePilotLateral):
def __init__(self, CP, packer, CAN):
super().__init__(CP, bp_safety_param(CP), packer, CAN)
def update(self, frame_inputs: FrameInputs, frame):
"""Every frame: the inputs and settings StarPilot's openpilot side put in frame_inputs. Returns whether
BluePilot lateral is active."""
return super().update(frame_inputs.lateralInputs, params_from_frame(frame_inputs), frame)
@@ -1,37 +0,0 @@
"""
BluePilot: the startup safety bits onto StarPilot's Ford safetyParam (HOSTS.md). StarPilot has no second
safety param, so the bits ride its one Ford param at bits 9-14, clear of the bits StarPilot's Ford safety
reads (0-3, and 8 for its AOL's manual transmission). Its own module, so car init imports only values_ext,
not the whole lateral.
"""
from ....car import structs
from ....car.ford.values import FordFlags
from ...core.values_ext import ford_safety_param
BP_SAFETY_PARAM_SHIFT = 9
BP_SAFETY_PARAM_MASK = 0x3F # ford_safety_param's six bits, before the shift
# StarPilot's Transit steers through Lane_Assist_Data1 alone: no BluePilot lateral
LKA_STEERING = getattr(FordFlags, "LKA_STEERING", 0)
def init_ford_safety_param_starpilot(CP: structs.CarParams, params_dict: dict[str, str]) -> None:
"""Called from StarPilot's Ford interface at car init, after its own safetyParam bits are set. The
shifted bits reach the panda with the Ford safety mode; StarPilot's ford_init passes them to ford_bp_init."""
if CP.brand != 'ford' or CP.flags & LKA_STEERING:
return
bits = ford_safety_param(CP, params_dict)
if bits:
CP.safetyConfigs[-1].safetyParam |= bits << BP_SAFETY_PARAM_SHIFT
def bp_safety_param(CP: structs.CarParams) -> int:
"""The startup bits as ford_safety_param returned them: what BluePilotLateral and ford_bp_init take."""
if not CP.safetyConfigs:
return 0
return (CP.safetyConfigs[-1].safetyParam >> BP_SAFETY_PARAM_SHIFT) & BP_SAFETY_PARAM_MASK
def lateral_inputs_required(CP: structs.CarParams) -> bool:
"""Whether StarPilot's openpilot side fills the per-frame inputs and settings: every Ford the lateral can
run on, BluePilot lateral on or off."""
return CP.brand == 'ford' and not CP.flags & LKA_STEERING
@@ -1,21 +0,0 @@
"""
BluePilot: the sunnypilot host adapter for the lateral (HOSTS.md). The Ford CarController builds this
with sunnypilot's types; it hands the core the library's types and nothing sunnypilot-specific.
"""
from ...core import carcontroller_ext
from ...params.param_store import ParamStore
def params_from_cc_sp(CC_SP) -> ParamStore:
"""The settings sunnypilot published this frame (CarControlSP.params entries) as (key, value) pairs."""
return ParamStore((p.key, p.value) for p in CC_SP.params)
class BluePilotLateral(carcontroller_ext.BluePilotLateral):
def __init__(self, CP, CP_SP, packer, CAN):
super().__init__(CP, CP_SP.safetyParam, packer, CAN)
def update(self, CC_SP, frame):
"""Every frame: the inputs and settings sunnypilot's controlsd put in CarControlSP. Returns whether
BluePilot lateral is active."""
return super().update(CC_SP.lateralInputs, params_from_cc_sp(CC_SP), frame)
@@ -1,15 +0,0 @@
"""
BluePilot: the startup safety bits onto sunnypilot's CarParamsSP (HOSTS.md). Its own module, so car
init imports only values_ext, not the whole lateral.
"""
from ....car import structs
from ...core.values_ext import ford_safety_param
def init_ford_safety_param_sp(CP: structs.CarParams, CP_SP: structs.CarParamsSP, params_dict: dict[str, str]) -> None:
"""Called from sunnypilot's setup_interfaces at car init. CP_SP.safetyParam reaches the panda as
current_safety_param_sp (USB 0xdf); lateralInputsRequired tells the host to fill
CarControlSP.lateralInputs and the per-frame settings, for every Ford (BluePilot lateral on or off)."""
CP_SP.safetyParam |= ford_safety_param(CP, params_dict)
if CP.brand == 'ford':
CP_SP.lateralInputsRequired = True
@@ -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")
@@ -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
@@ -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
@@ -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
}
}
}
@@ -1,137 +0,0 @@
"""
BluePilot: every setting the lateral library reads, in one place.
Each Setting says what the host stores (key, type, default: its params_keys.h line), what the user
sees (label, description, range: the BluePilot UI's text and limits), and how the library reads it
(at startup, every frame or both; clamped to its range or not). The library reads every setting
through `value` (per frame, from the CarControlSP.params ParamStore) or `startup_value` (get_car's
params dict), with one rule: a published, parseable value is used; missing, empty or unparsable
gives the default.
`python -m <pkg>.bluepilot_lateral.params.manifest` prints the lines for a host's params_keys.h (<pkg>: the host's opendbc package).
"""
from dataclasses import dataclass
from typing import Literal
STARTUP, PER_FRAME, BOTH = "startup", "per-frame", "both"
@dataclass(frozen=True)
class Setting:
key: str
type: type
default: bool | int | float
read: Literal["startup", "per-frame", "both"]
label: str
description: str
range: tuple[float, float] | None = None # the UI's limits
clamp: bool = False # the library clamps to range (the angle-mode factors only, as BluePilot does)
SETTINGS: tuple[Setting, ...] = (
Setting("disable_BP_lat_UI", bool, False, BOTH, "Disable BP Lateral Control",
"Disable BluePilot lateral control."),
Setting("enable_human_turn_detection_curv", bool, True, PER_FRAME, "Enable Human Turn Detection",
"Enable detection of human-initiated turns."),
Setting("enable_lane_positioning_curv", bool, False, PER_FRAME, "Enable Lane Positioning",
"Enable custom lane positioning controls."),
Setting("enable_lane_full_mode_curv", bool, False, PER_FRAME, "Enable Lanefull Mode",
"Enable lanefull mode for lane positioning."),
Setting("enable_lane_positioning_ang", bool, False, PER_FRAME, "Enable Lane Positioning",
"Nudge the vehicle toward true lane-line center (plus optional bias) while in angle-primary control."),
Setting("FordPrefLateralControl", int, 0, PER_FRAME, "Primary Control Variable",
"Curvature matches the existing strategy. Angle uses path_angle as the main actuator (in development).",
range=(0, 1)),
# an on/off toggle in the UI, stored as INT
Setting("custom_profile_curv", int, 0, PER_FRAME, "Use Custom Tuning Profile",
"Enable custom tuning profile settings.", range=(0, 1)),
Setting("lane_change_factor_high_curv", float, 0.85, PER_FRAME, "Lane Change Factor High",
"Scales steering during a lane change (curvature control). Values <1.0 reduce it.", range=(0.5, 1.0)),
Setting("pc_blend_ratio_high_C_UI_curv", float, 0.4, PER_FRAME, "Predicted Curvature Blend Ratio High",
"Adjust the high curvature blend ratio (0.0-1.0).", range=(0.0, 1.0)),
Setting("pc_blend_ratio_low_C_UI_curv", float, 0.4, PER_FRAME, "Predicted Curvature Blend Ratio Low",
"Adjust the low curvature blend ratio (0.0-1.0).", range=(0.0, 1.0)),
Setting("custom_path_offset_curv", float, 0.0, PER_FRAME, "In-Lane Offset",
"Adjust the in-lane offset (-0.5 to 0.5).", range=(-0.5, 0.5)),
Setting("LC_PID_gain_UI_curv", float, 1.0, PER_FRAME, "Centering PID gain",
"PID gain for the curvature-mode centering controller. Applies whenever lane positioning is on.",
range=(0.0, 50.0)),
Setting("FordLowSpeedFactor_ang", float, 1.0, PER_FRAME, "Low Speed Adjustment Factor",
"Scales the low-speed steering response in angle mode. Adjust for personal feel. Default 1.0.",
range=(0.5, 1.5), clamp=True),
Setting("FordHighSpeedFactor_ang", float, 1.0, PER_FRAME, "High Speed Adjustment Factor",
"Scales the high-speed steering response in angle mode. Adjust for personal feel. Default 1.0.",
range=(0.5, 1.5), clamp=True),
Setting("FordHighSpeedDampening_ang", float, 1.0, PER_FRAME, "High Speed Low Curve Adjustment Factor",
"Tune adjustment factor for low curve straightaways (highways) at high speeds. If oversteering, reduce. " +
"If understeering, increase", range=(0.25, 1.25), clamp=True),
Setting("lane_change_factor_high_ang", float, 1.0, PER_FRAME, "Lane Change Factor High",
"Scales steering during a lane change (angle control). Values >1.0 boost it.", range=(0.85, 1.5), clamp=True),
Setting("custom_path_offset_ang", float, 0.0, PER_FRAME, "In-Lane Offset",
"Adjust the in-lane offset (-0.5 to 0.5).", range=(-0.5, 0.5), clamp=True),
Setting("lane_centering_strength_ang", float, 0.25, PER_FRAME, "Lane Centering Strength",
"How much authority the lane centering trim has vs. the model's own path (0.0-1.0).",
range=(0.0, 1.0), clamp=True),
Setting("FordPrefSteerAngleCurvature", bool, False, STARTUP, "Use Pinion Yaw Sensor",
"Measures how the car is turning from the steering pinion angle sensor instead of a faulty RCM yaw sensor " +
'(symptoms: "Turn Exceeds Steering Limit" warnings, weak curve tracking, "Service AdvanceTrac"). Check with ' +
"tools/ford_yaw_health_check.py. Applies the next time the car starts. Not available on the Edge."),
)
_BY_KEY = {s.key: s for s in SETTINGS}
# what a host publishes in CarControlSP.params every frame (values_ext.BP_LATERAL_PARAMS)
PER_FRAME_KEYS = tuple(s.key for s in SETTINGS if s.read != STARTUP)
def _parse(setting: Setting, raw):
"""The setting's value from what the host gave, or None if there is nothing usable."""
if isinstance(raw, (bytes, bytearray)):
raw = raw.decode("utf-8", errors="replace")
if raw is None or raw == "":
return None
if setting.type is bool:
if isinstance(raw, (bool, int)):
return bool(raw)
text = str(raw).strip().lower()
return True if text in ("1", "true") else False if text in ("0", "false") else None
try:
v = setting.type(raw)
except (TypeError, ValueError):
return None
if setting.clamp and setting.range is not None:
v = setting.type(min(max(v, setting.range[0]), setting.range[1]))
return v
def default(key: str):
return _BY_KEY[key].default
def value(params, key: str):
"""A per-frame setting from the host's ParamStore (built from this frame's (key, value) pairs)."""
setting = _BY_KEY[key]
assert setting.read != STARTUP, f"{key} is read at startup only: hosts don't publish it per frame"
v = _parse(setting, params.get(key))
return setting.default if v is None else v
def startup_value(params_dict: dict, key: str):
"""A startup setting from get_car's params dict (values as Params returned them)."""
setting = _BY_KEY[key]
assert setting.read != PER_FRAME, f"{key} is read per frame only: hosts don't pass it at startup"
v = _parse(setting, params_dict.get(key))
return setting.default if v is None else v
def params_keys_lines() -> list[str]:
"""A host's params_keys.h entries for every setting."""
types = {bool: "BOOL", int: "INT", float: "FLOAT"}
def text(s):
return ("1" if s.default else "0") if s.type is bool else str(s.default)
return [f'{{"{s.key}", {{PERSISTENT | BACKUP, {types[s.type]}, "{text(s)}"}}}},' for s in SETTINGS]
if __name__ == "__main__":
print("\n".join(params_keys_lines()))
@@ -1,17 +0,0 @@
"""
BluePilot: the settings a host published this frame, by key (HOSTS.md). The lateral code reads every
setting through params/manifest.py's value(), which parses the published text and takes the manifest
default for a key that is missing, empty or unparsable. A host publishes every per-frame key anyway,
using its own registry default for one never written.
"""
class ParamStore:
def __init__(self, pairs):
"""pairs: the (key, value) settings a host published this frame, value as bytes or text."""
self._values = dict(pairs)
def get(self, key):
"""The published value as text, or None if the host didn't publish the key."""
v = self._values.get(key)
return v.decode("utf-8", errors="replace") if isinstance(v, (bytes, bytearray)) else v
@@ -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
@@ -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
}
@@ -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
@@ -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,
}
@@ -1,383 +0,0 @@
/**
* BluePilot Ford lateral-control extensions: state and implementations.
* See ford_declarations.h in this directory for the declarations.
*/
#pragma once
#include "../safety/ford_declarations.h"
#include "../safety/lateral.h"
// ===============================
// Global Variables
// ===============================
bool ford_bp_lateral = false; // SP safety-param bit 5: BP 4-signal lateral checks instead of stock
bool ford_bp_pinion_curvature = false;
const AngleSteeringParams *ford_bp_pinion_params = &ford_pinion_geometry[0];
// BluePilot: per-platform geometry for pinion-angle -> curvature conversion (the optional
// angle_meas source), selected by the 4-bit geometry index in current_safety_param_sp
// bits 1-4. Row order and values must match FORD_PINION_GEOMETRY_INDEX in
// bluepilot_lateral/core/values_ext.py (enforced by test_ford_bluepilot_pinion.py's
// geometry test against CarSpecs + calc_slip_factor(VehicleModel(CP)), with the wheelbase
// overrides in FORD_PINION_WHEELBASE applied).
// Index 0 is reserved as invalid; ford_bp_init disables the feature outright on a zero or
// out-of-range index so a half-configured param can never select the wrong geometry.
// FORD_EDGE_MK2 (ALT_STEER_ANGLE: relative pinion angle + learned offset) is unsupported
// and deliberately absent.
const AngleSteeringParams ford_pinion_geometry[FORD_PINION_GEOMETRY_ROWS] = {
{.slip_factor = 0.0f, .steer_ratio = 1.0f, .wheelbase = 1.0f}, // 0: invalid
{.slip_factor = -0.00062819555f, .steer_ratio = 17.7f, .wheelbase = 2.670f}, // 1: FORD_BRONCO_SPORT_MK1
{.slip_factor = -0.00061892325f, .steer_ratio = 16.7f, .wheelbase = 2.710f}, // 2: FORD_ESCAPE_MK4
{.slip_factor = -0.00061892325f, .steer_ratio = 16.7f, .wheelbase = 2.710f}, // 3: FORD_ESCAPE_MK4_5
{.slip_factor = -0.00045454798f, .steer_ratio = 17.0f, .wheelbase = 3.690f}, // 4: FORD_EXPEDITION_MK4
{.slip_factor = -0.00055447339f, .steer_ratio = 16.8f, .wheelbase = 3.025f}, // 5: FORD_EXPLORER_MK6
{.slip_factor = -0.00062121569f, .steer_ratio = 15.0f, .wheelbase = 2.700f}, // 6: FORD_FOCUS_MK4
{.slip_factor = -0.00045331952f, .steer_ratio = 16.9f, .wheelbase = 3.700f}, // 7: FORD_F_150_LIGHTNING_MK1
{.slip_factor = -0.00043679222f, .steer_ratio = 17.0f, .wheelbase = 3.840f}, // 8: FORD_F_150_MK14 (average wheelbase, #21)
{.slip_factor = -0.00054528036f, .steer_ratio = 17.0f, .wheelbase = 3.076f}, // 9: FORD_MAVERICK_MK1
{.slip_factor = -0.00058852001f, .steer_ratio = 14.8f, .wheelbase = 2.850f}, // 10: FORD_MONDEO_MK5
{.slip_factor = -0.00056209187f, .steer_ratio = 17.0f, .wheelbase = 2.984f}, // 11: FORD_MUSTANG_MACH_E_MK1
{.slip_factor = -0.00051293030f, .steer_ratio = 17.0f, .wheelbase = 3.270f}, // 12: FORD_RANGER_MK2
};
bool ford_bp_angle_mode_engaged = false;
int16_t ford_bp_shadow_curvature_raw = 0; // wire units, scale 1e-6 1/m (LANE_ASSIST_DATA1.md)
int desired_path_angle_last = 0;
int desired_path_offset_last = 0;
// ===============================
// Function Implementations
// ===============================
static inline bool path_angle_cmd_checks(int desired_path_angle, bool steer_control_enabled, const AngleSteeringLimits limits) {
bool violation = false;
if (steer_control_enabled) {
float speed = ((float)vehicle_speed.min / VEHICLE_SPEED_FACTOR) - 1.;
int delta_path_angle_roc = (safety_interpolate(limits.angle_rate_up_lookup, speed) * limits.angle_deg_to_can) + 1.;
int highest_desired_path_angle = desired_path_angle_last + delta_path_angle_roc;
int lowest_desired_path_angle = desired_path_angle_last - delta_path_angle_roc;
violation |= safety_max_limit_check(desired_path_angle, highest_desired_path_angle, lowest_desired_path_angle);
FORD_BP_DBG("path_angle_cmd_checks 1: desired_path_angle: %d desired_path_angle_last: %d highest_desired_path_angle: %d lowest_desired_path_angle: %d violation: %d \n",
desired_path_angle, desired_path_angle_last, highest_desired_path_angle, lowest_desired_path_angle, (int)violation);
}
desired_path_angle_last = desired_path_angle;
if (!steer_control_enabled) {
violation |= (desired_path_angle != 0);
}
FORD_BP_DBG("path_angle_cmd_checks 2: violation: %d \n", (int)violation);
return violation;
}
static inline bool path_offset_cmd_checks(int desired_path_offset, bool steer_control_enabled, const AngleSteeringLimits limits) {
bool violation = false;
if (steer_control_enabled) {
float speed = ((float)vehicle_speed.min / VEHICLE_SPEED_FACTOR) - 1.;
int delta_path_offset_roc = (safety_interpolate(limits.angle_rate_up_lookup, speed) * limits.angle_deg_to_can) + 1.;
int highest_desired_path_offset = desired_path_offset_last + delta_path_offset_roc;
int lowest_desired_path_offset = desired_path_offset_last - delta_path_offset_roc;
violation |= safety_max_limit_check(desired_path_offset, highest_desired_path_offset, lowest_desired_path_offset);
FORD_BP_DBG("path_offset_cmd_checks 1: desired_path_offset: %d desired_path_offset_last: %d highest_desired_path_offset: %d lowest_desired_path_offset: %d violation: %d \n",
desired_path_offset, desired_path_offset_last, highest_desired_path_offset, lowest_desired_path_offset, (int)violation);
}
desired_path_offset_last = desired_path_offset;
if (!steer_control_enabled) {
violation |= (desired_path_offset != 0);
}
FORD_BP_DBG("path_offset_cmd_checks 2: violation: %d \n", (int)violation);
return violation;
}
// BluePilot: angle mode has no "current path_angle" measurement to check the command against,
// unlike curvature mode, which compares desired_curvature against angle_meas (measured curvature,
// from yaw rate). Without this, a large deviation between commanded path_angle and the car's ACTUAL
// curvature -- e.g. a pothole or driver override kicking the wheel -- would go unchecked: path_angle's
// own ROC only bounds how fast the *command* changes, not how far it may sit from reality.
//
// Deliberately narrower than steer_angle_cmd_checks: no rate-of-change enforcement here, and no
// shared state (desired_angle_last) with curvature mode. path_angle already has its own dedicated,
// tuned ROC (path_angle_cmd_checks / FORD_PATH_ANGLE_LIMITS); imposing a second, curvature-tuned ROC
// on shadow_curvature -- which isn't an actuator, just a cross-check value -- would risk spurious
// blocks unrelated to path_angle's actual behavior (confirmed on real hardware 2026-07-10: doing
// this via steer_angle_cmd_checks caused blocks at low speed from shadow_curvature jumping frame to
// frame with nothing driving it toward path_angle's own smooth ROC). This is a pure per-frame
// proximity check: does this frame's steering intent make physical sense given where the car is.
// BluePilot: enforce_angle_error is gone from the struct; the check is unconditional now because
// its only caller, ford_lmc_checks, passes the base of a BluePilot limit set (FORD_LIMITS, above
// ford_bp_lmc_tx), all of which set it true pre-sync.
static inline bool ford_shadow_curvature_error_check(int desired_curvature, bool steer_control_enabled,
const BP_HOST_CURVATURE_LIMITS limits) {
bool violation = false;
if (steer_control_enabled &&
((vehicle_speed.values[0] / VEHICLE_SPEED_FACTOR) > limits.curvature_error_min_speed)) {
int lowest_allowed = BP_HOST_CURVATURE_STATE.meas.min - limits.max_curvature_error - 1;
int highest_allowed = BP_HOST_CURVATURE_STATE.meas.max + limits.max_curvature_error + 1;
violation = safety_max_limit_check(desired_curvature, highest_allowed, lowest_allowed);
}
return violation;
}
// BluePilot: shared curvature/curvature_rate/path_offset/path_angle command checks for
// LateralMotionControl (CAN) and LateralMotionControl2 (CAN FD), in signed CAN units. limits is the
// curvature limit set ford_bp_lmc_tx picked for the message and the angle_meas source.
// dbg_prefix labels the FORD_BP_DBG output ("CAN Out" / "CANFD Out").
static inline bool ford_lmc_checks(int desired_curvature, int desired_curvature_rate, int desired_path_offset, int desired_path_angle,
bool steer_control_enabled, const FordBpCurvatureLimits *limits, const char *dbg_prefix) {
// dbg_prefix is only read inside FORD_BP_DBG, which expands to a no-op unless FORD_BP_DEBUG is defined for the
// debug build, making the parameter otherwise unused.
SAFETY_UNUSED(dbg_prefix);
// PathAngle rate limits
static const AngleSteeringLimits FORD_PATH_ANGLE_LIMITS = {
.max_angle = 1000,
// 0.0005
.angle_deg_to_can = 2000, // 1 / (2e-5) rad to can
// Mirror lateral_angle_ext.py _soft_roc: interp(v_ego, [9,10,15,25], [0.055,0.055,0.0425,0.009])
// rad/call, scaled x1.02 so panda is 2% LOOSER than the Python control and never blocks LMC2.
// lookup_t is fixed at 3 points; Python's 9 & 10 m/s nodes are both 0.055 (flat top), so {10,15,25}
// reproduces the curve exactly and speeds <10 clamp to the first point. The +1 CAN unit and the
// speed-1 fudge in path_angle_cmd_checks add extra headroom on top of the 2%.
// BluePilot: LMC2 is only sent once per CarControllerParams.STEER_STEP (5) = 20Hz, not 100Hz --
// _soft_roc's y-values (and this mirror) are per-call, not per-100Hz-tick; see lateral_angle_ext.py.
.angle_rate_up_lookup = {
.x = {10., 15., 25.},
.y = {0.0561, 0.04335, 0.00918}
},
.angle_rate_down_lookup = {
.x = {10., 15., 25.},
.y = {0.0561, 0.04335, 0.00918}
},
.frequency = 20U, // Hz -- LateralMotionControl/LateralMotionControl2 @ 20Hz (matches
// actual STEER_STEP=5 cadence; was 100U, a stale leftover from an
// abandoned 100Hz-cadence experiment. Currently unread by
// path_angle_cmd_checks (only angle_rate_up/down_lookup matter),
// but corrected for consistency/documentation and in case a future
// rt_angle_rate_limit_check() wiring starts consuming it.
};
// PathOffset rate limits
static const AngleSteeringLimits FORD_PATH_OFFSET_LIMITS = {
.max_angle = 100, // 1.0 meter in CAN units (100 * 0.01)
.angle_deg_to_can = 100, // 1 / (0.01) meter to can
.angle_rate_up_lookup = {
.x = {5., 15., 25.},
.y = {0.05, 0.025, 0.01} // Slower rate limits for path offset
},
.angle_rate_down_lookup = {
.x = {5., 15., 25.},
.y = {0.05, 0.025, 0.01} // Slower rate limits for path offset
},
.frequency = 20U, // Hz - 20Hz message rate
};
const BP_HOST_CURVATURE_LIMITS *base = &limits->base;
bool violation = false;
// Check curvature value limits (already converted to signed CAN units by the caller). Note:
// curvature's wire scale (curvature_to_can) is the same for CAN and CAN FD, so this is safe to
// read off the (possibly pinion-widened) limits struct regardless of bus.
int curvature_min_can = (int)(FORD_CURVATURE_MIN * base->curvature_to_can);
int curvature_max_can = (int)(FORD_CURVATURE_MAX * base->curvature_to_can);
violation |= (desired_curvature < curvature_min_can) || (desired_curvature > curvature_max_can);
FORD_BP_DBG("%s: desired_curvature: %d, curvature_min_can: %d, curvature_max_can: %d, violation: %d\n",
dbg_prefix, desired_curvature, curvature_min_can, curvature_max_can, (int)violation);
// Curvature rate must be 0, like stock Ford: BluePilot always sends 0 (#22)
violation |= (desired_curvature_rate != 0);
FORD_BP_DBG("%s: desired_curvature_rate: %d, violation: %d\n", dbg_prefix, desired_curvature_rate, (int)violation);
// Check path offset value limits
int path_offset_min_can = (int)(FORD_PATH_OFFSET_MIN * FORD_PATH_OFFSET_LIMITS.angle_deg_to_can);
int path_offset_max_can = (int)(FORD_PATH_OFFSET_MAX * FORD_PATH_OFFSET_LIMITS.angle_deg_to_can);
violation |= (desired_path_offset < path_offset_min_can) || (desired_path_offset > path_offset_max_can);
FORD_BP_DBG("%s: desired_path_offset: %d, path_offset_min_can: %d, path_offset_max_can: %d, violation: %d\n",
dbg_prefix, desired_path_offset, path_offset_min_can, path_offset_max_can, (int)violation);
// Check path angle value limits. Angle mode uses path_angle as the actuator and may swing to
// the full DBC range, corroborated by ford_bp_angle_mode_engaged so a frame can't unlock this
// wider range by merely setting curvature to 0. Curvature mode always keeps the tight cap,
// including at curvature == 0 (straight driving, or the reset/human-turn frame) -- path_angle
// there only trims and amplifies wound-up curvature, never needs the wide range.
float path_angle_min_phys = ford_bp_angle_mode_engaged ? FORD_DBC_PATH_ANGLE_MIN : FORD_PATH_ANGLE_MIN;
float path_angle_max_phys = ford_bp_angle_mode_engaged ? FORD_DBC_PATH_ANGLE_MAX : FORD_PATH_ANGLE_MAX;
const float path_angle_min_scaled = path_angle_min_phys * FORD_PATH_ANGLE_LIMITS.angle_deg_to_can;
const float path_angle_max_scaled = path_angle_max_phys * FORD_PATH_ANGLE_LIMITS.angle_deg_to_can;
int path_angle_min_can = (int)path_angle_min_scaled;
int path_angle_max_can = (int)path_angle_max_scaled;
violation |= (desired_path_angle < path_angle_min_can) || (desired_path_angle > path_angle_max_can);
FORD_BP_DBG("%s: desired_path_angle: %d, path_angle_min_can: %d, path_angle_max_can: %d, violation: %d\n",
dbg_prefix, desired_path_angle, path_angle_min_can, path_angle_max_can, (int)violation);
// Check the curvature command and steer_control_enabled. At curvature 0 (angle mode, where
// path_angle does the steering, and curvature mode's reset frame) ford_bp_curvature_cmd_checks skips
// its value checks itself and keeps the speed cross-check, message-rate check and controls gate;
// path_angle keeps its own checks regardless.
violation |= ford_bp_curvature_cmd_checks(desired_curvature, steer_control_enabled, limits);
FORD_BP_DBG("%s: 1. desired_curvature violation: %d\n", dbg_prefix, (int)violation);
// Angle mode's own deviation-only check against shadow_curvature, once angle mode is confirmed
// engaged. If desired_curvature == 0 but angle mode is NOT confirmed, this is skipped -- that's
// ordinary curvature mode at zero (straight driving or the reset/human-turn frame), which needs
// no shadow-curvature check; it's still bounded by the tight path_angle range above and
// steer_control_enabled's own checks.
if ((desired_curvature == 0) && ford_bp_angle_mode_engaged) {
const float shadow_curvature_scaled = (float)ford_bp_shadow_curvature_raw * FORD_BP_LKA_SHADOW_RAW_TO_CAN;
int shadow_curvature_can = (int)shadow_curvature_scaled;
violation |= ford_shadow_curvature_error_check(shadow_curvature_can, steer_control_enabled, *base);
}
// Check path angle rate of change limits
violation |= path_angle_cmd_checks(desired_path_angle, steer_control_enabled, FORD_PATH_ANGLE_LIMITS);
FORD_BP_DBG("%s: 2. desired_path_angle violation: %d\n", dbg_prefix, (int)violation);
// Check path offset rate of change limits
violation |= path_offset_cmd_checks(desired_path_offset, steer_control_enabled, FORD_PATH_OFFSET_LIMITS);
FORD_BP_DBG("%s: 3. desired_path_offset violation: %d\n", dbg_prefix, (int)violation);
return violation;
}
// BluePilot: the curvature limit sets ford_bp_lmc_tx picks from: the host's BP_HOST_CURVATURE_LIMITS as
// .base plus the measured rate tables, checked by ford_bp_curvature_cmd_checks instead of upstream's
// ISO-jerk-derived delta. The values are the pre-sync macro's. max_curv_err is 100 (0.002) on the stock
// yaw-sourced angle_meas path and 150 (0.003) on the pinion-sourced path (STEER_ANGLE_CURVATURE):
// firmware uses the raw pinion angle, with no roll/alignment-offset compensation (the Python layer
// compensates via liveParameters). ford_bp_curvature_cmd_checks assumes max_steer_power 0 and
// inactive_curvature_is_zero true rather than reading them, and base sets only the fields the library
// reads, so it initializes upstream's CurvatureSteeringLimits and a host's narrower struct alike.
#define FORD_LIMITS(limit_lateral_accel, max_curv_err) { \
.base = { \
.max_curvature = 1000, /* 0.02 curvature */ \
.curvature_to_can = 50000, /* 1 / (2e-5) rad to can */ \
.frequency = 20U, /* LateralMotionControl / LateralMotionControl2 @ 20 Hz */ \
.max_curvature_error = (max_curv_err), \
/* no blending at low speed due to lack of torque wind-up and inaccurate current curvature */\
.curvature_error_min_speed = 10.0, /* m/s */ \
}, \
/* Down table 1% looser than up (#20); both >= the Python control's tables (values_ext) */ \
.curvature_rate_up_lookup = { \
{5., 16., 25.}, \
{0.0025f, 0.0014f, 0.00018f} \
}, \
.curvature_rate_down_lookup = { \
{5., 16., 25.}, \
{0.002525f, 0.001414f, 0.0001818f} \
}, \
.limit_lateral_acceleration = (limit_lateral_accel), \
}
// BluePilot: LateralMotionControl (CAN) or LateralMotionControl2 (CAN FD) with BP lateral on. Both
// messages carry the same four signals; ford_tx_hook decodes the raw values, and this converts them
// to signed CAN units (physical = raw * scale - offset), picks the limit set for the message and the
// angle_meas source, and runs ford_lmc_checks.
static inline bool ford_bp_lmc_tx(bool canfd, unsigned int raw_curvature, unsigned int raw_curvature_rate,
unsigned int raw_path_offset, unsigned int raw_path_angle, bool steer_control_enabled) {
// static inside the one function that reads them (MISRA 8.9)
static const FordBpCurvatureLimits FORD_BP_STEERING_LIMITS = FORD_LIMITS(false, 100);
static const FordBpCurvatureLimits FORD_BP_STEERING_LIMITS_PINION = FORD_LIMITS(false, 150);
static const FordBpCurvatureLimits FORD_CANFD_STEERING_LIMITS = FORD_LIMITS(true, 100);
static const FordBpCurvatureLimits FORD_CANFD_STEERING_LIMITS_PINION = FORD_LIMITS(true, 150);
const FordBpCurvatureLimits *limits;
unsigned int inactive_curvature_rate;
const char *dbg_prefix;
if (canfd) {
limits = ford_bp_pinion_curvature ? &FORD_CANFD_STEERING_LIMITS_PINION : &FORD_CANFD_STEERING_LIMITS;
inactive_curvature_rate = FORD_CANFD_INACTIVE_CURVATURE_RATE;
dbg_prefix = "CANFD Out";
} else {
limits = ford_bp_pinion_curvature ? &FORD_BP_STEERING_LIMITS_PINION : &FORD_BP_STEERING_LIMITS;
inactive_curvature_rate = FORD_INACTIVE_CURVATURE_RATE;
dbg_prefix = "CAN Out";
}
int desired_curvature = raw_curvature - FORD_INACTIVE_CURVATURE;
int desired_curvature_rate = raw_curvature_rate - inactive_curvature_rate;
int desired_path_offset = raw_path_offset - FORD_INACTIVE_PATH_OFFSET;
int desired_path_angle = raw_path_angle - FORD_INACTIVE_PATH_ANGLE;
return ford_lmc_checks(desired_curvature, desired_curvature_rate, desired_path_offset, desired_path_angle,
steer_control_enabled, limits, dbg_prefix);
}
// BluePilot: angle_mode_engaged and shadow_curvature ride in Lane_Assist_Data1 bits with no DBC
// signal mapped to them (layout: bluepilot_lateral/can/LANE_ASSIST_DATA1.md), read out of
// the frame being sent. A separate CAN message (0x5F0)
// was tried first: the panda never receives its own TX, and an RX check for it tripped
// safety_tick's lagging check and blocked controls car-wide (2026-07-09).
static inline void ford_bp_lka_tx(const CANPacket_t *msg) {
ford_bp_angle_mode_engaged = (msg->data[FORD_BP_LKA_ANGLE_MODE_BYTE] & FORD_BP_LKA_ANGLE_MODE_MASK) != 0U;
unsigned int shadow_curvature_raw = (msg->data[FORD_BP_LKA_SHADOW_MSB_BYTE] << 8) | msg->data[FORD_BP_LKA_SHADOW_LSB_BYTE];
ford_bp_shadow_curvature_raw = (int16_t)shadow_curvature_raw;
}
// BluePilot: optional angle_meas source -- measured curvature from the steering pinion angle (PSCM)
// via the vehicle model, for vehicles whose RCM broadcasts implausible yaw (sign-inverted vs
// IMU/steering geometry) while its quality flag still reads OK. The pinion angle was validated
// against the comma IMU (corr +0.99 on real routes); the Python control layer measures from the
// same source when this is enabled (carcontroller_ext.InputTracker.get_current_curvature), so the layers always
// agree. ford_rx_hook skips its yaw block while this source is on.
static inline void ford_bp_rx_hook(const CANPacket_t *msg) {
// addr and bus compared directly, not with upstream's msg_matches, which not every host has
if ((msg->addr == FORD_SteeringPinion_Data) && (msg->bus == FORD_MAIN_BUS) && ford_bp_pinion_curvature) {
// Signal: StePinComp_An_Est, 22|15@0+ (0.1,-1600) deg
int angle_raw = ((msg->data[2] & 0x7FU) << 8) | msg->data[3];
float pinion_angle_deg = ((float)angle_raw * 0.1f) - 1600.0f;
float pinion_angle_rad = pinion_angle_deg * 0.017453292519943295f; // DEG_TO_RAD
// angle -> curvature via vehicle model (matches VehicleModel.curvature_factor);
// sign: firmware angle_meas is Ford wire convention (the yaw block uses +yaw/v), and
// pinion angle correlates +0.97 with wire desired curvature on real frames -> positive.
float speed = SAFETY_MAX(vehicle_speed.values[0] / VEHICLE_SPEED_FACTOR, 0.1);
float curvature_factor = get_curvature_factor(speed, *ford_bp_pinion_params);
float current_curvature = pinion_angle_rad * curvature_factor / ford_bp_pinion_params->steer_ratio;
// convert current curvature into units on CAN for comparison with desired curvature
update_sample(&BP_HOST_CURVATURE_STATE.meas, ROUND(current_curvature * FORD_STEERING_LIMITS.curvature_to_can));
}
}
// BluePilot: read the SP safety param and reset the BP lateral state. param_sp is
// current_safety_param_sp, delivered via USB 0xdf before the safety model is set (a separate uint16
// from ford_init's param; pattern: subaru_common.h). Bits: 0 pinion-curvature enable, 1-4 pinion
// geometry index, 5 BP 4-signal lateral (clear = upstream's stock lateral safety, verbatim). A zero
// or out-of-range index disables the pinion source, so a half-configured param can never select the
// wrong geometry: the stock yaw path is kept. Returns whether the pinion source is on, i.e. whether
// ford_init applies the pinion RX check (ford_rx_checks_pinion). That check stays out of the stock
// config, so a pinion hiccup can't disable controls for users who never consume the message.
static inline bool ford_bp_init(uint16_t param_sp) {
const uint16_t FORD_PARAM_SP_BP_LATERAL = 32;
ford_bp_lateral = GET_FLAG(param_sp, FORD_PARAM_SP_BP_LATERAL);
const uint16_t FORD_PARAM_SP_STEER_ANGLE_CURVATURE = 1;
// Pinion measurement is only valid with the BP checks: the stock error band (100) was tuned for the
// yaw source and the stock Python path clips against yaw-derived curvature.
bool pinion_enabled = ford_bp_lateral && GET_FLAG(param_sp, FORD_PARAM_SP_STEER_ANGLE_CURVATURE);
const uint16_t pinion_geometry_index = (param_sp >> 1) & 0xFU;
if ((pinion_geometry_index == 0U) || (pinion_geometry_index > FORD_PINION_GEOMETRY_COUNT)) {
pinion_enabled = false;
}
ford_bp_pinion_curvature = pinion_enabled;
ford_bp_pinion_params = pinion_enabled ? &ford_pinion_geometry[pinion_geometry_index] : &ford_pinion_geometry[0];
// start from a clean BP lateral state, as set_safety_hooks does for upstream's (desired_angle_last
// etc.), so a re-init never checks against a previous session's commands. The angle-mode flag is
// set again by the next Lane_Assist_Data1 frame.
desired_path_angle_last = 0;
desired_path_offset_last = 0;
ford_bp_angle_mode_engaged = false;
return ford_bp_pinion_curvature;
}
@@ -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 = &current_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;
}
@@ -1,99 +0,0 @@
/**
* BluePilot Ford lateral-control extensions: type declarations, state, and prototypes.
* See ford.h in this directory for the implementations.
*/
#pragma once
#include "../../safety/declarations.h"
#include "../safety/lateral_declarations.h"
// BluePilot: Ford safety debug prints. Compile-time switch: build with -DFORD_BP_DEBUG (bench /
// libsafety only) to turn every FORD_BP_DBG into a printf; otherwise it expands to nothing, so CI
// coverage and mutation see no code and the panda build carries no runtime flag. The printf
// branch is bench-only and is not part of the MISRA-checked configuration (test_misra.sh runs
// without FORD_BP_DEBUG). To use it on the bench, compile libsafety with
// cc ... -DALLOW_DEBUG -DFORD_BP_DEBUG -I . -c <pkg>/safety/tests/libsafety/safety.c
// (the same flags <pkg>/safety/tests/libsafety/libsafety_py.py uses, plus FORD_BP_DEBUG; <pkg> is the
// host's opendbc package: opendbc, iqdbc).
#ifdef FORD_BP_DEBUG
#include <stdio.h>
#define FORD_BP_DBG(...) printf(__VA_ARGS__)
#else
#define FORD_BP_DBG(...) ((void)0)
#endif
// ===============================
// Constants and Defines
// ===============================
// BluePilot: steering-angle curvature measurement (bad-yaw-sensor workaround). Index 0 of
// ford_pinion_geometry is reserved as invalid; see ford_bp_init in ford.h.
#define FORD_PINION_GEOMETRY_COUNT 12U
// Row count including the reserved index-0 entry. Kept as a plain literal: the mutation
// harness rewrites arithmetic in array sizes into runtime expressions, which cannot compile.
#define FORD_PINION_GEOMETRY_ROWS 13U
// Control signal limits -- curvature magnitude must match MAX_CURVATURE; rate tables must match
// bluepilot_lateral/core/values_ext.py BP_ANGLE_LIMITS.
#define FORD_CURVATURE_MIN -0.02f
#define FORD_CURVATURE_MAX 0.02f
#define FORD_PATH_OFFSET_MIN -1.0f
#define FORD_PATH_OFFSET_MAX 1.0f
#define FORD_PATH_ANGLE_MIN -0.25f
#define FORD_PATH_ANGLE_MAX 0.25f
// BluePilot: full DBC signal range for path_angle (LatCtlPath_An, 0.0005 scale). Used as the
// value limit in ANGLE mode, where path_angle is the steering actuator (see ford_lmc_checks).
// Matches lateral_angle_ext.py FORD_DBC_PATH_ANGLE_MIN/MAX. In curvature mode the tight ±0.25
// cap above applies instead (path_angle there only trims and amplifies wound-up curvature).
#define FORD_DBC_PATH_ANGLE_MIN -0.5f
#define FORD_DBC_PATH_ANGLE_MAX 0.5235f
// ===============================
// Global Variables
// ===============================
// BluePilot: optional angle_meas source, measured curvature from the steering pinion angle
// (PSCM) via the vehicle model, selected by the geometry index in current_safety_param_sp
// bits 1-4. Default off = stock yaw-sourced angle_meas. See ford_bp_init in ford.h.
extern bool ford_bp_lateral;
extern bool ford_bp_pinion_curvature;
extern const AngleSteeringParams *ford_bp_pinion_params;
extern const AngleSteeringParams ford_pinion_geometry[FORD_PINION_GEOMETRY_ROWS];
// BluePilot: angle_mode_engaged + shadow_curvature, read out of Lane_Assist_Data1's unused
// bits by ford_bp_lka_tx (no separate CAN message, no RX). The layout is in
// bluepilot_lateral/can/LANE_ASSIST_DATA1.md; fordcan_ext.py packs it with the same values
// (tests/test_lane_assist_data1.py).
#define FORD_BP_LKA_ANGLE_MODE_BYTE 4U
#define FORD_BP_LKA_ANGLE_MODE_MASK 0x1U
#define FORD_BP_LKA_SHADOW_MSB_BYTE 5U // shadow curvature: int16, big-endian, bytes 5-6
#define FORD_BP_LKA_SHADOW_LSB_BYTE 6U
// shadow curvature raw units (1e-6 1/m) to curvature CAN units (2e-5 1/m)
#define FORD_BP_LKA_SHADOW_RAW_TO_CAN 0.05f
extern bool ford_bp_angle_mode_engaged;
extern int16_t ford_bp_shadow_curvature_raw; // wire units, scale 1e-6 1/m (LANE_ASSIST_DATA1.md)
// last commanded values for the path_angle / path_offset rate-of-change checks
extern int desired_path_angle_last;
extern int desired_path_offset_last;
// ===============================
// Function Declarations
// ===============================
static inline bool path_angle_cmd_checks(int desired_path_angle, bool steer_control_enabled, AngleSteeringLimits limits);
static inline bool path_offset_cmd_checks(int desired_path_offset, bool steer_control_enabled, AngleSteeringLimits limits);
static inline bool ford_shadow_curvature_error_check(int desired_curvature, bool steer_control_enabled, BP_HOST_CURVATURE_LIMITS limits);
// Shared curvature/curvature_rate/path_offset/path_angle command checks for LateralMotionControl
// (CAN) and LateralMotionControl2 (CAN FD) -- see ford_lmc_checks in ford.h.
static inline bool ford_lmc_checks(int desired_curvature, int desired_curvature_rate, int desired_path_offset, int desired_path_angle,
bool steer_control_enabled, const FordBpCurvatureLimits *limits, const char *dbg_prefix);
// Called from modes/ford.h's hooks and ford_init -- see bluepilot_lateral/safety/ford.h.
static inline bool ford_bp_lmc_tx(bool canfd, unsigned int raw_curvature, unsigned int raw_curvature_rate,
unsigned int raw_path_offset, unsigned int raw_path_angle, bool steer_control_enabled);
static inline void ford_bp_lka_tx(const CANPacket_t *msg);
static inline void ford_bp_rx_hook(const CANPacket_t *msg);
static inline bool ford_bp_init(uint16_t param_sp);
@@ -1,121 +0,0 @@
/**
* BluePilot lateral-control extensions shared across safety modes: implementation.
* See lateral_declarations.h in this directory for the declarations.
*/
#pragma once
#include "../safety/lateral_declarations.h"
// BluePilot: measured-table rate limiting. This is the pre-sync steer_angle_cmd_checks logic,
// carried over verbatim in the curvature domain so Ford lateral behavior is unchanged by the
// move off AngleSteeringLimits. Differences from upstream's ISO-only path (steer_curvature_cmd_checks
// in opendbc/safety/lateral.h) that matter:
// - asymmetric up/down deltas selected by the sign of the last command
// - the error boundary uses relaxed deltas and CONVERGES toward measured, rather than
// hard-clamping, so a wound-up command unwinds instead of instantly faulting
// - the ISO lateral accel cap is applied only on buses that need it (Q4/CAN FD)
static inline bool ford_bp_curvature_rate_lookup_check(int desired_curvature, const FordBpCurvatureLimits *limits) {
const BP_HOST_CURVATURE_LIMITS *base = &limits->base;
bool violation = false;
const float fudged_speed_lookup = (vehicle_speed.min / VEHICLE_SPEED_FACTOR) - 1.;
const int delta_up = (safety_interpolate(limits->curvature_rate_up_lookup, fudged_speed_lookup) * base->curvature_to_can) + 1.;
const int delta_down = (safety_interpolate(limits->curvature_rate_down_lookup, fudged_speed_lookup) * base->curvature_to_can) + 1.;
// allow down limits at zero since small floats from openpilot will be rounded to 0
int highest_desired_curvature = BP_HOST_CURVATURE_STATE.desired_last + ((BP_HOST_CURVATURE_STATE.desired_last > 0) ? delta_up : delta_down);
int lowest_desired_curvature = BP_HOST_CURVATURE_STATE.desired_last - ((BP_HOST_CURVATURE_STATE.desired_last >= 0) ? delta_down : delta_up);
if (base->max_curvature_error && ((vehicle_speed.values[0] / VEHICLE_SPEED_FACTOR) > base->curvature_error_min_speed)) {
// flipped fudge to avoid false positives
const float fudged_speed_error = (vehicle_speed.max / VEHICLE_SPEED_FACTOR) + 1.;
const int delta_up_relaxed = (safety_interpolate(limits->curvature_rate_up_lookup, fudged_speed_error) * base->curvature_to_can) - 1.;
const int delta_down_relaxed = (safety_interpolate(limits->curvature_rate_down_lookup, fudged_speed_error) * base->curvature_to_can) - 1.;
const int lowest_desired_curvature_error = BP_HOST_CURVATURE_STATE.meas.min - base->max_curvature_error - 1;
const int highest_desired_curvature_error = BP_HOST_CURVATURE_STATE.meas.max + base->max_curvature_error + 1;
// the MAX/MIN allow the desired value to reach the edge of the bounds without going under
if (BP_HOST_CURVATURE_STATE.desired_last > highest_desired_curvature_error) {
const int delta = (BP_HOST_CURVATURE_STATE.desired_last >= 0) ? delta_down_relaxed : delta_up_relaxed;
highest_desired_curvature = SAFETY_MAX(BP_HOST_CURVATURE_STATE.desired_last - delta, highest_desired_curvature_error);
} else if (BP_HOST_CURVATURE_STATE.desired_last < lowest_desired_curvature_error) {
const int delta = (BP_HOST_CURVATURE_STATE.desired_last <= 0) ? delta_down_relaxed : delta_up_relaxed;
lowest_desired_curvature = SAFETY_MIN(BP_HOST_CURVATURE_STATE.desired_last + delta, lowest_desired_curvature_error);
} else {
// already inside error boundary, don't allow commanding outside it
highest_desired_curvature = SAFETY_MIN(highest_desired_curvature, highest_desired_curvature_error);
lowest_desired_curvature = SAFETY_MAX(lowest_desired_curvature, lowest_desired_curvature_error);
}
// don't enforce above the max curvature
lowest_desired_curvature = SAFETY_CLAMP(lowest_desired_curvature, -base->max_curvature, base->max_curvature);
highest_desired_curvature = SAFETY_CLAMP(highest_desired_curvature, -base->max_curvature, base->max_curvature);
}
violation |= safety_max_limit_check(desired_curvature, highest_desired_curvature, lowest_desired_curvature);
if (limits->limit_lateral_acceleration) {
// Limit to average banked road since safety doesn't have the roll. NOTE: this is the
// pre-sync constant (ISO_LATERAL_ACCEL MINUS the roll term, ~2.4 m/s^2), not the
// MAX_LATERAL_ACCEL used by the ISO path in steer_curvature_cmd_checks (~3.6 m/s^2). Do not
// merge the two.
static const float BP_MAX_LATERAL_ACCEL = ISO_LATERAL_ACCEL - (EARTH_G * AVERAGE_ROAD_ROLL);
const float fudged_speed = SAFETY_MAX((vehicle_speed.min / VEHICLE_SPEED_FACTOR) - 1.0, 1.0);
const float max_curvature_accel = BP_MAX_LATERAL_ACCEL / (fudged_speed * fudged_speed);
const int max_curvature_accel_can = (max_curvature_accel * base->curvature_to_can) + 1.;
violation |= safety_max_limit_check(desired_curvature, max_curvature_accel_can, -max_curvature_accel_can);
}
return violation;
}
// BluePilot: upstream's steer_curvature_cmd_checks (opendbc/safety/lateral.h) with
// ford_bp_curvature_rate_lookup_check in place of its ISO lateral accel and jerk checks. Ford has no
// steer power signal (max_steer_power 0) and resets to zero on a violation
// (inactive_curvature_is_zero), so only those sides of upstream's branches are kept.
// The other difference from upstream: curvature 0 (no curvature command: angle mode, curvature
// mode's reset frame) skips the cap and rate-table checks, keeping the message-rate check and the
// gates. Keep it when re-syncing against upstream (#60).
static inline bool ford_bp_curvature_cmd_checks(int desired_curvature, bool steer_control_enabled,
const FordBpCurvatureLimits *limits) {
bool violation = false;
BP_HOST_SPEED_MISMATCH_CHECK();
if (BP_HOST_LAT_ALLOWED() && steer_control_enabled) {
// BluePilot: curvature 0 is the no-curvature-command sentinel (angle mode steers with path_angle
// and holds curvature at 0; curvature mode's reset frame sends 0), so the value checks don't
// apply to it: the error band would trip as the car turns while the command stays at 0. The
// message-rate check and the gates below still run.
if (desired_curvature != 0) {
// *** absolute curvature cap ***
violation |= safety_max_limit_check(desired_curvature, limits->base.max_curvature, -limits->base.max_curvature);
// *** measured-table rate limits, error band and (CAN FD) lateral accel cap ***
violation |= ford_bp_curvature_rate_lookup_check(desired_curvature, limits);
}
// *** real time rate limit check ***
violation |= BP_HOST_RT_CURVATURE_RATE_CHECK(limits->base);
}
BP_HOST_CURVATURE_STATE.desired_last = desired_curvature;
// Curvature must be 0 while not steering
if (!steer_control_enabled) {
violation |= desired_curvature != 0;
}
// No curvature control allowed when controls are not allowed
violation |= !BP_HOST_LAT_ALLOWED() && steer_control_enabled;
// reset to zero (inactive_curvature_is_zero)
if (violation || !BP_HOST_LAT_ALLOWED()) {
BP_HOST_CURVATURE_STATE.desired_last = 0;
}
return violation;
}
@@ -1,60 +0,0 @@
/**
* BluePilot lateral-control extensions shared across safety modes: declarations.
* See lateral.h in this directory for the implementation.
*/
#pragma once
#include "../../safety/declarations.h"
// BluePilot: the host bindings. The library is written against comma's opendbc safety names; a host
// whose names differ defines these before including safety/ford.h (HOSTS.md, "Host bindings"). The
// defaults are upstream opendbc's (sunnypilot/opendbc), so a host on those names defines nothing.
// Type of FordBpCurvatureLimits.base: the host's curvature limit struct. The library reads only its
// max_curvature, curvature_to_can, frequency, max_curvature_error and curvature_error_min_speed.
#ifndef BP_HOST_CURVATURE_LIMITS
#define BP_HOST_CURVATURE_LIMITS CurvatureSteeringLimits
#endif
// The host's curvature state (desired_last, meas), the one its curvature RX hook fills.
#ifndef BP_HOST_CURVATURE_STATE
#define BP_HOST_CURVATURE_STATE curvature_state
#endif
// The host's real-time message-rate check, taking a BP_HOST_CURVATURE_LIMITS by value.
#ifndef BP_HOST_RT_CURVATURE_RATE_CHECK
#define BP_HOST_RT_CURVATURE_RATE_CHECK rt_curvature_rate_limit_check
#endif
// Whether lateral control is allowed: controls_allowed or the host's lateral-only engagement (MADS).
#ifndef BP_HOST_LAT_ALLOWED
#define BP_HOST_LAT_ALLOWED() (controls_allowed || controls_allowed_lateral)
#endif
// The second-speed cross-check upstream runs inside its curvature check. A host that runs it in its
// RX hook instead defines this as ((void)0).
#ifndef BP_HOST_SPEED_MISMATCH_CHECK
#define BP_HOST_SPEED_MISMATCH_CHECK() speed_mismatch_check((float)vehicle_speed_2.values[0] / VEHICLE_SPEED_FACTOR)
#endif
// BluePilot: curvature limits for the measured-table check. base holds upstream's fields
// (max_curvature, curvature_to_can, frequency, error band, ...); the rest are BluePilot's.
typedef struct {
BP_HOST_CURVATURE_LIMITS base;
// Explicit rate-of-change tables, mirrored from values_ext.py BP_ANGLE_LIMITS. Upstream derives
// the per-tick delta from the ISO lateral jerk limit alone, which is looser than Ford's EPS
// tolerates at low speed and tighter than it tolerates at high speed.
struct lookup_t curvature_rate_up_lookup;
struct lookup_t curvature_rate_down_lookup;
// Ford CAN (Q3) is NOT lateral-accel limited in safety -- the EPS already caps it, and applying
// the ISO cap here would clip commands the car accepts today. Ford CAN FD (Q4) has more torque
// available and IS limited.
bool limit_lateral_acceleration;
} FordBpCurvatureLimits;
// BluePilot: measured-table curvature rate-of-change + error-band check, used by
// ford_bp_curvature_cmd_checks below.
static inline bool ford_bp_curvature_rate_lookup_check(int desired_curvature, const FordBpCurvatureLimits *limits);
// BluePilot: curvature command checks for the BluePilot lateral (Ford only today, see the
// FORD_LIMITS macro in bluepilot_lateral/safety/ford.h). Upstream's steer_curvature_cmd_checks with
// the measured-table check in place of its ISO accel and jerk checks, and no value checks at
// curvature 0, the no-curvature-command sentinel (only the message-rate check and the gates).
static inline bool ford_bp_curvature_cmd_checks(int desired_curvature, bool steer_control_enabled,
const FordBpCurvatureLimits *limits);
@@ -1,43 +0,0 @@
#!/usr/bin/env bash
# BluePilot: 100% line coverage of the BluePilot safety headers (#53). Upstream's test.sh only measures
# files under <pkg>/safety/, and the headers live in <pkg>/bluepilot_lateral/safety/. <pkg> is the host's
# opendbc package, whatever it's named (opendbc, iqdbc): the one the library is mounted in.
set -e
DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" >/dev/null && pwd)"
ROOT="$(cd "$DIR/../../../.." && pwd)"
PKG="$(basename "$(cd "$DIR/../../.." && pwd)")"
cd "$ROOT/$PKG/safety/tests"
source "$ROOT/setup.sh"
# reset coverage data, then run upstream's safety tests. The BluePilot ones come in through the host's
# loader (test_bluepilot_lateral.py) where it has one; otherwise they run here on their own.
rm -f ./libsafety/*.gcda ./libsafety/*.gcno
SAFETY_COVERAGE=1 python -m unittest discover -s .
if [ ! -f test_bluepilot_lateral.py ]; then
SAFETY_COVERAGE=1 python -m unittest discover -s "$ROOT/$PKG/bluepilot_lateral/safety/tests" -t "$ROOT"
fi
if [ "$(uname)" = "Darwin" ]; then
GCOV_EXEC="llvm-cov gcov"
else
GCOV_EXEC="gcov"
fi
# Two reports: the library's safety/ford.h and the host's modes/ford.h share a file name, and one gcovr run
# over both can credit one's lines to the other. modes/ford.h is measured from <pkg>/safety, as the host's
# test.sh does; the second run deletes the coverage data.
if ! OUT="$(gcovr -r "$ROOT/$PKG/safety" --gcov-executable "$GCOV_EXEC" --fail-under-line=100 \
-f "$ROOT/$PKG/safety/modes/ford.h")"; then
echo -e "FAILED:\n$OUT"
exit 1
fi
echo "$OUT"
if ! OUT="$(gcovr -r "$ROOT" --gcov-executable "$GCOV_EXEC" -d --fail-under-line=100 \
-f "$ROOT/$PKG/bluepilot_lateral/safety/")"; then
echo -e "FAILED:\n$OUT"
exit 1
fi
echo "$OUT"
echo "SUCCESS: the BluePilot safety headers and modes/ford.h have 100% coverage!"
@@ -1,47 +0,0 @@
#!/usr/bin/env python3
"""BluePilot: run upstream's mutation.py on the BluePilot safety headers (#53).
Upstream's run only mutates code from files under <pkg>/safety/, and the BluePilot headers live in
the library (<pkg>/bluepilot_lateral/safety/). This points the same run at them; the killer tests
are the ones mutation.py already discovers in <pkg>/safety/tests/, the BluePilot ones through the
loader there (test_bluepilot_lateral.py). Same options as mutation.py. <pkg> is the host's opendbc
package, whatever it's named (opendbc, iqdbc): the one the library is mounted in."""
import importlib
import sys
from pathlib import Path
PKG = Path(__file__).resolve().parents[3].name
mutation = importlib.import_module(f"{PKG}.safety.tests.mutation")
mutation.SAFETY_DIR = mutation.ROOT / PKG / "bluepilot_lateral" / "safety"
# Equivalent mutants: no test can kill them, so they are skipped (mutation.py keeps its own list inside
# main()). ford.h's +-0.02 range check in ford_lmc_checks is the same +-1000 CAN cap as lateral.h's
# max_curvature check, which blocks every frame it would (its steering-off and controls-not-allowed
# checks cover the rest), and the range check writes no state (only ford_bp_curvature_cmd_checks
# resets desired_last). It stays as the backstop if a platform's max_curvature ever differs, and a
# test can reach it then.
KNOWN_SURVIVORS = {
(f"{PKG}/bluepilot_lateral/safety/ford.h", 197, "|=", "&="),
}
_enumerate_sites = mutation.enumerate_sites
def key(site):
return str(site.origin_file.relative_to(mutation.ROOT)), site.origin_line, site.original_op, site.mutated_op
def enumerate_sites(input_source, preprocessed_file):
sites, counts, build_incompatible_ids, source = _enumerate_sites(input_source, preprocessed_file)
skipped = [s for s in sites if key(s) in KNOWN_SURVIVORS]
assert len(skipped) == len(KNOWN_SURVIVORS), f"an equivalent mutant moved or is gone: {sorted(KNOWN_SURVIVORS - {key(s) for s in skipped})}"
for s in skipped:
print(f"skipping equivalent mutant: {key(s)[0]}:{s.origin_line} [{s.mutator}] {s.original_op}->{s.mutated_op}", flush=True)
return [s for s in sites if key(s) not in KNOWN_SURVIVORS], counts, build_incompatible_ids, source
mutation.enumerate_sites = enumerate_sites # main() looks it up by name
if __name__ == "__main__":
sys.exit(mutation.main())
@@ -1,268 +0,0 @@
"""
BluePilot: shared harness for the Ford 4-signal lateral safety tests.
Not a test module (no test_ prefix). Provides:
* BPFordLateralModel: a Python mirror of the BluePilot curvature checks in
opendbc/bluepilot_lateral/safety/lateral.h (ford_bp_curvature_rate_lookup_check) and the lateral
acceleration cap, computed with the same float32 arithmetic and rounding as the C, so the
tests can assert exact CAN-unit boundaries on both x86 and ARM runners.
* BPFordTestCase: unittest base that borrows upstream's Ford test class for its message
builders (composition, so upstream's tests are not inherited) and sets the BP_LATERAL safety
param bit before ford_init.
"""
import re
import unittest
from pathlib import Path
import numpy as np
from ....car.structs import CarParams
from ....car.ford.fordcan import CanBus
from ....car.ford.values import FordSafetyFlags
from ...can import fordcan_ext
from ...core.values_ext import FordSafetyFlagsSP
from ....safety.tests.libsafety import libsafety_py
from ....safety.tests.common import CANPackerSafety
from ....safety.tests import test_ford # module import keeps its test classes out of discovery here
from ...tests import host
f32 = np.float32
def c_int(v) -> int:
"""C (int) cast: truncation toward zero."""
return int(np.trunc(float(v)))
# --- constants mirrored from the C (opendbc/safety/modes/ford.h, opendbc/bluepilot_lateral/safety/*.h, lateral.h) ---
CURVATURE_TO_CAN = 50000.0 # FORD_LIMITS .curvature_to_can
FORD_CURVATURE_MAX = 0.02 # rad/m, FORD_CURVATURE_MAX in ford_declarations.h
MAX_CURVATURE_CAN = c_int(f32(FORD_CURVATURE_MAX) * f32(CURVATURE_TO_CAN)) # FORD_LIMITS .max_curvature, 1000
MAX_CURVATURE_ERROR_CAN = 100 # FORD_LIMITS(_, 100)
MAX_CURVATURE_ERROR_CAN_PINION = 150 # FORD_BP_STEERING_LIMITS_PINION / FORD_CANFD_STEERING_LIMITS_PINION
CURVATURE_ERROR_MIN_SPEED = 10.0 # m/s
VEHICLE_SPEED_FACTOR = 1000.0
RATE_LOOKUP_X = (5., 16., 25.) # m/s, FORD_LIMITS curvature_rate_{up,down}_lookup
RATE_LOOKUP_UP_Y = (0.0025, 0.0014, 0.00018) # rad/m per frame, curvature_rate_up_lookup
RATE_LOOKUP_DOWN_Y = (0.002525, 0.001414, 0.0001818) # curvature_rate_down_lookup: 1% looser than up (#20)
ISO_LATERAL_ACCEL = 3.0
EARTH_G = 9.81
AVERAGE_ROAD_ROLL = 0.06
BP_MAX_LATERAL_ACCEL = float(f32(ISO_LATERAL_ACCEL) - f32(EARTH_G) * f32(AVERAGE_ROAD_ROLL)) # lateral.h, ~2.41 m/s^2
PATH_ANGLE_TO_CAN = 2000.0 # FORD_PATH_ANGLE_LIMITS .angle_deg_to_can (1 / 5e-4 rad)
FORD_PATH_ANGLE_MAX = 0.25 # rad, curvature mode
FORD_DBC_PATH_ANGLE_MIN = -0.5 # rad, angle mode: the DBC's own range
FORD_DBC_PATH_ANGLE_MAX = 0.5235
PATH_ANGLE_MAX_CAN = c_int(f32(FORD_PATH_ANGLE_MAX) * f32(PATH_ANGLE_TO_CAN)) # 500
PATH_ANGLE_DBC_MIN_CAN = c_int(f32(FORD_DBC_PATH_ANGLE_MIN) * f32(PATH_ANGLE_TO_CAN)) # -1000
PATH_ANGLE_DBC_MAX_CAN = c_int(f32(FORD_DBC_PATH_ANGLE_MAX) * f32(PATH_ANGLE_TO_CAN)) # 1047, truncated like the C's (int) cast
PATH_ANGLE_LOOKUP_X = (10., 15., 25.)
PATH_ANGLE_LOOKUP_Y = (0.0561, 0.04335, 0.00918) # rad per frame
PATH_OFFSET_TO_CAN = 100.0 # FORD_PATH_OFFSET_LIMITS .angle_deg_to_can (1 / 0.01 m)
FORD_PATH_OFFSET_MAX = 1.0 # m
PATH_OFFSET_MAX_CAN = c_int(f32(FORD_PATH_OFFSET_MAX) * f32(PATH_OFFSET_TO_CAN)) # 100
PATH_OFFSET_LOOKUP_X = (5., 15., 25.)
PATH_OFFSET_LOOKUP_Y = (0.05, 0.025, 0.01) # m per frame
CURVATURE_RATE_TO_CAN_CANFD = 1000000.0 # LatCtlCrv_NoRate2_Actl wire resolution, 1e-6 1/m^2
CURVATURE_RATE_TO_CAN_CAN = 4000000.0 # LatCtlCurv_NoRate_Actl wire resolution, 2.5e-7 1/m^2
LATCTL_CURVATURE_SIGNAL_MAX = 0.02094 # rad/m, LatCtlCurv_No_Actl range [-0.02|0.02094] in the DBC
CURVATURE_SIGNAL_MAX_CAN = c_int(f32(LATCTL_CURVATURE_SIGNAL_MAX) * f32(CURVATURE_TO_CAN)) # 1047: the packer cannot go further
FORMER_LATCH_WINDOW_FRAMES = 70 # > the 60 frames the removed reset-bypass latch covered (#9)
SMALL_ANGLE = 0.01 # rad: a small non-zero path_angle; probes hold it constant, so its ROC never decides
def c_interpolate(xs, ys, x) -> np.float32:
"""safety_interpolate() from opendbc/safety/helpers.h, in float32."""
x = f32(x)
xs = [f32(v) for v in xs]
ys = [f32(v) for v in ys]
ret = ys[-1]
if x <= xs[0]:
ret = ys[0]
else:
for i in range(len(xs) - 1):
if x < xs[i + 1]:
x0, y0 = xs[i], ys[i]
dx = f32(max(xs[i + 1] - x0, f32(0.0001)))
dy = f32(ys[i + 1] - y0)
ret = f32(f32(dy * f32(x - x0)) / dx) + y0
break
return f32(ret)
def c_fudged_speed(speed_ms: float, offset: float) -> np.float32:
"""(vehicle_speed.x / VEHICLE_SPEED_FACTOR) + offset, as the C computes it: the sample is an
int in mm/s, the division and the offset happen in double, and the result is rounded to
float once when passed to safety_interpolate. speed_ms comes from libsafety's getters,
which are the sample / 1000 rounded to float32; the integer is recovered exactly."""
sample = round(float(speed_ms) * VEHICLE_SPEED_FACTOR)
return f32(sample / VEHICLE_SPEED_FACTOR + offset)
class BPFordLateralModel:
"""Mirror of the BP curvature path in ford_bp_curvature_cmd_checks + ford_bp_curvature_rate_lookup_check.
Speeds are what the C sees: vehicle_speed.min / max / values[0] in m/s (read back from
libsafety after the rx messages so packer rounding is included).
"""
def __init__(self, canfd: bool, max_curvature_error: int = MAX_CURVATURE_ERROR_CAN):
self.limit_lateral_accel = canfd # FORD_LIMITS(true, …) only for CAN FD
self.max_curvature_error = max_curvature_error
@staticmethod
def rate_delta(speed_min: float, up: bool = True) -> int:
# (safety_interpolate(lookup, (vehicle_speed.min / F) - 1.) * curvature_to_can) + 1. -> int
fudged = c_fudged_speed(speed_min, -1.0)
table = RATE_LOOKUP_UP_Y if up else RATE_LOOKUP_DOWN_Y
return c_int(float(f32(c_interpolate(RATE_LOOKUP_X, table, fudged) * f32(CURVATURE_TO_CAN))) + 1.0)
@staticmethod
def rate_delta_relaxed(speed_max: float, up: bool = True) -> int:
fudged = c_fudged_speed(speed_max, 1.0)
table = RATE_LOOKUP_UP_Y if up else RATE_LOOKUP_DOWN_Y
return c_int(float(f32(c_interpolate(RATE_LOOKUP_X, table, fudged) * f32(CURVATURE_TO_CAN))) - 1.0)
@staticmethod
def accel_cap(speed_min: float) -> int:
# BP_MAX_LATERAL_ACCEL / (fudged_speed^2) * curvature_to_can + 1, fudged = max(v.min - 1, 1)
fudged = f32(max(float(c_fudged_speed(speed_min, -1.0)), 1.0))
max_curv = f32(f32(BP_MAX_LATERAL_ACCEL) / f32(fudged * fudged))
return c_int(float(f32(max_curv * f32(CURVATURE_TO_CAN))) + 1.0)
def bounds(self, desired_last: int, meas_min: int, meas_max: int,
speed_min: float, speed_max: float, speed_now: float) -> tuple[int, int]:
"""(lowest, highest) allowed desired curvature in CAN units for the next frame."""
delta_up = self.rate_delta(speed_min, up=True)
delta_down = self.rate_delta(speed_min, up=False)
highest = desired_last + (delta_up if desired_last > 0 else delta_down)
lowest = desired_last - (delta_down if desired_last >= 0 else delta_up)
if self.max_curvature_error and speed_now > CURVATURE_ERROR_MIN_SPEED:
relaxed_up = self.rate_delta_relaxed(speed_max, up=True)
relaxed_down = self.rate_delta_relaxed(speed_max, up=False)
lowest_err = meas_min - self.max_curvature_error - 1
highest_err = meas_max + self.max_curvature_error + 1
if desired_last > highest_err:
delta = relaxed_down if desired_last >= 0 else relaxed_up
highest = max(desired_last - delta, highest_err)
elif desired_last < lowest_err:
delta = relaxed_down if desired_last <= 0 else relaxed_up
lowest = min(desired_last + delta, lowest_err)
else:
highest = min(highest, highest_err)
lowest = max(lowest, lowest_err)
lowest = max(-MAX_CURVATURE_CAN, min(MAX_CURVATURE_CAN, lowest))
highest = max(-MAX_CURVATURE_CAN, min(MAX_CURVATURE_CAN, highest))
return lowest, highest
def cap(self, speed_min: float) -> int:
"""The largest |curvature| the checks accept at this speed: the lateral-accel cap on CAN FD, the
0.02 hard limit otherwise (FORD_LIMITS .limit_lateral_acceleration)."""
return min(self.accel_cap(speed_min), MAX_CURVATURE_CAN) if self.limit_lateral_accel else MAX_CURVATURE_CAN
def allowed(self, desired: int, desired_last: int, meas_min: int, meas_max: int,
speed_min: float, speed_max: float, speed_now: float) -> bool:
"""Whether a non-zero desired curvature passes the BP curvature checks (controls allowed, steer enabled)."""
if abs(desired) > MAX_CURVATURE_CAN:
return False
lowest, highest = self.bounds(desired_last, meas_min, meas_max, speed_min, speed_max, speed_now)
if desired > highest or desired < lowest:
return False
if self.limit_lateral_accel:
cap = self.accel_cap(speed_min)
if desired > cap or desired < -cap:
return False
return True
_NUM = r"[-+0-9.eE]+"
_GEOMETRY_ROW = re.compile(rf"\{{\.slip_factor = (?P<slip>{_NUM})f, \.steer_ratio = (?P<sr>{_NUM})f, \.wheelbase = (?P<wb>{_NUM})f\}},\s*// (?P<idx>\d+):")
def pinion_geometry_table() -> dict[int, tuple[float, float, float]]:
"""ford_pinion_geometry from opendbc/bluepilot_lateral/safety/ford.h as {index: (slip_factor, steer_ratio,
wheelbase)}. Read from source: libsafety exposes no getters for it and adding some would touch
upstream's harness."""
bp = Path(__file__).resolve().parents[1]
src = (bp / "ford.h").read_text()
body = src[src.index("ford_pinion_geometry[FORD_PINION_GEOMETRY_ROWS] = {"):]
body = body[:body.index("};")]
matches = list(_GEOMETRY_ROW.finditer(body))
# every initializer must parse (a row in a spelling the regex misses would otherwise vanish),
# the comment index must be the row's position, and the count must be the declared size
assert len(matches) == body.count("{.slip_factor"), "a geometry row did not parse"
rows = {}
for pos, m in enumerate(matches):
assert int(m["idx"]) == pos, f"row {pos} is labeled {m['idx']}"
rows[pos] = (float(m["slip"]), float(m["sr"]), float(m["wb"]))
declared = re.search(r"#define FORD_PINION_GEOMETRY_ROWS (\d+)U", (bp / "ford_declarations.h").read_text())
assert declared and int(declared[1]) == len(rows), "FORD_PINION_GEOMETRY_ROWS does not match the table"
return rows
def angle_roc_delta(xs, ys, scale: float, speed_min: float) -> int:
"""path_angle / path_offset per-frame ROC: interpolate(lookup, v.min - 1) * scale + 1."""
fudged = c_fudged_speed(speed_min, -1.0)
return c_int(float(f32(c_interpolate(xs, ys, fudged) * f32(scale))) + 1.0)
class BPFordTestCase(unittest.TestCase):
"""Base for BluePilot Ford lateral tests. Subclasses set CANFD and may set PARAM_SP."""
CANFD = True
PARAM_SP = FordSafetyFlagsSP.BP_LATERAL
def setUp(self):
cls = test_ford.TestFordCANFDStockSafety if self.CANFD else test_ford.TestFordLongitudinalSafety
self.stock = cls("test_steer_allowed") # upstream's Ford TestCase, for its message builders only
self.stock.packer = CANPackerSafety("ford_lincoln_base_pt")
self.stock.safety = libsafety_py.libsafety
self.safety = self.stock.safety
self.reinit()
self.safety.init_tests()
self.safety.set_controls_allowed(True)
self.model = BPFordLateralModel(self.CANFD)
self.set_meas(0, 15.0)
def tearDown(self):
# stock classes in the same process must not inherit the bit
host.set_safety_param(self.safety, 0)
super().tearDown() # the host's own resets (IQ.Pilot's AOL state)
def reinit(self):
"""A safety-mode init with the BP bit set (ford_init reads the bit)."""
host.set_safety_param(self.safety, self.PARAM_SP)
self.safety.set_safety_hooks(CarParams.SafetyModel.ford, host.ford_param(FordSafetyFlags.CANFD if self.CANFD else 0, self.PARAM_SP))
# --- wrappers over upstream's builders ---
def tx(self, msg) -> bool:
return self.stock._tx(msg)
def rx(self, msg) -> bool:
return self.stock._rx(msg)
def lat(self, enabled: bool, path_offset=0.0, path_angle=0.0, curvature=0.0, curvature_rate=0.0, increment_timer=True):
return self.stock._lat_ctl_msg(enabled, path_offset, path_angle, curvature, curvature_rate, increment_timer=increment_timer)
def set_meas(self, curvature: float, speed: float):
self.stock._reset_curvature_measurement(curvature, speed)
def set_prev_curvature_can(self, can: int):
self.safety.set_desired_curvature_last(can)
def speeds(self) -> tuple[float, float]:
return float(self.safety.get_vehicle_speed_min()), float(self.safety.get_vehicle_speed_max())
def meas(self) -> tuple[int, int]:
return int(self.safety.get_curvature_meas_min()), int(self.safety.get_curvature_meas_max())
def lka_bp_status_msg(self, angle_mode_engaged: bool, shadow_curvature: float):
"""Lane_Assist_Data1 with BluePilot's angle-mode side channel (can/LANE_ASSIST_DATA1.md), built by
the real packer, so every angle-mode test runs Python's packing through the panda's decode."""
addr, dat, bus = fordcan_ext.create_lka_msg(self.stock.packer, CanBus(fingerprint={}), False, None, angle_mode_engaged,
shadow_curvature)
return libsafety_py.make_CANPacket(addr, bus, bytes(dat))
@@ -1,58 +0,0 @@
#!/usr/bin/env python3
"""
BluePilot: the BP_LATERAL safety-param bit selects which Ford lateral checks the panda runs.
This pins the switch itself, not the BluePilot limits: with the bit set a modest non-zero
path_angle is accepted, and with it clear (upstream's stock checks) the same frame is rejected.
The BluePilot limits are covered separately.
"""
import unittest
from ....car.structs import CarParams
from ....car.ford.values import FordSafetyFlags
from ...core.values_ext import FordSafetyFlagsSP
from ....safety.tests.libsafety import libsafety_py
from ....safety.tests.common import CANPackerSafety
from ....safety.tests import test_ford # module import: keeps its test classes out of this module's discovery
from ...tests import host
SPEED = 15.0 # m/s, above the curvature-error gate, inside the path_angle ROC table
SMALL_PATH_ANGLE = 0.01 # rad, well inside the per-call ROC at this speed (~0.043)
LARGE_PATH_ANGLE = 0.30 # rad, outside both the ROC step and the ±0.25 curvature-mode range
class TestFordBPLateralBit(unittest.TestCase):
"""Uses upstream's CAN FD stock test class only for its message helpers; its tests are not inherited."""
def setUp(self):
self.h = test_ford.TestFordCANFDStockSafety("test_steer_allowed")
self.h.packer = CANPackerSafety("ford_lincoln_base_pt")
self.h.safety = libsafety_py.libsafety
def tearDown(self):
host.set_safety_param(self.h.safety, 0)
super().tearDown()
def _init(self, param_sp: int):
h = self.h
host.set_safety_param(h.safety, param_sp)
h.safety.set_safety_hooks(CarParams.SafetyModel.ford, host.ford_param(FordSafetyFlags.CANFD, param_sp))
h.safety.init_tests()
h.safety.set_controls_allowed(True)
h._reset_curvature_measurement(0, SPEED)
h._set_prev_desired_angle(0.001)
def test_bit_set_runs_bluepilot_checks(self):
self._init(FordSafetyFlagsSP.BP_LATERAL)
self.assertTrue(self.h._tx(self.h._lat_ctl_msg(True, 0, SMALL_PATH_ANGLE, 0.001, 0)))
self.assertFalse(self.h._tx(self.h._lat_ctl_msg(True, 0, LARGE_PATH_ANGLE, 0.001, 0)))
def test_bit_clear_runs_stock_checks(self):
self._init(0)
# upstream: any non-zero path_angle is a violation
self.assertFalse(self.h._tx(self.h._lat_ctl_msg(True, 0, SMALL_PATH_ANGLE, 0.001, 0)))
self.assertTrue(self.h._tx(self.h._lat_ctl_msg(True, 0, 0, 0.001, 0)))
if __name__ == "__main__":
unittest.main()
@@ -1,99 +0,0 @@
#!/usr/bin/env python3
"""
BluePilot Ford lateral, angle mode: the shadow-curvature plausibility check.
In angle mode the LatCtl curvature signal is held at 0 and the command rides on path_angle.
Lane_Assist_Data1 carries a side channel (angle mode engaged, and the curvature the controller
would have commanded, "shadow curvature"; layout in opendbc/bluepilot_lateral/can/LANE_ASSIST_DATA1.md)
that the panda checks against the yaw-measured curvature with the same error window as curvature mode
(ford_shadow_curvature_error_check, ford.h). Ported from BluePilot's earlier vendored tests.
"""
import unittest
from .ford_bluepilot_common import (
BPFordTestCase, SMALL_ANGLE, FORMER_LATCH_WINDOW_FRAMES, CURVATURE_TO_CAN, MAX_CURVATURE_ERROR_CAN, CURVATURE_ERROR_MIN_SPEED,
)
class TestFordBPAngleModeCANFD(BPFordTestCase):
CANFD = True
def _angle_frame(self) -> bool:
return self.tx(self.lat(True, 0, SMALL_ANGLE, 0, 0))
def test_shadow_curvature_error_window(self):
"""Above the speed gate the shadow curvature must be within max_curvature_error of measured;
below it the check is off. Covers ford_shadow_curvature_error_check and its call site."""
measured_can = 250 # 0.005 rad/m
for speed in (CURVATURE_ERROR_MIN_SPEED - 1, CURVATURE_ERROR_MIN_SPEED + 1, 20.0):
enforced = speed > CURVATURE_ERROR_MIN_SPEED
self.set_meas(measured_can / CURVATURE_TO_CAN, speed)
m_min, m_max = self.meas()
hi_edge = m_max + MAX_CURVATURE_ERROR_CAN + 1 # highest_allowed in the C
lo_edge = m_min - MAX_CURVATURE_ERROR_CAN - 1
# shadow arrives as int16 at 1e-6 rad/m; the C scales by 0.05 to CAN units and truncates,
# so pick shadow values that land exactly on the CAN-unit boundaries
for shadow_can, expect in ((m_max, True), (hi_edge, True), (hi_edge + 1, not enforced),
(lo_edge, True), (lo_edge - 1, not enforced), (0, not enforced)):
self.tx(self.lka_bp_status_msg(True, shadow_can / CURVATURE_TO_CAN))
with self.subTest(speed=speed, shadow_can=shadow_can):
self.assertEqual(expect, self._angle_frame())
def test_shadow_curvature_has_no_rate_limit(self):
"""Only the path_angle ROC applies in angle mode: a large frame-to-frame jump in the shadow
curvature that stays inside the window of a correspondingly moved measurement must pass."""
speed = CURVATURE_ERROR_MIN_SPEED + 1
for curvature in (0.015, -0.015, 0.018, -0.018, 0.001, -0.019):
self.set_meas(curvature, speed)
self.tx(self.lka_bp_status_msg(True, curvature))
with self.subTest(curvature=curvature):
self.assertTrue(self._angle_frame())
def test_flag_clear_skips_shadow_check(self):
"""Without the angle-mode bit a curvature-0 frame is not checked against the shadow value."""
speed = CURVATURE_ERROR_MIN_SPEED + 5
self.set_meas(0.005, speed)
self.tx(self.lka_bp_status_msg(False, 0.02)) # would fail the window if it were applied
self.assertTrue(self._angle_frame())
def test_curvature_mode_unaffected_by_angle_mode_flag(self):
"""A real (non-zero) curvature command is curvature mode by its own content; the flag and the
shadow value must not gate it either way."""
speed = CURVATURE_ERROR_MIN_SPEED + 5
curvature_can = 500
self.set_meas(curvature_can / CURVATURE_TO_CAN, speed)
for flag in (True, False):
self.tx(self.lka_bp_status_msg(flag, 0.02))
self.set_prev_curvature_can(curvature_can)
with self.subTest(flag=flag):
self.assertTrue(self.tx(self.lat(True, 0, 0, curvature_can / CURVATURE_TO_CAN, 0)))
def test_shadow_out_of_window_blocks_while_enabled(self):
"""An out-of-window shadow value blocks the enabled frame; the disabled all-zero frame (mode 0)
is not checked against it."""
speed = CURVATURE_ERROR_MIN_SPEED + 5
self.set_meas(0.005, speed)
self.tx(self.lka_bp_status_msg(True, 0.02))
self.assertFalse(self._angle_frame())
self.assertTrue(self.tx(self.lat(False, 0, 0, 0, 0)))
def test_mode0_frame_leaves_shadow_check_active(self):
"""Angle mode's human-turn override sends mode 0 with every signal zero. The frames after it
are checked: an out-of-window shadow curvature blocks on every frame of the 60-frame window
the removed bypass latch used to cover (#9)."""
speed = CURVATURE_ERROR_MIN_SPEED + 5
self.set_meas(0.005, speed)
self.tx(self.lka_bp_status_msg(True, 0.005))
self.assertTrue(self.tx(self.lat(False, 0, 0, 0, 0)))
self.tx(self.lka_bp_status_msg(True, 0.02))
for frame in range(FORMER_LATCH_WINDOW_FRAMES):
with self.subTest(frame=frame):
self.assertFalse(self._angle_frame())
class TestFordBPAngleModeCAN(TestFordBPAngleModeCANFD):
CANFD = False
if __name__ == "__main__":
unittest.main()
@@ -1,463 +0,0 @@
#!/usr/bin/env python3
"""
BluePilot Ford lateral: the 4-signal limits with the BP_LATERAL bit set.
Every expectation comes from ford_bluepilot_common.BPFordLateralModel, a float32 mirror of the
C, so boundaries are asserted at the exact CAN unit on both x86 and ARM.
"""
import random
import unittest
from ....safety.tests import common
from ....can.dbc import DBC
from .ford_bluepilot_common import (
BPFordTestCase, angle_roc_delta, SMALL_ANGLE, FORMER_LATCH_WINDOW_FRAMES, CURVATURE_SIGNAL_MAX_CAN,
CURVATURE_TO_CAN, MAX_CURVATURE_CAN, MAX_CURVATURE_ERROR_CAN, CURVATURE_ERROR_MIN_SPEED,
PATH_ANGLE_TO_CAN, PATH_ANGLE_MAX_CAN, PATH_ANGLE_DBC_MIN_CAN, PATH_ANGLE_DBC_MAX_CAN,
PATH_ANGLE_LOOKUP_X, PATH_ANGLE_LOOKUP_Y,
PATH_OFFSET_TO_CAN, PATH_OFFSET_MAX_CAN, PATH_OFFSET_LOOKUP_X, PATH_OFFSET_LOOKUP_Y,
CURVATURE_RATE_TO_CAN_CANFD, CURVATURE_RATE_TO_CAN_CAN,
)
from ...tests import host
# speeds chosen to hit both sides of the error-band gate (10 m/s) and every segment of the
# {5, 16, 25} rate table, plus its clamped ends
SPEEDS = (3.0, 5.0, 8.0, 10.5, 12.0, 16.0, 20.0, 25.0, 30.0)
class TestFordBPLimitsCANFD(BPFordTestCase):
CANFD = True
def _probe(self, desired_can: int, last_can: int) -> bool:
self.set_prev_curvature_can(last_can)
return self.tx(self.lat(True, 0, SMALL_ANGLE, desired_can / CURVATURE_TO_CAN, 0))
def _assert_matches_model(self, last_can: int, probes):
v_min, v_max = self.speeds()
m_min, m_max = self.meas()
for desired in probes:
if desired == 0 or abs(desired) > CURVATURE_SIGNAL_MAX_CAN: # 0 skips the value checks the model mirrors
continue
expected = self.model.allowed(desired, last_can, m_min, m_max, v_min, v_max, v_max)
with self.subTest(speed=v_max, meas=(m_min, m_max), last=last_can, desired=desired):
self.assertEqual(expected, self._probe(desired, last_can))
def test_curvature_rate_lookup_boundaries(self):
"""Per-frame delta from the {5,16,25} m/s table (ford_bp_curvature_rate_lookup_check), both
directions, both signs, exact boundary: the speed fudge and the delta arithmetic."""
for speed in SPEEDS:
self.set_meas(0, speed)
v_min, v_max = self.speeds()
delta = self.model.rate_delta(v_min)
for last in (0, 40, -40, 250, -250):
lowest, highest = self.model.bounds(last, *self.meas(), v_min, v_max, v_max)
self._assert_matches_model(last, (highest - 1, highest, highest + 1, lowest - 1, lowest, lowest + 1,
last + delta, last + delta + 1, last - delta, last - delta - 1))
def test_curvature_error_band_convergence(self):
"""Above 10 m/s the command must stay within max_curvature_error of measured; when the last
command is already outside the band it must move back toward it by at least the relaxed
delta, and may not move further away. Below 10 m/s the band is off (the relaxed branches of
ford_bp_curvature_rate_lookup_check). Seen in the car: a 4-frame block at 26 mph with the driver
steering harder than the command, sitting exactly on this window's edge (#12)."""
# measured both signs, and last commands on both sides of zero, so both relaxed branches run
# with last commands of either sign. The C picks the up or down table by that sign, and the
# down table is 1% looser (#20), so each relaxed probe below uses the table the C picks.
for meas_can in (200, -200, 600, -600):
for speed in (8.0, 12.0, 16.0, 20.0):
self.set_meas(meas_can / CURVATURE_TO_CAN, speed)
v_min, v_max = self.speeds()
m_min, m_max = self.meas()
band_on = v_max > CURVATURE_ERROR_MIN_SPEED
delta = self.model.rate_delta(v_min)
lowest_err = m_min - MAX_CURVATURE_ERROR_CAN - 1
highest_err = m_max + MAX_CURVATURE_ERROR_CAN + 1
cap = self.model.cap(v_min) # the explicit asserts below stay under it
# last command below the band (on either side of zero): must climb toward it
for last in (lowest_err - 150, 0, -1, 1):
if last >= lowest_err:
continue
relaxed = self.model.rate_delta_relaxed(v_max, up=last > 0) # climbing: down table while last <= 0
self._assert_matches_model(last, (last + relaxed - 1, last + relaxed, last + delta, last + delta + 1,
last - 1, lowest_err))
if band_on:
ctx = f"meas={meas_can} speed={speed} last={last} relaxed={relaxed} band=({lowest_err},{highest_err})"
self.assertFalse(self._probe(last + relaxed - 1, last), "must move toward the band " + ctx)
if abs(min(last + relaxed, lowest_err)) <= cap:
self.assertTrue(self._probe(min(last + relaxed, lowest_err), last), ctx)
if last - 1 != 0: # curvature 0 is angle mode's sentinel and skips the curvature checks
self.assertFalse(self._probe(last - 1, last), "may not move away from the band " + ctx)
# last command above the band (on either side of zero): must descend toward it
for last in (highest_err + 150, 0, -1, 1):
if last <= highest_err:
continue
relaxed = self.model.rate_delta_relaxed(v_max, up=last < 0) # descending: down table while last >= 0
self._assert_matches_model(last, (last - relaxed + 1, last - relaxed, last - delta, last - delta - 1,
last + 1, highest_err))
if band_on:
ctx = f"meas={meas_can} speed={speed} last={last} relaxed={relaxed} band=({lowest_err},{highest_err})"
self.assertFalse(self._probe(last - relaxed + 1, last), "must move toward the band " + ctx)
if abs(max(last - relaxed, highest_err)) <= cap:
self.assertTrue(self._probe(max(last - relaxed, highest_err), last), ctx)
if last + 1 != 0:
self.assertFalse(self._probe(last + 1, last), "may not move away from the band " + ctx)
# last command inside the band: may not leave it
last = highest_err - 1
self._assert_matches_model(last, (highest_err, highest_err + 1, lowest_err, lowest_err - 1))
if band_on and delta > 1 and abs(highest_err) <= cap:
self.assertTrue(self._probe(highest_err, last))
self.assertFalse(self._probe(highest_err + 1, last), "inside the band, may not command outside it")
def test_lateral_accel_cap(self):
"""CAN FD only: |curvature| <= (ISO_LATERAL_ACCEL - g*roll) / v^2, with the speed fudged down 1 m/s."""
for speed in (15.0, 20.0, 25.0, 30.0):
self.set_meas(0, speed)
v_min, _ = self.speeds()
cap = self.model.accel_cap(v_min)
self.assertLess(cap, MAX_CURVATURE_CAN, "cap only means something below the 0.02 hard limit")
for sign in (1, -1):
# measured curvature at the cap so the error band and rate limits allow it; last at the cap too
self.set_meas(sign * cap / CURVATURE_TO_CAN, speed)
with self.subTest(speed=speed, sign=sign):
self.assertTrue(self._probe(sign * cap, sign * cap))
self.assertFalse(self._probe(sign * (cap + 1), sign * cap))
def test_max_curvature_hard_limit(self):
"""+-0.02 rad/m (1000 CAN) regardless of speed. At 3 m/s the accel cap and the band are off. Only the
positive side has an over-cap frame: LatCtlCurv_No_Actl is 11 bits unsigned with offset -0.02, so its
minimum is exactly -0.02, and -1001 CAN units can't be sent (it wraps to +1047 on the wire)."""
self.set_meas(0.02, 3.0)
for sign in (1, -1):
self.assertTrue(self._probe(sign * MAX_CURVATURE_CAN, sign * MAX_CURVATURE_CAN))
self.assertFalse(self._probe(MAX_CURVATURE_CAN + 1, MAX_CURVATURE_CAN))
name = "LateralMotionControl2" if self.CANFD else "LateralMotionControl"
sig = next(m for m in DBC("ford_lincoln_base_pt").msgs.values() if m.name == name).sigs["LatCtlCurv_No_Actl"]
self.assertFalse(sig.is_signed)
self.assertEqual(round(sig.offset * CURVATURE_TO_CAN), -MAX_CURVATURE_CAN)
def test_over_cap_frame_resets_last(self):
"""A frame past the 0.02 cap resets desired_last to 0 (ford_bp_curvature_cmd_checks' own cap), so
the next frame at the cap is a jump from 0 past the rate limit. ford_lmc_checks' range check blocks
the over-cap frame either way; only the cap in ford_bp_curvature_cmd_checks resets. At 5 m/s the
band is off and the CAN FD accel cap is far above 0.02. Positive only: the signal's minimum is
-0.02 exactly (11 bits unsigned, offset -0.02), so -1001 wraps to +1047 on the wire."""
self.set_meas(0.02, 5.0)
self.assertLess(self.model.rate_delta(self.speeds()[0]), MAX_CURVATURE_CAN)
self.assertFalse(self._probe(MAX_CURVATURE_CAN + 1, MAX_CURVATURE_CAN))
self.assertFalse(self.tx(self.lat(True, 0, SMALL_ANGLE, MAX_CURVATURE_CAN / CURVATURE_TO_CAN, 0)))
def test_signals_zero_when_steer_disabled(self):
"""With LatCtl_D2_Rq = 0 every signal must be zero (path_angle/path_offset_cmd_checks, the
curvature-rate check and ford_bp_curvature_cmd_checks), each on its own and in combination."""
self.set_meas(0, 15.0)
self.assertFalse(self.tx(self.lat(False, 0.1, 0, 0, 0)))
self.assertFalse(self.tx(self.lat(False, 0, 0, 0, 0.0001)))
self.assertFalse(self.tx(self.lat(False, 0, 0.01, 0, 0)))
self.assertFalse(self.tx(self.lat(False, 0.1, 0.01, 0, 0)))
self.assertFalse(self.tx(self.lat(False, 0, 0.01, 0, 0.0001)))
self.assertFalse(self.tx(self.lat(False, 0, 0, 0.001, 0)))
self.assertFalse(self.tx(self.lat(False, 0.1, 0, 0.001, 0)))
self.assertFalse(self.tx(self.lat(False, 0, 0, 0.001, 0.0001)))
# one CAN unit of curvature: the curvature-must-be-0 check is the only one that blocks it
for sign in (1, -1):
self.assertFalse(self.tx(self.lat(False, 0, 0, sign / CURVATURE_TO_CAN, 0)))
# the all-zero disabled frame is the one thing allowed
self.assertTrue(self.tx(self.lat(False, 0, 0, 0, 0)))
def test_controls_not_allowed_blocks_steering(self):
"""steer enabled with controls not allowed is blocked whatever the signals carry: a real
curvature command (ford_bp_curvature_cmd_checks), in curvature mode and with the angle-mode
flag set. Upstream's test_steer_allowed asserts this for the stock path; this is the BP path."""
self.set_meas(0, 15.0)
for angle_mode in (False, True):
self.tx(self.lka_bp_status_msg(angle_mode, 0.0))
self.safety.set_controls_allowed(True)
self.assertTrue(self._probe(20, 10))
self.safety.set_controls_allowed(False)
host.set_controls_allowed_lat(self.safety, False)
with self.subTest(angle_mode=angle_mode):
self.assertFalse(self._probe(20, 10))
self.assertFalse(self.tx(self.lat(True, 0, SMALL_ANGLE, 0, 0)))
self.safety.set_controls_allowed(True)
self.tx(self.lka_bp_status_msg(False, 0.0))
def test_newest_speed_sample_gates_the_band(self):
"""The error band switches on vehicle_speed.values[0], the newest sample, not the window's
min or max, and only strictly above 10 m/s. Six samples at 9 m/s then one at 11: band on;
the reverse: band off; a newest sample of exactly 10.0: band off."""
meas_can = 200
last = meas_can + MAX_CURVATURE_ERROR_CAN # inside the band, so only the band decides
below, above, gate = CURVATURE_ERROR_MIN_SPEED - 1, CURVATURE_ERROR_MIN_SPEED + 1, CURVATURE_ERROR_MIN_SPEED
# outside the band (its edge is meas + band + 1), inside the rate delta from 'last' at the slowest window
out_of_band = last + self.model.rate_delta(below) // 2
self.assertGreater(out_of_band, meas_can + MAX_CURVATURE_ERROR_CAN + 1)
for window, newest, expect_blocked in ((below, above, True), (above, below, False), (above, gate, False), (below, gate, False)):
self.set_meas(meas_can / CURVATURE_TO_CAN, window)
self.rx(self.stock._speed_msg(newest))
v_min, v_max = self.speeds()
m_min, m_max = self.meas()
with self.subTest(window=window, newest=newest):
self.assertEqual(not expect_blocked, self.model.allowed(out_of_band, last, m_min, m_max, v_min, v_max, newest))
self.assertEqual(not expect_blocked, self._probe(out_of_band, last))
def test_newest_speed_sample_gates_the_shadow_check(self):
"""Angle mode's shadow-curvature check (ford_shadow_curvature_error_check) also switches on
vehicle_speed.values[0], the newest sample: older samples at 9.5 m/s and the newest at 10.5: on;
the reverse: off. 0.5 m/s either side keeps clear of speed_mismatch_check's 2 m/s limit."""
below, above = CURVATURE_ERROR_MIN_SPEED - 0.5, CURVATURE_ERROR_MIN_SPEED + 0.5
for window, newest, expect_blocked in ((below, above, True), (above, below, False)):
self.set_meas(0, window)
self.rx(self.stock._speed_msg(newest))
_, m_max = self.meas()
out_of_band = m_max + MAX_CURVATURE_ERROR_CAN + 2 # one past highest_allowed in the C
self.tx(self.lka_bp_status_msg(True, out_of_band / CURVATURE_TO_CAN))
with self.subTest(window=window, newest=newest):
self.assertEqual(not expect_blocked, self.tx(self.lat(True, 0, SMALL_ANGLE, 0, 0)))
self.tx(self.lka_bp_status_msg(False, 0.0))
def test_zero_curvature_skips_curvature_checks(self):
"""Curvature == 0 (angle mode's sentinel) skips the curvature value checks (cap, rate tables,
error band); the controls-allowed gate and the message-rate check remain
(ford_bp_curvature_cmd_checks). Pins current behavior, see #10 and #60."""
self.set_meas(0.01, 15.0) # measured 500 CAN: a real curvature command of 0 would be far outside the band
self.assertTrue(self.tx(self.lat(True, 0, SMALL_ANGLE, 0, 0)))
self.safety.set_controls_allowed(False)
host.set_controls_allowed_lat(self.safety, False)
self.assertFalse(self.tx(self.lat(True, 0, SMALL_ANGLE, 0, 0)))
self.safety.set_controls_allowed(True)
# --- the reset frame: curvature 0 and path_angle 0 (#9) ---
def test_reset_frame_accepted_mid_curve(self):
"""Curvature mode's human-turn reset: steering enabled, curvature 0 and path_angle 0 while the
car is mid-curve. Curvature 0 skips the error band, so the frame is accepted; the
controller depends on this."""
self.set_meas(0.01, 20.0) # measured 500 CAN: a real curvature command of 0 would be far outside the band
self.set_prev_curvature_can(500)
self.assertTrue(self.tx(self.lat(True, 0, 0, 0, 0)))
def test_reset_frame_then_jump_blocked(self):
"""The repro in #9, steps A-C: at 25 m/s a jump from 0.001 to 0.02 rad/m is blocked (A); a
curvature 0 / path_angle 0 frame is accepted (B); the same jump right after it is still
blocked (C). With the latch, C passed."""
self.set_meas(0, 25.0)
jump, last = 0.02, int(0.001 * CURVATURE_TO_CAN)
self.set_prev_curvature_can(last)
self.assertFalse(self.tx(self.lat(True, 0, 0, jump, 0))) # A
self.assertTrue(self.tx(self.lat(True, 0, 0, 0, 0))) # B
self.set_prev_curvature_can(last)
self.assertFalse(self.tx(self.lat(True, 0, 0, jump, 0))) # C
def _walk(self, reset_frame) -> list[bool]:
"""Re-init, send reset_frame (if any), then a seeded random walk of curvature, path_angle and
path_offset steps up to 1.3 ROC steps each, so some frames pass and some are blocked by the
rate limits and the error band. Returns each frame's tx result. curvature_rate stays 0: its ROC
check can never fire (#22), so varying it would show nothing."""
self.reinit()
self.safety.set_controls_allowed(True)
self.set_meas(0, 12.0) # band on around 0
if reset_frame is not None:
self.assertTrue(self.tx(reset_frame))
v_min, _ = self.speeds()
steps = (self.model.rate_delta(v_min),
angle_roc_delta(PATH_ANGLE_LOOKUP_X, PATH_ANGLE_LOOKUP_Y, PATH_ANGLE_TO_CAN, v_min),
angle_roc_delta(PATH_OFFSET_LOOKUP_X, PATH_OFFSET_LOOKUP_Y, PATH_OFFSET_TO_CAN, v_min))
bounds = (150, 300, 80) # CAN units: past the band (101), inside the path_angle / path_offset ranges
rng = random.Random(9)
pos = [self.TINY_CURVATURE_CAN, 0, 0]
results = []
for _ in range(FORMER_LATCH_WINDOW_FRAMES):
pos = [max(-b, min(b, p + round(rng.uniform(-1.3, 1.3) * s))) for p, s, b in zip(pos, steps, bounds, strict=True)]
pos[0] = pos[0] or self.TINY_CURVATURE_CAN # curvature 0 would skip the value checks
curvature, angle, offset = pos
results.append(self.tx(self.lat(True, offset / PATH_OFFSET_TO_CAN, angle / PATH_ANGLE_TO_CAN, curvature / CURVATURE_TO_CAN, 0)))
return results
def test_reset_frame_leaves_no_state(self):
"""After a reset frame, enabled (curvature mode's human-turn reset) or disabled (angle mode's
mode 0), every check gives the same result, frame for frame, as without it, across the whole
window the removed bypass latch used to cover (#9)."""
baseline = self._walk(None)
self.assertTrue(any(baseline)) # some frames pass
self.assertFalse(all(baseline)) # and some are blocked
for enabled in (True, False):
with self.subTest(enabled=enabled):
self.assertEqual(baseline, self._walk(self.lat(enabled, 0, 0, 0, 0)))
def test_init_resets_bp_state(self):
"""ford_bp_init (from ford_init) clears the BP path_angle / path_offset last values and the angle-mode flag, the
way set_safety_hooks clears upstream's lateral state: after a re-init the first frame is
checked against 0, not against the previous session. (The curvature_rate last value is reset
too, but its ROC can never fire, so that is not observable; see #22.)"""
speed = CURVATURE_ERROR_MIN_SPEED + 5
for stale in ("path_angle", "path_offset", "angle_mode"):
with self.subTest(stale=stale):
self.set_meas(0, speed)
v_min, _ = self.speeds()
angle_delta = angle_roc_delta(PATH_ANGLE_LOOKUP_X, PATH_ANGLE_LOOKUP_Y, PATH_ANGLE_TO_CAN, v_min)
offset_delta = angle_roc_delta(PATH_OFFSET_LOOKUP_X, PATH_OFFSET_LOOKUP_Y, PATH_OFFSET_TO_CAN, v_min)
# leave the one piece of state 3 ROC steps away from 0 (or angle mode engaged, with a
# shadow value that fails the window), then re-init
for step in (1, 2, 3):
angle = step * angle_delta if stale == "path_angle" else 0
offset = step * offset_delta if stale == "path_offset" else 0
self.set_prev_curvature_can(self.TINY_CURVATURE_CAN)
self.assertTrue(self.tx(self.lat(True, offset / PATH_OFFSET_TO_CAN, angle / PATH_ANGLE_TO_CAN,
self.TINY_CURVATURE_CAN / CURVATURE_TO_CAN, 0)))
if stale == "angle_mode":
self.tx(self.lka_bp_status_msg(True, 0.02))
self.reinit()
self.safety.set_controls_allowed(True)
self.set_meas(0.005 if stale == "angle_mode" else 0, speed)
self.set_prev_curvature_can(self.TINY_CURVATURE_CAN)
if stale == "angle_mode":
# the flag is cleared, so a curvature-0 frame is not checked against the shadow value
# (ford_bp_init leaves the raw shadow value alone; the flag gates its use)
self.assertTrue(self.tx(self.lat(True, 0, SMALL_ANGLE, 0, 0)))
else:
# one full ROC step below 0: within the ROC only if the last value is exactly 0 (from the
# stale value it is 4 steps, from 1 it is one unit too many)
angle = -angle_delta if stale == "path_angle" else 0
offset = -offset_delta if stale == "path_offset" else 0
self.assertTrue(self.tx(self.lat(True, offset / PATH_OFFSET_TO_CAN, angle / PATH_ANGLE_TO_CAN,
self.TINY_CURVATURE_CAN / CURVATURE_TO_CAN, 0)))
# --- the other three signals ---
# the three non-curvature probes carry 1 CAN unit of curvature (measured 0, last 1), which
# passes the curvature checks, so only the signal under test decides
TINY_CURVATURE_CAN = 1
def _angle_probe(self, angle_can: int) -> bool:
self.set_prev_curvature_can(self.TINY_CURVATURE_CAN)
return self.tx(self.lat(True, 0, angle_can / PATH_ANGLE_TO_CAN, self.TINY_CURVATURE_CAN / CURVATURE_TO_CAN, 0))
def test_path_angle_range_and_roc(self):
"""Per-frame ROC from the {10,15,25} table (path_angle_cmd_checks) and the +-0.25 rad range in curvature
mode. A frame always becomes the new 'last' even when blocked, so each probe re-baselines."""
for speed in (8.0, 12.0, 20.0, 25.0):
self.set_meas(0, speed)
v_min, _ = self.speeds()
delta = angle_roc_delta(PATH_ANGLE_LOOKUP_X, PATH_ANGLE_LOOKUP_Y, PATH_ANGLE_TO_CAN, v_min)
for base in (0, 200, -200):
for sign in (1, -1):
with self.subTest(speed=speed, base=base, sign=sign):
self._angle_probe(base)
self.assertTrue(self._angle_probe(base + sign * delta))
self._angle_probe(base)
self.assertFalse(self._angle_probe(base + sign * (delta + 1)))
# range: step from just inside so the ROC allows it
if delta > 2:
for sign in (1, -1):
self._angle_probe(sign * (PATH_ANGLE_MAX_CAN - 1))
self.assertTrue(self._angle_probe(sign * PATH_ANGLE_MAX_CAN))
self.assertFalse(self._angle_probe(sign * (PATH_ANGLE_MAX_CAN + 1)))
def test_path_angle_dbc_range_in_angle_mode(self):
"""With angle mode engaged (Lane_Assist_Data1 bit) the range widens to the DBC's [-0.5, 0.5235]."""
self.set_meas(0, 8.0) # below the shadow-check speed gate so only the range matters
self.tx(self.lka_bp_status_msg(True, 0.0))
v_min, _ = self.speeds()
delta = angle_roc_delta(PATH_ANGLE_LOOKUP_X, PATH_ANGLE_LOOKUP_Y, PATH_ANGLE_TO_CAN, v_min)
self.assertGreater(delta, 60)
for target, over in ((PATH_ANGLE_DBC_MAX_CAN, PATH_ANGLE_DBC_MAX_CAN + 1), (PATH_ANGLE_DBC_MIN_CAN, PATH_ANGLE_DBC_MIN_CAN - 1)):
# walk up in ROC-sized steps (the signal can pack these values)
pos = 0
while abs(target - pos) > delta:
pos += delta if target > pos else -delta
self._angle_probe(pos)
self.assertTrue(self._angle_probe(target))
self.assertFalse(self._angle_probe(over))
self._angle_probe(pos)
self.tx(self.lka_bp_status_msg(False, 0.0))
def _offset_probe(self, offset_can: int) -> bool:
self.set_prev_curvature_can(self.TINY_CURVATURE_CAN)
return self.tx(self.lat(True, offset_can / PATH_OFFSET_TO_CAN, SMALL_ANGLE, self.TINY_CURVATURE_CAN / CURVATURE_TO_CAN, 0))
def test_path_offset_range_and_roc(self):
"""Per-frame ROC from the {5,15,25} table (path_offset_cmd_checks) and the +-1.0 m range.
At 9 m/s the speed fudge's sign decides the limit (5 with v - 1, 4 with v + 1)."""
for speed in (3.0, 8.0, 9.0, 12.0, 20.0, 25.0):
self.set_meas(0, speed)
v_min, _ = self.speeds()
delta = angle_roc_delta(PATH_OFFSET_LOOKUP_X, PATH_OFFSET_LOOKUP_Y, PATH_OFFSET_TO_CAN, v_min)
for base in (0, 50, -50):
for sign in (1, -1):
with self.subTest(speed=speed, base=base, sign=sign):
self._offset_probe(base)
self.assertTrue(self._offset_probe(base + sign * delta))
self._offset_probe(base)
self.assertFalse(self._offset_probe(base + sign * (delta + 1)))
for sign in (1, -1):
self._offset_probe(sign * (PATH_OFFSET_MAX_CAN - 1))
self.assertTrue(self._offset_probe(sign * PATH_OFFSET_MAX_CAN))
self.assertFalse(self._offset_probe(sign * (PATH_OFFSET_MAX_CAN + 1)))
RATE_TO_CAN = CURVATURE_RATE_TO_CAN_CANFD
def _rate_probe(self, rate_can: int) -> bool:
self.set_prev_curvature_can(self.TINY_CURVATURE_CAN)
return self.tx(self.lat(True, 0, SMALL_ANGLE, self.TINY_CURVATURE_CAN / CURVATURE_TO_CAN, rate_can / self.RATE_TO_CAN))
def test_curvature_rate_must_be_zero(self):
"""Curvature rate must be 0, the rule stock Ford applies (#22): one wire unit either way is
blocked at any speed, steer enabled or disabled. The disabled frame carries only the rate, so
the rate check is the one deciding (the all-zero disabled frame passes)."""
for speed in (3.0, 12.0, 30.0):
self.set_meas(0, speed)
for rate_can in (1, -1, 1023, -1024):
with self.subTest(speed=speed, rate_can=rate_can):
self.assertTrue(self._rate_probe(0))
self.assertFalse(self._rate_probe(rate_can))
# disabled frames last: their path_angle of 0 would make the next enabled probe's path_angle step decide
for speed in (3.0, 12.0, 30.0):
self.set_meas(0, speed)
for rate_can in (1, -1, 1023, -1024):
with self.subTest(speed=speed, rate_can=rate_can, enabled=False):
self.assertTrue(self.tx(self.lat(False, 0, 0, 0, 0)))
self.assertFalse(self.tx(self.lat(False, 0, 0, 0, rate_can / self.RATE_TO_CAN)))
def test_curvature_zero_frames_are_rate_limited(self):
"""#24: angle mode sends curvature 0 on every frame. Those frames are held to the same message-rate
window as the rest (upstream's rolling 250 ms window, split in two halves): sent faster than 20 Hz,
every frame past the limit is blocked until the window rolls over. Path angle carries the command,
so these frames never arm the reset latch."""
self.set_meas(0, 15.0)
max_rt_msgs = int(20 * common.RT_INTERVAL / 1e6 * 1.2 + 1)
half = common.RT_INTERVAL // 2
def send():
return self.tx(self.lat(True, 0, SMALL_ANGLE, 0, 0, increment_timer=False))
self.safety.set_timer(0)
for i in range(max_rt_msgs * 2):
self.assertEqual(i <= max_rt_msgs, send(), i)
self.safety.set_timer(half)
self.assertFalse(send()) # the overflow moves into the previous half
self.safety.set_timer(half + common.RT_INTERVAL)
self.assertFalse(send())
self.safety.set_timer(half + 2 * common.RT_INTERVAL)
for _ in range(max_rt_msgs):
self.assertTrue(send())
class TestFordBPLimitsCAN(TestFordBPLimitsCANFD):
"""Same checks on the CAN (non-FD) LateralMotionControl message: no lateral-accel cap, and the
curvature-rate signal has 4x the wire resolution."""
CANFD = False
RATE_TO_CAN = CURVATURE_RATE_TO_CAN_CAN
def test_lateral_accel_cap(self):
"""CAN: no cap. A curvature well above the CAN FD cap is accepted up to the 0.02 hard limit."""
self.set_meas(MAX_CURVATURE_CAN / CURVATURE_TO_CAN, 25.0)
v_min, _ = self.speeds()
self.assertLess(self.model.accel_cap(v_min), MAX_CURVATURE_CAN) # the FD cap would bite here
self.assertTrue(self._probe(MAX_CURVATURE_CAN, MAX_CURVATURE_CAN))
if __name__ == "__main__":
unittest.main()
@@ -1,129 +0,0 @@
#!/usr/bin/env python3
"""
BluePilot Ford lateral: upstream's whole Ford safety matrix with the BP_LATERAL bit set.
Subclasses the three stock test classes so relay-malfunction, forwarding, button, longitudinal,
rx-hook and every other upstream test runs against the BluePilot tx hook. Only the tests whose
stock assertions the 4-signal lateral changes on purpose are replaced:
* test_steer_allowed, test_curvature_rate_limits: assert upstream's single-signal limits; the
BluePilot equivalents are in test_ford_bluepilot_limits.py (every signal, exact boundaries).
* test_max_lateral_acceleration: BluePilot caps at ISO_LATERAL_ACCEL - g*roll (~2.41 m/s^2)
with a speed fudge, not upstream's ~3.6 m/s^2; CAN FD only.
* test_rt_limits runs unchanged: it sends curvature-0 frames, which still get the message-rate
check in ford_bp_curvature_cmd_checks (#24, #60). test_rt_limits_nonzero_curvature pins it for
curvature mode.
"""
import unittest
from ....safety.tests import common
from ...core.values_ext import FordSafetyFlagsSP
from ....safety.tests import test_ford
from ....safety.tests.libsafety import libsafety_py
from .ford_bluepilot_common import (
BPFordLateralModel, CURVATURE_TO_CAN, MAX_CURVATURE_ERROR_CAN, CURVATURE_SIGNAL_MAX_CAN,
)
from ...tests import host
SKIP_REASON = "BluePilot 4-signal limits are asserted in test_ford_bluepilot_limits.py"
class BPLateralMatrixMixin:
"""Set the bit before ford_init runs, clear it after, and swap the host's stock lateral tests
(skipped below, or replaced).
Class names must start with 'TestFord': common.py's cross-mode TX sweep only skips
Ford-vs-Ford comparisons by that prefix."""
CANFD = True
PARAM_SP = int(FordSafetyFlagsSP.BP_LATERAL)
MAX_CURVATURE_ERROR_CAN_BP = MAX_CURVATURE_ERROR_CAN # FORD_LIMITS(_, 100); the pinion classes use MAX_CURVATURE_ERROR_CAN_PINION
def setUp(self):
self.safety = libsafety_py.libsafety
host.set_safety_param(self.safety, self.PARAM_SP)
# StarPilot: the bits ride the Ford param. Only the upstream bases that define SAFETY_PARAM
# (sunnypilot, StarPilot) need this; IQ.Pilot's iqdbc base doesn't define it, and ford_param
# is a no-op for non-StarPilot hosts anyway.
if hasattr(self, "SAFETY_PARAM"):
self.SAFETY_PARAM = host.ford_param(self.SAFETY_PARAM, self.PARAM_SP)
super().setUp() # stock setUp: packer, set_safety_hooks, init_tests
self.model = BPFordLateralModel(self.CANFD, self.MAX_CURVATURE_ERROR_CAN_BP)
def tearDown(self):
host.set_safety_param(self.safety, 0)
super().tearDown() # the host's own resets (IQ.Pilot's AOL state)
@unittest.skip(SKIP_REASON)
def test_steer_allowed(self):
pass
@unittest.skip(SKIP_REASON)
def test_curvature_rate_limits(self):
pass
# IQ.Pilot's test_ford: its stock controller (CURVATURE_LIMITS.apply_limits) against the stock checks.
# With BP_LATERAL set the car controller sends the BluePilot commands instead, never these.
@unittest.skip(SKIP_REASON)
def test_controller_limits_pass_safety(self):
pass
def test_max_lateral_acceleration(self):
"""BluePilot's cap (CAN FD only) at ISO_LATERAL_ACCEL - g*roll over the fudged speed squared."""
for speed in (12.0, 15.0, 20.0, 25.0, 30.0, 35.0):
self.safety.set_controls_allowed(True)
self._reset_curvature_measurement(0, speed)
v_min = float(self.safety.get_vehicle_speed_min())
cap = self.model.cap(v_min)
for sign in (1, -1):
for offset in (-5, -1, 0, 1, 5):
curvature_can = sign * (cap + offset)
if abs(curvature_can) > CURVATURE_SIGNAL_MAX_CAN:
continue
self._reset_curvature_measurement(curvature_can / CURVATURE_TO_CAN, speed)
self._set_prev_desired_angle(curvature_can / CURVATURE_TO_CAN)
should_tx = abs(curvature_can) <= cap
with self.subTest(speed=speed, curvature_can=curvature_can):
self.assertEqual(should_tx, self._tx(self._lat_ctl_msg(True, 0, 0, curvature_can / CURVATURE_TO_CAN, 0)))
def test_rt_limits_nonzero_curvature(self):
"""Upstream's rolling-window message-rate check, driven with a non-zero curvature (curvature mode)."""
self.safety.set_controls_allowed(True)
self._reset_curvature_measurement(0, 0)
curvature = 1 / CURVATURE_TO_CAN
max_rt_msgs = int(self.LATERAL_FREQUENCY * common.RT_INTERVAL / 1e6 * 1.2 + 1)
half = common.RT_INTERVAL // 2
def send():
self._set_prev_desired_angle(curvature)
return self._tx(self._lat_ctl_msg(True, 0, 0, curvature, 0, increment_timer=False))
self.safety.set_timer(0)
for i in range(max_rt_msgs * 2):
self.assertEqual(i <= max_rt_msgs, send())
self.safety.set_timer(half)
self.assertFalse(send())
self.safety.set_timer(half + 2 * common.RT_INTERVAL // 5)
self.assertFalse(send())
self.assertFalse(send())
self.safety.set_timer(half + common.RT_INTERVAL)
self.assertFalse(send())
self.safety.set_timer(half + 2 * common.RT_INTERVAL)
for _ in range(max_rt_msgs):
self.assertTrue(send())
class TestFordBPCANFDStockSafety(BPLateralMatrixMixin, test_ford.TestFordCANFDStockSafety):
CANFD = True
class TestFordBPCANFDLongitudinalSafety(BPLateralMatrixMixin, test_ford.TestFordCANFDLongitudinalSafety):
CANFD = True
class TestFordBPLongitudinalSafety(BPLateralMatrixMixin, test_ford.TestFordLongitudinalSafety):
CANFD = False
if __name__ == "__main__":
unittest.main()

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