mirror of
https://github.com/firestar5683/StarPilot.git
synced 2026-11-25 14:23:45 +08:00
Compare commits
255 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| c8a17afb21 | |||
| ff4b154609 | |||
| c9fea63596 | |||
| 8852c7bce6 | |||
| 71a9228954 | |||
| 63fe5bb3e1 | |||
| 697dcf29e0 | |||
| 591c5fcf53 | |||
| 78303dda84 | |||
| fb4468b347 | |||
| c707dd4938 | |||
| 698a203cbc | |||
| db79a4620d | |||
| 48fb24ee48 | |||
| 22f010c1ac | |||
| d89f221d06 | |||
| 07331b33e8 | |||
| 951beb26be | |||
| 683435ac68 | |||
| 241e0a43d4 | |||
| fad5a9faaf | |||
| 19b7edf344 | |||
| ab02d5a44c | |||
| 8a9f7a084c | |||
| e59fa4930a | |||
| 855dfb3a17 | |||
| 026ce00b72 | |||
| 3728cea591 | |||
| bc1edc500d | |||
| 330a302aa1 | |||
| 6e879b55da | |||
| 059612c13a | |||
| bbe680c127 | |||
| ceb0bea247 | |||
| 35c80054d3 | |||
| 6cfa8b9f25 | |||
| 919363f4fa | |||
| 131ad10d63 | |||
| 47346ad98b | |||
| 9c5a5e5b86 | |||
| ce47ff1da3 | |||
| 55269d0856 | |||
| 0da55d93ae | |||
| 6f73fad098 | |||
| 9da91c24af | |||
| bd2e523bfe | |||
| 70de2df8f2 | |||
| d461cad223 | |||
| a8d1dd1d91 | |||
| 2151b3c77b | |||
| e555faacc1 | |||
| e7f5d5fd4e | |||
| 9a32c18941 | |||
| aafa97df61 | |||
| 4f07a1ea4a | |||
| cf26c720f0 | |||
| ef38e75164 | |||
| 0ecbad2a41 | |||
| ff9f0f0b33 | |||
| d24bfcd0f3 | |||
| 17ea1c3c3e | |||
| 4ef3b1c2b4 | |||
| f9bc75a3fd | |||
| f67edb6529 | |||
| fa66e9baac | |||
| 6dea0ec66c | |||
| 3fa425f769 | |||
| 7dbbb43c3b | |||
| 777df8f6d8 | |||
| f29ab3c676 | |||
| d197e09d3b | |||
| 24f65c6feb | |||
| cf2ddc0734 | |||
| 3693294b10 | |||
| 0ea99a0128 | |||
| 981455ecc6 | |||
| 2c53700269 | |||
| 3393b7d698 | |||
| ec4c158e20 | |||
| 1c087154ae | |||
| a46f9941e7 | |||
| 47bbc2e1bf | |||
| c0d7eeb09c | |||
| 16786b6517 | |||
| 00be4586e2 | |||
| 0b0f216dff | |||
| 404ef33a96 | |||
| b119731ad2 | |||
| e71059b2d1 | |||
| 288027a08d | |||
| 0b5e75d9c5 | |||
| 9b25c7c0cc | |||
| 6ccf23ddb6 | |||
| bb4840ab89 | |||
| 7848780457 | |||
| b5931c365d | |||
| 6c2f6fc048 | |||
| 3f5068a19b | |||
| f7ef9b117c | |||
| 0972ef0d44 | |||
| 459d2e6b94 | |||
| e366cb0170 | |||
| 81c66ef1ac | |||
| 645cca2086 | |||
| 5ab912b3d4 | |||
| 1ffb6314f2 | |||
| 791e9ee4ad | |||
| 7da988976c | |||
| b94119ec3e | |||
| cce15c82dc | |||
| ede0735ffd | |||
| d98dfb489d | |||
| 29b703d207 | |||
| fce3f7d436 | |||
| a24192a582 | |||
| 1f06ce685c | |||
| dda32b141c | |||
| 75757ab021 | |||
| 6da9182f6c | |||
| 870bd63ff4 | |||
| 2535ee3901 | |||
| 6d4b357e1f | |||
| 68ef096322 | |||
| d8439a094b | |||
| 2a2594b697 | |||
| 2223a9d371 | |||
| b25bbb8c78 | |||
| 16806d8a93 | |||
| ae4df1725c | |||
| f2c632ef11 | |||
| ea17311f8c | |||
| a3c73c70e5 | |||
| 5fbcdffece | |||
| 972dd457c5 | |||
| 19122ea4e2 | |||
| 46c17cc1aa | |||
| d3f179e766 | |||
| cd65e68b60 | |||
| 31f8918db7 | |||
| e4f363003b | |||
| f36af88b54 | |||
| ec59d25227 | |||
| 8687966c6d | |||
| 91683efbf6 | |||
| 73e593514d | |||
| 549a28fa9f | |||
| ea704cb66d | |||
| fd9cd41a68 | |||
| d4fac91919 | |||
| 80c21b10dc | |||
| 50e0e7241a | |||
| d7f509b98a | |||
| 5561759a77 | |||
| 3e34e48f91 | |||
| cf1ecc9aff | |||
| 9f954d2909 | |||
| c8abbd740b | |||
| 1f0455554b | |||
| 730713bb89 | |||
| 85a2f5b786 | |||
| b739b32844 | |||
| 403c79eaff | |||
| 87a57e5359 | |||
| 4603d87068 | |||
| 0db704125d | |||
| 0c57d72897 | |||
| 2cf77aa2de | |||
| 19a135ff10 | |||
| 08c2199599 | |||
| 122a248050 | |||
| c67b1c074a | |||
| d91e913953 | |||
| d907949650 | |||
| 6738edad1a | |||
| c1f7468fff | |||
| ba10c64889 | |||
| 6bf5e14704 | |||
| b2e84e4a11 | |||
| ede83a74d1 | |||
| 80aae010ee | |||
| 91a070023d | |||
| 28a6cf1133 | |||
| ee7b5d66be | |||
| 058f28ed2f | |||
| faef0b43ee | |||
| 193835d88d | |||
| 4218e46640 | |||
| c0a70d3d87 | |||
| 64e4411939 | |||
| f06dfafff0 | |||
| 5bf72b4a2c | |||
| e9d7d1610f | |||
| e44319a142 | |||
| 94473780e8 | |||
| cb3ebdd09e | |||
| 81dc63dac6 | |||
| 448a673630 | |||
| 9d88359d20 | |||
| 8c0826a61f | |||
| 008b0cbcf1 | |||
| 8d487d0dc5 | |||
| 4241d07dc8 | |||
| 1faca4bed4 | |||
| 1aa4f9ce50 | |||
| bd2dba096c | |||
| 6d9b146eea | |||
| ec9cd685b9 | |||
| 3508aba53d | |||
| ef3b03444c | |||
| e29879ca79 | |||
| 14fe0d040d | |||
| 602b54181c | |||
| c82db4bc03 | |||
| d7b3560862 | |||
| 256924b83c | |||
| 028cbb9df4 | |||
| 92f4cbe228 | |||
| 829c5ce6c8 | |||
| ee3aa066f8 | |||
| ee82c843ca | |||
| 9e869ef085 | |||
| 212b1d7eef | |||
| 57135a1f28 | |||
| f8e110a1ac | |||
| 64a28c5877 | |||
| f84e678554 | |||
| b00d753a24 | |||
| 4e0e99039a | |||
| 5da0140842 | |||
| 43b1ea1b34 | |||
| 508409e6ba | |||
| aef357ce92 | |||
| be463c0905 | |||
| 013d9753e0 | |||
| b5b3b8b80f | |||
| 5a88d1c7c1 | |||
| 08d23a48e9 | |||
| 7181662d12 | |||
| eac912d9ad | |||
| 06f2da46ad | |||
| 38e7b89f66 | |||
| 03d6f7b445 | |||
| 84592f6012 | |||
| 3bbd0280a6 | |||
| fbc192941d | |||
| 2568d806e4 | |||
| 8a301fa02f | |||
| 6232db5ce0 | |||
| 555dac7d12 | |||
| cb3bfc720b | |||
| 6709d6743d | |||
| 4e86f60665 | |||
| 8af946ac09 | |||
| 1cd4feed89 | |||
| e5ea759719 |
@@ -11,6 +11,7 @@ on:
|
||||
- testing
|
||||
- dev
|
||||
pull_request:
|
||||
types: [opened, synchronize, reopened, edited]
|
||||
workflow_dispatch:
|
||||
workflow_call:
|
||||
inputs:
|
||||
@@ -25,11 +26,15 @@ concurrency:
|
||||
jobs:
|
||||
docs:
|
||||
name: build docs
|
||||
permissions:
|
||||
contents: read
|
||||
runs-on: ${{
|
||||
(github.repository == 'commaai/openpilot') &&
|
||||
(github.repository == 'StarPilotHQ/StarPilot' && github.event_name == 'push' && github.ref == 'refs/heads/testing')
|
||||
&& fromJSON('["self-hosted","Linux","X64","truenas","starpilot-build"]')
|
||||
|| ((github.repository == 'commaai/openpilot') &&
|
||||
((github.event_name != 'pull_request') ||
|
||||
(github.event.pull_request.head.repo.full_name == 'commaai/openpilot'))
|
||||
&& fromJSON('["namespace-profile-amd64-8x16"]')
|
||||
&& fromJSON('["namespace-profile-amd64-8x16"]'))
|
||||
|| fromJSON('["ubuntu-24.04"]') }}
|
||||
steps:
|
||||
- uses: commaai/timeout@v1
|
||||
@@ -40,6 +45,11 @@ jobs:
|
||||
/openpilot/selfdrive/assets/icons_mici/settings/comma_icon.png
|
||||
sparse-checkout-cone-mode: false
|
||||
|
||||
- uses: actions/setup-python@v6
|
||||
if: github.repository == 'StarPilotHQ/StarPilot' && github.event_name == 'push' && github.ref == 'refs/heads/testing'
|
||||
with:
|
||||
python-version: '3.12.13'
|
||||
|
||||
# Build
|
||||
- name: Build docs
|
||||
run: python3 docs/serve.py --build
|
||||
|
||||
@@ -24,6 +24,9 @@ on:
|
||||
- '.github/workflows/flm-offroad.yaml'
|
||||
- 'pyproject.toml'
|
||||
- 'uv.lock'
|
||||
pull_request:
|
||||
branches: [stable]
|
||||
types: [opened, synchronize, reopened, edited]
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
source_sha:
|
||||
@@ -88,6 +91,8 @@ jobs:
|
||||
--json-output ci-results/flm-offroad.json
|
||||
.venv/bin/python -m pytest -q --import-mode=importlib \
|
||||
openpilot/starpilot/flm/tests/test_steering_compatibility.py \
|
||||
openpilot/starpilot/flm/tests/test_offroad_nonemitted_controls.py \
|
||||
openpilot/starpilot/flm/tests/test_pending_review.py \
|
||||
openpilot/starpilot/flm/tests/test_observed_maneuvers.py \
|
||||
openpilot/starpilot/flm/tests/test_upstream_producer_transport.py \
|
||||
openpilot/starpilot/flm/tests/test_clock_resolution_budget.py \
|
||||
|
||||
@@ -7,10 +7,12 @@ on:
|
||||
- 'openpilot/starpilot/galaxy_bluetooth/**'
|
||||
- '.github/workflows/galaxy-phone-bridge.yaml'
|
||||
pull_request:
|
||||
branches-ignore: [stable]
|
||||
paths:
|
||||
- 'openpilot/starpilot/galaxy_bluetooth/**'
|
||||
- '.github/workflows/galaxy-phone-bridge.yaml'
|
||||
workflow_dispatch:
|
||||
workflow_call:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
@@ -35,8 +35,9 @@ jobs:
|
||||
|
||||
REPO = "StarPilotHQ/StarPilot"
|
||||
MARKER = "<!-- starpilot-pr-discord-reminder-v1 -->"
|
||||
BODY = ("In order to review this PR, please open a ticket in the "
|
||||
"StarPilot Discord at https://firestar.link/discord.\n\n" + MARKER)
|
||||
BODY = ("Thank you for your PR! To increase communication and responsiveness, "
|
||||
"please open a ticket describing your PR in the StarPilot discord at "
|
||||
"[https://firestar.link/discord](https://firestar.link/discord)\n\n" + MARKER)
|
||||
|
||||
def remind(event, request):
|
||||
if event.get("action") != "opened" or "pull_request" not in event:
|
||||
|
||||
@@ -4,6 +4,7 @@ on:
|
||||
push:
|
||||
branches: [master, Domathon, Dom, StarPilot, stable, testing, dev]
|
||||
pull_request:
|
||||
types: [opened, synchronize, reopened, edited]
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
|
||||
@@ -11,6 +11,7 @@ on:
|
||||
- testing
|
||||
- dev
|
||||
pull_request:
|
||||
types: [opened, synchronize, reopened, edited]
|
||||
workflow_dispatch:
|
||||
workflow_call:
|
||||
inputs:
|
||||
@@ -31,6 +32,12 @@ env:
|
||||
PYTHONPATH: ${{ github.workspace }}
|
||||
|
||||
jobs:
|
||||
stable_pr_phone_bridge:
|
||||
if: github.event_name == 'pull_request' && github.base_ref == 'stable'
|
||||
permissions:
|
||||
contents: read
|
||||
uses: ./.github/workflows/galaxy-phone-bridge.yaml
|
||||
|
||||
source_integrity:
|
||||
name: source integrity
|
||||
runs-on: ubuntu-24.04
|
||||
@@ -45,6 +52,7 @@ jobs:
|
||||
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"'
|
||||
python3 -c 'from pathlib import Path; paths = ("openpilot/system/camerad/camerad", "msgq_repo/msgq/visionipc/_visionipc.so", "openpilot/system/loggerd/encoderd", "openpilot/tools/replay/replay"); assert all(b"/dev/ion\0" in Path(p).read_bytes() for p in paths), "Shipped camera buffers must use ION"'
|
||||
- name: Test one-shot branch migration
|
||||
run: python3 -m unittest discover -s scripts/tests -v
|
||||
- name: Validate tracked dependencies
|
||||
@@ -93,7 +101,7 @@ jobs:
|
||||
env:
|
||||
GOTOOLCHAIN: local
|
||||
run: |
|
||||
sudo apt-get -o Acquire::Retries=2 -o Acquire::http::Timeout=30 -o Acquire::https::Timeout=30 update && sudo apt-get -o Acquire::Retries=2 -o Acquire::http::Timeout=30 -o Acquire::https::Timeout=30 install -y --no-install-recommends pkg-config zlib1g-dev
|
||||
sudo apt-get update && sudo apt-get install -y --no-install-recommends pkg-config zlib1g-dev
|
||||
(cd mapd_repo && go mod download)
|
||||
PYTHONPATH="$GITHUB_WORKSPACE" python3 -m openpilot.starpilot.maps.package_shadow
|
||||
- name: Build devel
|
||||
@@ -218,7 +226,7 @@ jobs:
|
||||
env:
|
||||
RAYLIB_BACKEND: headless
|
||||
STARPILOT_TEST_DIAGNOSTICS: ci-results/host-test-diagnostics/unittest
|
||||
run: tools/op.sh test --jobs 2 --json-output unit-test-results.json
|
||||
run: tools/op.sh test --json-output unit-test-results.json
|
||||
- name: Test GM vehicle configurations and CAN behavior
|
||||
if: ${{ !cancelled() && steps.build.outcome == 'success' }}
|
||||
timeout-minutes: 5
|
||||
@@ -303,7 +311,7 @@ jobs:
|
||||
.venv/bin/python -c "import av; assert 'libx264' in av.codecs_available"
|
||||
- name: Provide Mesa software graphics for pixel-level tests
|
||||
if: ${{ !cancelled() && steps.build.outcome == 'success' }}
|
||||
run: sudo apt-get -o Acquire::Retries=2 -o Acquire::http::Timeout=30 -o Acquire::https::Timeout=30 update && sudo apt-get -o Acquire::Retries=2 -o Acquire::http::Timeout=30 -o Acquire::https::Timeout=30 install -y libegl1 libgles-dev libgl1-mesa-dri
|
||||
run: sudo apt-get update && sudo apt-get install -y libegl1 libgles-dev libgl1-mesa-dri
|
||||
- name: Test every assigned custom pytest node serially
|
||||
if: ${{ !cancelled() && steps.build.outcome == 'success' }}
|
||||
timeout-minutes: 20
|
||||
@@ -410,7 +418,7 @@ jobs:
|
||||
go-version: '1.25.1'
|
||||
cache-dependency-path: mapd_repo/go.sum
|
||||
- name: Install native build dependencies
|
||||
run: sudo apt-get -o Acquire::Retries=2 -o Acquire::http::Timeout=30 -o Acquire::https::Timeout=30 update && sudo apt-get -o Acquire::Retries=2 -o Acquire::http::Timeout=30 -o Acquire::https::Timeout=30 install -y --no-install-recommends pkg-config zlib1g-dev
|
||||
run: sudo apt-get update && sudo apt-get install -y --no-install-recommends pkg-config zlib1g-dev
|
||||
- name: Test and build pinned map provider
|
||||
run: python3 tools/ci/run_map_tests.py --output ci-results/map-provider
|
||||
- name: Save test and build evidence
|
||||
|
||||
@@ -49,3 +49,7 @@ The explicit StarPilot [jacobw Subaru adapter](opendbc_repo/opendbc/car/subaru/J
|
||||
The previous optional StarPilot Controller, formerly in `openpilot/starpilot/car/ford/starpilot_tuning.py`, restored demand tuning from StarPilot `8da0c9d916^`, descended from BluePilot bp-7.0 `e1d051d7ba270261b4455068bd68f1a58db15a4a` through StarPilot `2efe6017bfe14cee4807833e05f9a7f6ba255cdb`. Contributors to that lineage include Alan Polk, John Christman, Jacob Neulight, tonesto7 and Haibin Wen. The current protocol adapter is maintained by StarPilot separately from the pinned BluePilot library; this attribution does not imply BluePilot maintains or endorses the adapted tune.
|
||||
|
||||
The current StarPilot Controller replaces that historical curvature-primary tune with a separately maintained adaptation of BluePilot v0.2.1's angle strategy (`2b9dc6cc784faac47a1885d0bda0561f7b76f74d`, `core/lateral_angle_ext.py`). Alan Polk is the principal controller author; John Christman contributed angle-mode anti-stall work, Jacob Neulight the pinion/shadow measurement, Nathan Ingraham and Praeuner high-speed damping, and other contributors are retained in the pinned library's `CREDITS.md`. StarPilot adds bounded small-signal conditioning ahead of the unchanged angle limit chain. This adaptation is not maintained or endorsed by BluePilot; the pinned library and its imported hooks are unchanged.
|
||||
|
||||
## Uniden radar detector link
|
||||
|
||||
The Uniden detector link builds on **inauner's** earlier Uniden R4/R8/R9 work in [inauner/StarPilot, uniden](https://github.com/inauner/StarPilot/tree/c4b694b2ac8742ddec44123d53f1f84d2990b47e) (`uniden_protocol.py`, `uniden_r4.py`, `uniden_radar_d.py`, the Galaxy Uniden panel and the radar alert banner), which established the detector's BLE alert flow and the Galaxy/UI integration approach. This branch's monitor, transport, widgets and tests are a separate implementation on the current StarPilot Bluetooth owner; the experimental settings and speed-limit slowdown logic are not included. The alert parser and command framing are based on AegisX86/UnidenR8wlink (see THIRD_PARTY_NOTICES.md).
|
||||
|
||||
@@ -8,73 +8,33 @@
|
||||
[](https://firestar.link/ios)
|
||||
[](https://firestar.link/android)
|
||||
|
||||
**StarPilot** is a custom fork of [comma.ai's openpilot](https://comma.ai/openpilot),
|
||||
an open source driver assistance system.
|
||||
StarPilot is an open source driver assistance system for comma 3, 3X, and 4. This branch is where you can try StarPilot 7.0.
|
||||
|
||||
Openpilot provides
|
||||
* Automated Lane Centering
|
||||
* Adaptive Cruise Control
|
||||
* Lane Change Assist
|
||||
* Driver Monitoring *without wheel nags*
|
||||
## What's on testing
|
||||
|
||||
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.
|
||||
* **Lane Centering 2.0** can keep the car centered when only one lane line is visible in certain scenarios. When lane markings are unreliable, it falls back to the driving model's path.
|
||||
* **Enhanced Stops** improves stops at stop signs and traffic lights. Vision Stop Sign Detection uses the road camera to recognize stop signs.
|
||||
* **Custom Controllers** improve turning behavior on supported vehicles. The Firestar Lateral Method adapts steering to your car, and StarPilot's longitudinal planner manages acceleration and braking on supported radar and vision-only configurations.
|
||||
* **Custom Models** let you choose from community fine tunes in Galaxy's Model Manager.
|
||||
* **On-Device UI Replay** lets you review a recorded drive with the driving interface overlaid on the footage.
|
||||
|
||||
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).
|
||||
## StarPort and companion apps
|
||||
|
||||
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)!
|
||||
**StarPort** puts the driving display on a compatible Android Auto head unit, with navigation, music controls, and model connection status. Use Mapbox or Google Maps for route guidance, and play audio through compatible car speakers with Spotify Connect or phone audio.
|
||||
|
||||
## Documentation
|
||||
**Galaxy** lets you change settings, download models, update StarPilot, run diagnostics, and manage dashcam footage from your phone. The native apps connect over Wi-Fi, Firestar Link (HTTPS), or Bluetooth. [Download for iOS](https://firestar.link/ios) · [Download for Android](https://firestar.link/android)
|
||||
|
||||
Please see [https://wiki.firestar.link](https://wiki.firestar.link) for hardware lists,
|
||||
installation guides, and software configuration.
|
||||
## Getting started
|
||||
|
||||
## Features
|
||||
Find supported hardware, installation steps, and settings in the [StarPilot wiki](https://wiki.firestar.link). Ask questions in the [community Discord](https://firestar.link/discord) or [open a driving support ticket](https://firestar.link/logs).
|
||||
|
||||
* **Full support for Comma C3, C3X, and C4**
|
||||
* Full support for chestnut/eGPU on C3, C3X, and C4. C3/C3X may require special gps handling.
|
||||
* Model switcher with all of comma's tinygrad driving models
|
||||
* StarPilot custom torque controller
|
||||
* StarPilot custom longitudinal planner for both radar and VoACC (visual only, radar-less) vehicles
|
||||
* **Custom tuning for an expanding list of vehicles**
|
||||
* Firestar Lateral Method -
|
||||
Auto tuning system to adapt openpilot to *your* car's unique lateral characteristics.
|
||||
* Galaxy: StarPilot's portal to configure your comma device using your phone from anywhere.
|
||||
Download models, change settings, update software, diagnostics, manage dashcam video, and more.
|
||||
* Android and iOS companion apps - Access Galaxy over Wi-Fi, Firestar Link (HTTPS), or Bluetooth.
|
||||
* StarPort - Project StarPilot onto compatible Android Auto head units for a larger driving display.
|
||||
* Customizable driving display - Driving map and navigation widgets, plus music controls and Jetlink status in StarPort.
|
||||
* Spotify Connect and phone audio - Play through compatible car speakers over StarPort or Bluetooth.
|
||||
* Navigation - Mapbox or Google maps and routing, with route guidance for exits and turns.
|
||||
* Always On Lateral (full time steering assist)
|
||||
* Lane Centering - Enable to center between detected lane lines,
|
||||
with graceful fallback to model E2E lateral outputs and safety breakout
|
||||
* Force Stop 2.0 - Better stops at stop signs and traffic lights.
|
||||
* Speed Limit Controller - Use dashboard, map data, and/or vision detection for speed limit signs
|
||||
* Curve Speed Controller - Learns from how you take curves
|
||||
* Conditional Experimental Mode (CEM)
|
||||
* Conditional Chill Mode (CCM)
|
||||
* Driving Profiles and Traffic Mode
|
||||
* Custom themes
|
||||
* Alert volume customization
|
||||
* Comma Pedal Interceptor support
|
||||
* Bluetooth support - Connect keyboards, controllers, steering wheel remotes, and more.
|
||||
* Sentry mode - Record when motion is detected while parked.
|
||||
* V-ASM - Detect vehicles in the adjacent/blind spots using the driver-facing camera.
|
||||
* Additional car support - Toyota SDSU, ZSS, CAN filter; pre-AP tesla; ford; Polestar 2; and more.
|
||||
* And more!
|
||||
## More driving and device features
|
||||
|
||||
* Always On Lateral keeps steering assistance available independently of adaptive cruise on supported vehicles.
|
||||
* Speed Limit Controller uses dashboard, map, or vision data. Curve Speed Controller learns from how you take curves.
|
||||
* Driving Profiles and Traffic Mode, adjustable alert volume, and vehicle-specific tuning.
|
||||
* Bluetooth keyboards, controllers, and steering wheel remotes.
|
||||
* Sentry Mode records motion while parked. V-ASM uses the driver-facing camera to detect vehicles alongside the car.
|
||||
|
||||
## GM-only Features
|
||||
|
||||
@@ -111,6 +71,28 @@ StarPilot retains upstream vehicle and Panda safety interfaces and adds regressi
|
||||
|
||||
Support depends on the vehicle configuration and enabled feature. An existing vehicle identifier or settings page does not by itself establish driving support. Model Laboratory currently exposes management controls, but paired driving inference remains unavailable pending integration and Chestnut validation.
|
||||
|
||||
## Integrations and credits
|
||||
|
||||
StarPilot builds on [comma.ai's openpilot](https://comma.ai/openpilot), which provides automated lane centering, adaptive cruise control, lane change assist, and driver monitoring.
|
||||
|
||||
* **JetLink** is an experimental integration with Zeph Leggett / ZoomPilot's host software. Run a larger driving model on a compatible USB-connected laptop, phone, tablet, or Jetson. See the [JetLink setup and hardware guide](openpilot/starpilot/models/JETLINK.md).
|
||||
* **Chestnut eGPU** is supported on comma 3, 3X, and 4. The 3 and 3X may need additional GPS setup. The model switcher also supports comma's tinygrad driving models.
|
||||
* Additional vehicle and hardware integrations include the comma pedal interceptor, Toyota SDSU, ZSS and CAN filter configurations, pre-AP Tesla, Ford, and Polestar 2.
|
||||
|
||||
Ford-specific lateral-control and vehicle-support work includes substantial adaptations from
|
||||
[BluePilot](https://github.com/BluePilotDev/bluepilot/tree/bp-7.0), principally developed by
|
||||
[Alan Polk](https://github.com/alan-polk) with additional BluePilot contributors. StarPilot's
|
||||
implementation has since diverged, but that does not erase its lineage. See [CREDITS.md](CREDITS.md)
|
||||
for the code-level provenance and [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md) for applicable
|
||||
upstream notices and terms. BluePilot and its contributors do not maintain or endorse StarPilot;
|
||||
please direct support requests for this adaptation to the StarPilot project.
|
||||
|
||||
Hyundai, Kia, and Genesis angle steering and related vehicle support include substantial adaptations
|
||||
from [sunnypilot](https://github.com/sunnypilot/sunnypilot/tree/hkg-angle-steering-2025) and its
|
||||
[opendbc angle-steering branch](https://github.com/sunnypilot/opendbc/tree/hkg-angle-steering-2025).
|
||||
StarPilot's implementation has diverged significantly; the upstream contributors do not maintain
|
||||
this adaptation. Detailed code lineage is recorded in [CREDITS.md](CREDITS.md).
|
||||
|
||||
## Third-Party Notices
|
||||
|
||||
* 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.
|
||||
|
||||
@@ -154,3 +154,7 @@ The Subaru angle implementation includes work from Jacob Waller's `jul-angle-bas
|
||||
The historical tuning formerly in `openpilot/starpilot/car/ford/starpilot_tuning.py` included the BluePilot bp-7.0-derived work identified in [CREDITS.md](CREDITS.md#starpilot-ford-demand-tuning). The published upstream license notices retained above and in the pinned BluePilot library remain applicable to the adapted source. StarPilot's separate protocol adapter does not modify those notices or resolve their scope.
|
||||
|
||||
The angle-primary adaptation in `openpilot/starpilot/car/ford/starpilot_controller.py` is derived from BluePilot v0.2.1. It retains the complete MIT copyright and permission notice in `opendbc_repo/opendbc/bluepilot_lateral/LICENSE`, including Comma.ai, BluePilot and StarPilot contributors. See the contributor attribution in `CREDITS.md`.
|
||||
|
||||
## Uniden detector protocol
|
||||
|
||||
The detector alert parser and command framing in `openpilot/starpilot/uniden/` are based on [AegisX86/UnidenR8wlink](https://github.com/AegisX86/UnidenR8wlink)'s MIT-licensed protocol documentation, copyright (c) 2026 Aegis "P.R Aigis". The complete notice is retained in [UPSTREAM-LICENSE](openpilot/starpilot/uniden/UPSTREAM-LICENSE).
|
||||
|
||||
+1
-1
@@ -26,7 +26,7 @@ fi
|
||||
export QCOM_PRIORITY=12
|
||||
|
||||
if [ -z "$AGNOS_VERSION" ]; then
|
||||
export AGNOS_VERSION="20.5.3"
|
||||
export AGNOS_VERSION="20.5.5"
|
||||
fi
|
||||
|
||||
# Legacy stagers defer flashing; agnos_init still requires AGNOS_VERSION before manager startup.
|
||||
|
||||
@@ -39,7 +39,7 @@ msgq_python = envNanobind.Program(f'msgq/_ipc{python_suffix}', ['msgq/ipc_py.cc'
|
||||
|
||||
# Build Vision IPC
|
||||
vipc_files = ['visionipc.cc', 'visionipc_server.cc', 'visionipc_client.cc']
|
||||
if File('/dev/ion').exists():
|
||||
if arch == "comma_arm64" or File('/dev/ion').exists():
|
||||
vipc_files += ['visionbuf_ion.cc']
|
||||
else:
|
||||
vipc_files += ['visionbuf.cc']
|
||||
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -10,12 +10,15 @@ from opendbc.car.fw_versions import (ObdCallback, get_fw_versions, get_fw_versio
|
||||
get_present_ecus, match_fw_to_car)
|
||||
from opendbc.car.mock.values import CAR as MOCK
|
||||
from opendbc.car.gm.pedal_capability import automatic_bolt_candidate
|
||||
from opendbc.car.gm.discovery import automatic_trax_candidate, automatic_volt_candidate, normal_bus0_topology as gm_normal_bus0_topology
|
||||
from opendbc.car.gm.discovery import (automatic_trax_candidate, automatic_volt_ascm_candidate, automatic_volt_candidate,
|
||||
normal_bus0_topology as gm_normal_bus0_topology)
|
||||
from opendbc.car.ford.discovery import (normal_bus0_selection as ford_normal_bus0_selection,
|
||||
normal_bus0_queries as ford_normal_bus0_queries, normal_bus_query_brand)
|
||||
from opendbc.car.volvo.discovery import normal_bus_topology as volvo_normal_bus_topology
|
||||
from opendbc.car.volvo.discovery import normal_bus_topology as volvo_normal_bus_topology, v60_bus_topology as volvo_v60_bus_topology
|
||||
from opendbc.car.hyundai.discovery import normal_bus_topology
|
||||
from opendbc.car.honda.discovery import normal_bus_topology as honda_normal_bus_topology
|
||||
from opendbc.car.honda.discovery import nidec_bus0_topology, normal_bus_topology as honda_normal_bus_topology
|
||||
from opendbc.car.honda.values import CAR as HONDA, HondaFlags
|
||||
from opendbc.car.mazda.discovery import normal_bus0_topology as mazda_normal_bus0_topology
|
||||
from opendbc.car.chrysler.discovery import normal_bus_topology as chrysler_normal_bus_topology
|
||||
from opendbc.car.tesla.discovery import normal_bus0_topology as tesla_normal_bus0_topology
|
||||
from opendbc.car.values import BRANDS
|
||||
@@ -94,6 +97,7 @@ def can_fingerprint(can_recv: CanRecvCallable, *, vin: str = VIN_UNKNOWN,
|
||||
frame += 1
|
||||
|
||||
car_fingerprint = automatic_volt_candidate(car_fingerprint, finger, candidate_cars)
|
||||
car_fingerprint = automatic_volt_ascm_candidate(car_fingerprint, finger, candidate_cars, vin)
|
||||
car_fingerprint = automatic_trax_candidate(car_fingerprint, finger, candidate_cars, vin)
|
||||
return automatic_bolt_candidate(car_fingerprint, finger, camera_cruise_messages, vin), finger
|
||||
|
||||
@@ -143,6 +147,14 @@ def fingerprint(can_recv: CanRecvCallable, can_send: CanSendCallable, set_obd_mu
|
||||
cached = True
|
||||
else:
|
||||
carlog.warning("Getting VIN & FW versions")
|
||||
volvo_v60 = False
|
||||
|
||||
def volvo_probe(fp):
|
||||
nonlocal volvo_v60
|
||||
volvo_v60 = volvo_v60_bus_topology(fp)
|
||||
return volvo_normal_bus_topology(fp) or volvo_v60
|
||||
|
||||
full_scan = False
|
||||
if known_gm_bus0:
|
||||
# An explicit registered GM selection already identifies the query family.
|
||||
# Current GM requests use normal bus 0. Keep live VIN/FW collection and
|
||||
@@ -179,21 +191,34 @@ def fingerprint(can_recv: CanRecvCallable, can_send: CanSendCallable, set_obd_mu
|
||||
elif (normal_brand := normal_bus_query_brand(
|
||||
observe_normal_bus, normal_bus_topology,
|
||||
gm_probe=gm_normal_bus0_topology if _gm_fw_uses_normal_bus0() else None,
|
||||
volvo_probe=volvo_normal_bus_topology if not fw_versions.FW_QUERY_CONFIGS['volvo'].requests else None,
|
||||
volvo_probe=volvo_probe,
|
||||
tesla_probe=tesla_normal_bus0_topology if _tesla_fw_uses_normal_bus0() else None) or
|
||||
('honda' if honda_normal_bus_topology(normal_bus_packets) else None) or
|
||||
('chrysler' if chrysler_normal_bus_topology(normal_bus_packets) else None)) is not None:
|
||||
('honda_nidec' if nidec_bus0_topology(normal_bus_packets) else None) or
|
||||
('chrysler' if chrysler_normal_bus_topology(normal_bus_packets) else None) or
|
||||
('mazda' if mazda_normal_bus0_topology(normal_bus_packets) else None)) is not None:
|
||||
|
||||
set_obd_multiplexing(False)
|
||||
warmup_remaining = 0.1 - (time.monotonic() - start_time)
|
||||
if warmup_remaining > 0:
|
||||
time.sleep(warmup_remaining)
|
||||
vin_buses = (0,) if normal_brand in ('ford', 'gm', 'volvo', 'tesla', 'chrysler') else (0, 1)
|
||||
vin_buses = (0,) if normal_brand in ('ford', 'gm', 'volvo', 'tesla', 'chrysler', 'honda_nidec', 'mazda') else (0, 1)
|
||||
vin_rx_addr, vin_rx_bus, vin = get_vin(can_recv, can_send, vin_buses)
|
||||
car_fw = get_fw_versions(can_recv, can_send, set_obd_multiplexing,
|
||||
query_brand=normal_brand, normal_bus_only=True)
|
||||
if normal_brand == 'honda_nidec':
|
||||
car_fw = get_fw_versions(can_recv, can_send, set_obd_multiplexing, query_brand='honda', query_bus=0)
|
||||
exact, matches = match_fw_to_car(car_fw, vin)
|
||||
full_scan = not (exact and len(matches) == 1 and any(
|
||||
candidate in HONDA and HONDA(candidate).config.flags & HondaFlags.NIDEC for candidate in matches))
|
||||
elif normal_brand == 'volvo' and not volvo_v60:
|
||||
# Polestar is identified by live CAN alone; the V60 by its engine FW, which answers on bus 0
|
||||
car_fw = []
|
||||
else:
|
||||
car_fw = get_fw_versions(can_recv, can_send, set_obd_multiplexing,
|
||||
query_brand=normal_brand, normal_bus_only=True)
|
||||
ecu_rx_addrs = {(fw.responseAddress, fw.subAddress or None, fw.bus) for fw in car_fw if fw.responseAddress > 0}
|
||||
else:
|
||||
full_scan = True
|
||||
if full_scan:
|
||||
# enable OBD multiplexing for VIN query
|
||||
# NOTE: this takes ~0.1s and is relied on to allow sendcan subscriber to connect in time
|
||||
set_obd_multiplexing(True)
|
||||
@@ -238,6 +263,11 @@ def fingerprint(can_recv: CanRecvCallable, can_send: CanSendCallable, set_obd_mu
|
||||
# Refine after both automatic sources, before the explicit override below.
|
||||
if not fixed_fingerprint:
|
||||
car_fingerprint = automatic_bolt_candidate(car_fingerprint, finger, camera_cruise_messages, vin)
|
||||
if car_fingerprint == 'SUBARU_IMPREZA' and source == CarParams.FingerprintSource.fw and exact_match:
|
||||
# Subaru's early GT Crosstrek and Impreza share a firmware bucket.
|
||||
# NHTSA vPIC identifies JF2GT with model-year codes J and K as Crosstrek.
|
||||
if is_valid_vin(vin) and vin.startswith('JF2GT') and vin[9] in ('J', 'K'):
|
||||
car_fingerprint = 'SUBARU_CROSSTREK_2018'
|
||||
|
||||
if fixed_fingerprint:
|
||||
car_fingerprint = fixed_fingerprint
|
||||
|
||||
@@ -79,6 +79,10 @@ def ford_sign(speed: int, unit: int) -> tuple[Status, float]:
|
||||
return (Status.ABSENT, 0.0) if speed in (251, 255) else (Status.UNKNOWN, 0.0)
|
||||
|
||||
|
||||
def volvo_sign(speed_kph: float) -> tuple[Status, float]:
|
||||
return (Status.VALID, speed_kph / 3.6) if speed_kph > 0 else (Status.ABSENT, 0.0)
|
||||
|
||||
|
||||
def hyundai_canfd_sign(speed: int, system_status: int, is_metric: bool) -> tuple[Status, float]:
|
||||
# FR_CMR_02_100ms defines 0 as no recognition, 253 as unlimited, and
|
||||
# 254/255 as reserved/invalid. A failed ISLW system is not evidence of absence.
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
"""Normal-bus discovery for explicitly selected Ford CAN-FD vehicles."""
|
||||
"""Normal-bus discovery for Ford vehicles."""
|
||||
import time
|
||||
|
||||
from opendbc.car.ford.values import CAR, FordFlags
|
||||
@@ -42,7 +42,8 @@ def normal_bus0_selection(candidate):
|
||||
# diagnostic query family; live VIN, ECU responses and fingerprinting still
|
||||
# determine the vehicle and its control configuration.
|
||||
NORMAL_BUS0_LAYOUT = {(0, 0x82): 8, (0, 0x165): 8, (0, 0x204): 8,
|
||||
(0, 0x217): 8, (2, 0x3CA): 8, (2, 0x3D6): 8}
|
||||
(0, 0x217): 8, (2, 0x3CA): 8}
|
||||
CAMERA_STEERING_LAYOUT = {(2, 0x3D3): 8, (2, 0x3D6): 8}
|
||||
|
||||
|
||||
def normal_bus_query_brand(can_recv, hyundai_probe, *, gm_probe=None, volvo_probe=None, tesla_probe=None, clock=time.monotonic):
|
||||
@@ -55,6 +56,10 @@ def normal_bus_query_brand(can_recv, hyundai_probe, *, gm_probe=None, volvo_prob
|
||||
reads = 0
|
||||
deadline = clock() + .12
|
||||
|
||||
def complete():
|
||||
return (not malformed and NORMAL_BUS0_LAYOUT.items() <= received.items() and
|
||||
any(key in received for key in CAMERA_STEERING_LAYOUT))
|
||||
|
||||
def observe(**kwargs):
|
||||
nonlocal malformed, gm_malformed, reads
|
||||
reads += 1
|
||||
@@ -67,9 +72,9 @@ def normal_bus_query_brand(can_recv, hyundai_probe, *, gm_probe=None, volvo_prob
|
||||
length = len(frame.dat)
|
||||
gm_malformed |= frame.address in bus and bus[frame.address] != length
|
||||
bus[frame.address] = length
|
||||
if key in NORMAL_BUS0_LAYOUT:
|
||||
if (expected := NORMAL_BUS0_LAYOUT.get(key) or CAMERA_STEERING_LAYOUT.get(key)) is not None:
|
||||
length = len(frame.dat)
|
||||
malformed |= length != NORMAL_BUS0_LAYOUT[key]
|
||||
malformed |= length != expected
|
||||
received[key] = length
|
||||
return packets
|
||||
|
||||
@@ -77,11 +82,11 @@ def normal_bus_query_brand(can_recv, hyundai_probe, *, gm_probe=None, volvo_prob
|
||||
return 'hyundai'
|
||||
# Rejecting HKG or Ford does not reject GM. Finish the shared passive window
|
||||
# within its original budget even when an early frame excludes Ford.
|
||||
while not (not malformed and received == NORMAL_BUS0_LAYOUT) and reads < 24 and clock() < deadline:
|
||||
while not complete() and reads < 24 and clock() < deadline:
|
||||
if malformed and ((gm_probe is None and volvo_probe is None and tesla_probe is None) or gm_malformed):
|
||||
break
|
||||
observe(wait_for_one=True)
|
||||
if not malformed and received == NORMAL_BUS0_LAYOUT and normal_bus0_queries():
|
||||
if complete() and normal_bus0_queries():
|
||||
return 'ford'
|
||||
if gm_probe is not None and not gm_malformed and gm_probe(gm_received):
|
||||
return 'gm'
|
||||
|
||||
@@ -93,6 +93,7 @@ class Request:
|
||||
logging: bool = False
|
||||
# pandad toggles OBD multiplexing on/off as needed
|
||||
obd_multiplexing: bool = True
|
||||
brand_query_only: bool = False
|
||||
|
||||
|
||||
@dataclass
|
||||
|
||||
@@ -40,6 +40,11 @@ def is_brand(brand: str, filter_brand: str | None) -> bool:
|
||||
return filter_brand is None or brand == filter_brand
|
||||
|
||||
|
||||
def firmware_requests(query_brand: str | None = None):
|
||||
return [(brand, config, request) for brand, config, request in REQUESTS
|
||||
if is_brand(brand, query_brand) and (query_brand is not None or not request.brand_query_only)]
|
||||
|
||||
|
||||
def build_fw_dict(fw_versions: list[CarParams.CarFw], filter_brand: str | None = None) -> dict[AddrType, set[bytes]]:
|
||||
fw_versions_dict: defaultdict[AddrType, set[bytes]] = defaultdict(set)
|
||||
for fw in fw_versions:
|
||||
@@ -200,7 +205,7 @@ def get_present_ecus(can_recv: CanRecvCallable, can_send: CanSendCallable, set_o
|
||||
parallel_queries: dict[bool, list[EcuAddrBusType]] = {True: [], False: []}
|
||||
responses: set[EcuAddrBusType] = set()
|
||||
|
||||
for brand, config, r in REQUESTS:
|
||||
for brand, config, r in firmware_requests():
|
||||
for ecu_type, addr, sub_addr in config.get_all_ecus(VERSIONS[brand]):
|
||||
# Only query ecus in whitelist if whitelist is not empty
|
||||
if len(r.whitelist_ecus) == 0 or ecu_type in r.whitelist_ecus:
|
||||
@@ -232,10 +237,11 @@ def get_brand_ecu_matches(ecu_rx_addrs: set[EcuAddrBusType]) -> dict[str, list[b
|
||||
"""Returns dictionary of brands and matches with ECUs in their FW versions"""
|
||||
|
||||
brand_rx_addrs = {brand: set() for brand in FW_QUERY_CONFIGS}
|
||||
brand_matches = {brand: [] for brand, _, _ in REQUESTS}
|
||||
requests = firmware_requests()
|
||||
brand_matches = {brand: [] for brand, _, _ in requests}
|
||||
|
||||
# Since we can't know what request an ecu responded to, add matches for all possible rx offsets
|
||||
for brand, config, r in REQUESTS:
|
||||
for brand, config, r in requests:
|
||||
for ecu in config.get_all_ecus(VERSIONS[brand]):
|
||||
if len(r.whitelist_ecus) == 0 or ecu[0] in r.whitelist_ecus:
|
||||
brand_rx_addrs[brand].add((uds.get_rx_addr_for_tx_addr(ecu[1], r.rx_offset), ecu[2]))
|
||||
@@ -275,7 +281,7 @@ def get_fw_versions_ordered(can_recv: CanRecvCallable, can_send: CanSendCallable
|
||||
|
||||
def get_fw_versions(can_recv: CanRecvCallable, can_send: CanSendCallable, set_obd_multiplexing: ObdCallback, query_brand: str | None = None,
|
||||
extra: OfflineFwVersions | None = None, timeout: float = 0.1, progress: bool = False,
|
||||
*, normal_bus_only: bool = False) -> list[CarParams.CarFw]:
|
||||
*, normal_bus_only: bool = False, query_bus: int | None = None) -> list[CarParams.CarFw]:
|
||||
versions = VERSIONS.copy()
|
||||
|
||||
if query_brand is not None:
|
||||
@@ -308,7 +314,8 @@ def get_fw_versions(can_recv: CanRecvCallable, can_send: CanSendCallable, set_ob
|
||||
|
||||
# Get versions and build capnp list to put into CarParams
|
||||
car_fw = []
|
||||
requests = [(brand, config, r) for brand, config, r in REQUESTS if is_brand(brand, query_brand) and
|
||||
requests = [(brand, config, r) for brand, config, r in firmware_requests(query_brand) if
|
||||
(query_bus is None or r.bus == query_bus) and
|
||||
not (normal_bus_only and r.bus % 4 == 1 and r.obd_multiplexing)]
|
||||
for addr_group in tqdm(addrs, disable=not progress): # split by subaddr, if any
|
||||
for addr_chunk in chunks(addr_group):
|
||||
|
||||
@@ -50,7 +50,7 @@ def migrate_assignments(params, cp):
|
||||
('LongDistanceButtonControl', 'LongCancelButtonControl', 5),
|
||||
('VeryLongDistanceButtonControl', 'VeryLongCancelButtonControl', 6))
|
||||
pending = []
|
||||
valid = tuple(str(value).encode() for value in range(15))
|
||||
valid = tuple(str(value).encode() for value in range(16))
|
||||
for source, target, default in pairs:
|
||||
raw, readable = read_saved(params, target, 8)
|
||||
previous, source_readable = read_saved(params, source, 8)
|
||||
|
||||
@@ -1008,7 +1008,8 @@ class CarController(CarControllerBase):
|
||||
else:
|
||||
stop_brake = fixed_stopping_brake(CC.longActive, near_stop, stopping, CC.cruiseControl.resume,
|
||||
self.CP.stopAccel, self.params.MAX_BRAKE)
|
||||
if stop_brake is not None:
|
||||
bolt_rolling_stop = self.bolt_euv_long and stop_brake is not None and not CS.out.standstill
|
||||
if stop_brake is not None and not bolt_rolling_stop:
|
||||
self.apply_gas = self.params.INACTIVE_REGEN
|
||||
self.apply_brake = stop_brake
|
||||
if self.truck_tuning is not None:
|
||||
@@ -1035,6 +1036,9 @@ class CarController(CarControllerBase):
|
||||
self.apply_gas, self.apply_brake = bolt_euv_demands(
|
||||
actuators.accel, CS.out.vEgo, CC.orientationNED if long_pitch else None,
|
||||
self.CP.mass, self.CP.wheelbase, self.params.MAX_BRAKE, acc_tune=self.gm_acc_tune)
|
||||
if bolt_rolling_stop:
|
||||
# Keep the requested braking until the wheels stop rolling.
|
||||
self.apply_brake = max(self.apply_brake, stop_brake)
|
||||
elif self.volt_gateway_long or self.volt_ascm_long or self.volt_camera_long or self.volt_sdgm_long:
|
||||
self.apply_gas, self.apply_brake = volt_demands(
|
||||
actuators.accel, CS.out.vEgo, CC.orientationNED if long_pitch else None,
|
||||
|
||||
@@ -419,10 +419,12 @@ class CarState(CarStateBase):
|
||||
ret.standstill = abs(pt_cp.vl["EBCMWheelSpdRear"]["RLWheelSpd"]) <= STANDSTILL_THRESHOLD and \
|
||||
abs(pt_cp.vl["EBCMWheelSpdRear"]["RRWheelSpd"]) <= STANDSTILL_THRESHOLD
|
||||
|
||||
if pt_cp.vl["ECMPRDNL2"]["ManualMode"] == 1:
|
||||
gear = pt_cp.vl["ECMPRDNL2"]
|
||||
self.gm_regen_gear = self.bolt_cc_profile and self.CP.carFingerprint in NO_ACC_BOLT_CAR and gear["PRNDL2"] in (5, 7)
|
||||
if gear["ManualMode"] == 1:
|
||||
ret.gearShifter = self.parse_gear_shifter("T")
|
||||
else:
|
||||
ret.gearShifter = self.parse_gear_shifter(self.shifter_values.get(pt_cp.vl["ECMPRDNL2"]["PRNDL2"], None))
|
||||
ret.gearShifter = self.parse_gear_shifter(self.shifter_values.get(gear["PRNDL2"], None))
|
||||
|
||||
source_be_brake = (gm_control_word(self.CP) &
|
||||
(GMSafetyFlags.ASCM_INTERCEPT | GMSafetyFlags.SDGM).value and
|
||||
@@ -493,7 +495,10 @@ class CarState(CarStateBase):
|
||||
if new_sample:
|
||||
self.pedal_sensor_ts_nanos = sensor_ts
|
||||
self.pedal_sensor_counter = counter
|
||||
self.pedal_sensor_healthy = bool(counter_changed and sensor["STATE"] == 0 and tracks_valid and checksum_valid)
|
||||
state = sensor["STATE"]
|
||||
state_ok = state == 0 or (state == 8 and bolt_pedal_profile and not removed_pedal and
|
||||
self.CP.carFingerprint == CAR.CHEVROLET_BOLT_CC_2022_2023)
|
||||
self.pedal_sensor_healthy = bool(counter_changed and state_ok and tracks_valid and checksum_valid)
|
||||
elif sensor_ts < self.pedal_sensor_ts_nanos:
|
||||
self.pedal_sensor_healthy = False
|
||||
self.pedal_sensor_ts_nanos = 0
|
||||
|
||||
@@ -46,6 +46,25 @@ def automatic_volt_candidate(candidate, fingerprint, candidates):
|
||||
return CAR.CHEVROLET_VOLT_CC
|
||||
|
||||
|
||||
def automatic_volt_ascm_candidate(candidate, fingerprint, candidates, vin):
|
||||
# The recorded 2018 SASCM Volt falls out of both legacy CAN candidate lists.
|
||||
if (candidate is not None or any(candidates.values()) or not isinstance(vin, str) or not is_valid_vin(vin) or
|
||||
not vin.startswith('1G1RD6S5') or vin[9] != 'J'):
|
||||
return candidate
|
||||
|
||||
pt = fingerprint.get(CanBus.POWERTRAIN, {})
|
||||
camera = fingerprint.get(CanBus.CAMERA, {})
|
||||
radar = fingerprint.get(CanBus.OBSTACLE, {})
|
||||
required = {0xC9: 8, 0x180: 4, 0x184: 8, 0x1C4: 8, 0x1E1: 7,
|
||||
0x2FF: 4, 0x348: 5, 0x34A: 5, 0x370: 6}
|
||||
if (pt != camera or any(pt.get(address) != size for address, size in required.items()) or
|
||||
radar.get(0x460) != 8 or radar.get(0x474) != 8 or
|
||||
any(address in pt for address in (0xBE, 0x201)) or pt.get(0x320) not in (None, 3) or
|
||||
any(messages for bus, messages in fingerprint.items() if bus not in (CanBus.POWERTRAIN, CanBus.OBSTACLE, CanBus.CAMERA))):
|
||||
return candidate
|
||||
return CAR.CHEVROLET_VOLT_ASCM
|
||||
|
||||
|
||||
# Frequent normal-bus frames observed on mirrored pedal installations. This is
|
||||
# only diagnostic query-family evidence, never a vehicle/control fingerprint.
|
||||
PEDAL_NORMAL_BUS_LAYOUT = {0xD3: 2, 0xBE: 6, 0xC9: 8, 0x1C4: 8,
|
||||
|
||||
@@ -10,11 +10,12 @@ from opendbc.car.gm.tests.test_ascm_intercept import params
|
||||
from opendbc.car.gm.values import CAR, DBC, is_bolt_euv_longitudinal
|
||||
|
||||
|
||||
def original_demand(cp, active, speed, accel, state, resume, pitch):
|
||||
# Original 6cae0ce, ordinary non-Volt camera path; default LongPitch on.
|
||||
def original_demand(cp, active, speed, accel, state, resume, pitch, *, standstill=False):
|
||||
# Original 6cae0ce camera path, with the hold demand as a floor while rolling.
|
||||
if not active:
|
||||
return 5650, 0
|
||||
if speed < 0.25 and state == 'stopping' and not resume:
|
||||
hold = speed < 0.25 and state == 'stopping' and not resume
|
||||
if hold and standstill:
|
||||
return 5650, 25
|
||||
grade = math.sin(pitch) * 9.81 if speed > 0.25 else 0.0
|
||||
if grade > 0 and accel > 0:
|
||||
@@ -27,6 +28,8 @@ def original_demand(cp, active, speed, accel, state, resume, pitch):
|
||||
switch = int(round(np.interp(speed, [0.5, 10.0], [6150, 5610])))
|
||||
brake_accel = min((torque - switch) / (radius * cp.mass), 0.0)
|
||||
brake = int(round(np.interp(brake_accel, [-4.0, 0.0], [400, 0])))
|
||||
if hold:
|
||||
brake = max(25, brake)
|
||||
return (5650 if brake > 0 or state == 'stopping' else raw), brake
|
||||
|
||||
|
||||
@@ -58,7 +61,8 @@ PHASES = [(False, False, 12., 1., 'off', False, False, 0.),
|
||||
(True, True, 12., 1., 'pid', False, False, 0.),
|
||||
(True, True, 7., -1.5, 'pid', False, False, -0.04)]
|
||||
PHASES += [(True, True, speed, -2., 'stopping', False, False, 0.) for speed in (0.6, 0.49, 0.3, 0.25, 0.24, 0.1)]
|
||||
PHASES += [(True, True, 0., -4., 'stopping', False, True, 0.),
|
||||
PHASES += [(True, True, .213, -.665, 'stopping', False, False, 0.),
|
||||
(True, True, 0., -.665, 'stopping', False, True, 0.),
|
||||
(True, True, 0., 1., 'stopping', True, True, 0.),
|
||||
(True, True, 0., 0.5, 'starting', True, True, 0.),
|
||||
(True, True, 0.3, 0.5, 'starting', True, False, 0.),
|
||||
@@ -136,7 +140,7 @@ class TestBoltEuvControl(unittest.TestCase):
|
||||
if not alpha or frame % 4:
|
||||
self.assertFalse(actual)
|
||||
continue
|
||||
raw, brake = original_demand(cp, active, speed, accel, state, resume, pitch)
|
||||
raw, brake = original_demand(cp, active, speed, accel, state, resume, pitch, standstill=still)
|
||||
expected = original_frames(raw, brake, (frame // 4) % 4, enabled, active and still and state == 'stopping')
|
||||
self.assertEqual(actual, expected, (alpha, alignment, phase, frame))
|
||||
self.assertEqual((controller.apply_gas, controller.apply_brake), (raw - 6150, brake))
|
||||
|
||||
@@ -50,9 +50,10 @@ class TestBoltFactoryAcc(unittest.TestCase):
|
||||
ci = CarInterface(cp)
|
||||
packer = CANPacker(DBC[cp.carFingerprint][Bus.pt])
|
||||
setup(cp)
|
||||
cases = [(speed, accel, pitch) for speed in (5., 20., 35.)
|
||||
cases = [(speed, accel, pitch, 'pid') for speed in (5., 20., 35.)
|
||||
for accel in (-4., -2., -.5, 0., 1., 2.) for pitch in (-.04, 0., .04)]
|
||||
for tick, (speed, accel, pitch) in enumerate(cases):
|
||||
cases += [(.213, -.665, 0., 'stopping'), (0., -.665, 0., 'stopping')]
|
||||
for tick, (speed, accel, pitch, state) in enumerate(cases):
|
||||
now = 1_000_000_000 + tick * 40_000_000
|
||||
out, sources = feed(ci, packer, now, counter=tick % 4, speed=speed)
|
||||
sources.append(packer.make_can_msg('ASCMActiveCruiseControlStatus', 2, {'ACCCruiseState': 3}))
|
||||
@@ -68,14 +69,15 @@ class TestBoltFactoryAcc(unittest.TestCase):
|
||||
control = structs.CarControl(enabled=True, longActive=cp.openpilotLongitudinalControl,
|
||||
orientationNED=[0., pitch, 0.])
|
||||
control.actuators.accel = accel
|
||||
control.actuators.longControlState = structs.CarControl.Actuators.LongControlState.pid
|
||||
control.actuators.longControlState = state
|
||||
ci.CC.frame = tick * 4
|
||||
_, messages = ci.apply(control.as_reader(), now)
|
||||
long_messages = [m for m in messages if m[0] in (0x2CB, 0x315, 0x2CD)]
|
||||
self.assertFalse(any(m[0] in (0x200, 0x1F5, 0xBD) for m in messages))
|
||||
if cp.openpilotLongitudinalControl:
|
||||
raw, brake = original_demand(cp, True, out.vEgo, accel, 'pid', False, pitch)
|
||||
self.assertEqual(long_messages, original_frames(raw, brake, tick % 4, True, False))
|
||||
raw, brake = original_demand(cp, True, out.vEgo, accel, state, False, pitch, standstill=out.standstill)
|
||||
full_stop = out.standstill and state == 'stopping'
|
||||
self.assertEqual(long_messages, original_frames(raw, brake, tick % 4, True, full_stop))
|
||||
for message in long_messages:
|
||||
self.assertTrue(native('tx', message, now // 1000), hex(message[0]))
|
||||
else:
|
||||
|
||||
@@ -337,6 +337,13 @@ class TestBoltPedalMessages(unittest.TestCase):
|
||||
self.assertTrue(state.pedal_sensor_healthy, gas)
|
||||
self.assertEqual(out.gasPressed, gas > 23., gas)
|
||||
|
||||
parsers[Bus.pt].update([(1_170_000_000, [self.sensor(packer, 30., 0, state=8)])])
|
||||
out = state.update(parsers)
|
||||
expected = candidate == CAR.CHEVROLET_BOLT_CC_2022_2023
|
||||
self.assertEqual(state.pedal_sensor_healthy, expected)
|
||||
if expected:
|
||||
self.assertTrue(out.gasPressed)
|
||||
|
||||
for counter, kwargs in ((9, {"state": 1}), (10, {"other_track": 1000.}), (11, {"bad_crc": True})):
|
||||
parsers[Bus.pt].update([(1_000_000_000 + counter * 20_000_000,
|
||||
[self.sensor(packer, 30., counter, **kwargs)])])
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
import json
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import patch
|
||||
|
||||
import pytest
|
||||
|
||||
from opendbc.car import car_helpers, structs
|
||||
from opendbc.car.can_definitions import CanData
|
||||
from opendbc.car.gm.values import CAR
|
||||
|
||||
VIN = '1G1RD6S50JU000001'
|
||||
RECORDED = Path(__file__).parent / 'testdata/volt_2018_ascm_fingerprint.json'
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def fingerprint():
|
||||
return {int(bus): {int(address): size for address, size in messages.items()}
|
||||
for bus, messages in json.loads(RECORDED.read_text()).items()}
|
||||
|
||||
|
||||
def receive(fingerprint):
|
||||
packets = [CanData(address, bytes(size), bus)
|
||||
for bus, messages in fingerprint.items() for address, size in messages.items()]
|
||||
return lambda **kwargs: [packets]
|
||||
|
||||
|
||||
def test_recorded_startup_selects_ascm_and_preserves_manual_override(fingerprint):
|
||||
fw = structs.CarParams.CarFw.new_message(brand='gm', logging=True)
|
||||
cache = SimpleNamespace(carFingerprint='MOCK', carVin=VIN, carFw=[fw], brand='mock')
|
||||
with patch.dict(car_helpers.os.environ, {'FINGERPRINT': '', 'SKIP_FW_QUERY': '', 'DISABLE_FW_CACHE': ''}), \
|
||||
patch.object(car_helpers, 'get_vin', return_value=(0x64B, 0, VIN)), \
|
||||
patch.object(car_helpers, 'get_fw_versions', return_value=[fw]):
|
||||
args = (receive(fingerprint), lambda _: None, lambda _: None, False, True)
|
||||
auto = car_helpers.get_car(*args, cached_params=cache).CP
|
||||
manual = car_helpers.get_car(*args, forced_candidate=CAR.CHEVROLET_VOLT).CP
|
||||
assert auto.carFingerprint == CAR.CHEVROLET_VOLT_ASCM
|
||||
assert auto.fingerprintSource == structs.CarParams.FingerprintSource.can
|
||||
assert auto.pcmCruise and not auto.openpilotLongitudinalControl and not auto.dashcamOnly
|
||||
assert auto.safetyConfigs[0].safetyParam == 0xE05
|
||||
assert manual.carFingerprint == CAR.CHEVROLET_VOLT
|
||||
assert manual.fingerprintSource == structs.CarParams.FingerprintSource.fixed
|
||||
|
||||
|
||||
@pytest.mark.parametrize('vin', ['0' * 17, '1G1RD6S50KU000001', '1G1FX6S50JU000001'])
|
||||
def test_layout_alone_does_not_match(fingerprint, vin):
|
||||
assert car_helpers.can_fingerprint(receive(fingerprint), vin=vin)[0] is None
|
||||
|
||||
|
||||
@pytest.mark.parametrize('bus,address,size', [(0, 0x2FF, 8), (0, 0x201, 6), (0, 0x320, 6),
|
||||
(2, 0x180, None), (1, 0x474, None)])
|
||||
def test_other_harness_or_control_sources_do_not_match(fingerprint, bus, address, size):
|
||||
for target in (0, 2) if bus == 0 else (bus,):
|
||||
if size is None:
|
||||
fingerprint[target].pop(address)
|
||||
else:
|
||||
fingerprint[target][address] = size
|
||||
assert car_helpers.can_fingerprint(receive(fingerprint), vin=VIN)[0] != CAR.CHEVROLET_VOLT_ASCM
|
||||
@@ -0,0 +1,5 @@
|
||||
{
|
||||
"0": {"189": 7, "193": 8, "197": 8, "201": 8, "209": 7, "211": 2, "241": 6, "298": 8, "304": 1, "308": 4, "309": 8, "311": 8, "313": 8, "320": 3, "328": 1, "352": 5, "381": 6, "384": 4, "386": 8, "388": 8, "451": 8, "452": 8, "453": 6, "479": 3, "481": 7, "485": 8, "489": 8, "493": 8, "497": 8, "500": 6, "501": 8, "528": 4, "532": 6, "560": 8, "562": 8, "563": 5, "565": 5, "566": 5, "608": 8, "609": 6, "610": 6, "611": 6, "612": 8, "613": 8, "707": 8, "715": 8, "717": 5, "761": 7, "767": 4, "810": 8, "840": 5, "842": 5, "844": 8, "869": 4, "880": 6, "977": 8, "1001": 8, "1017": 8, "1020": 8, "1033": 7, "1034": 7, "1217": 8, "1221": 5, "1233": 8, "1249": 8, "1265": 8, "1267": 1, "1280": 4, "1296": 4, "1300": 8, "1922": 7, "1930": 7},
|
||||
"1": {"161": 7, "262": 5, "309": 1, "768": 8, "771": 2, "774": 8, "776": 7, "784": 6, "848": 8, "849": 8, "850": 8, "851": 8, "852": 8, "853": 8, "854": 3, "1033": 7, "1034": 7, "1056": 6, "1057": 8, "1058": 8, "1059": 8, "1060": 8, "1061": 8, "1062": 8, "1063": 8, "1064": 8, "1065": 8, "1066": 8, "1067": 8, "1068": 8, "1088": 8, "1089": 8, "1090": 8, "1091": 8, "1092": 8, "1093": 8, "1094": 8, "1095": 8, "1096": 8, "1097": 8, "1098": 8, "1099": 8, "1100": 8, "1120": 8, "1121": 8, "1122": 8, "1123": 8, "1124": 8, "1125": 8, "1126": 8, "1127": 8, "1128": 8, "1129": 8, "1130": 8, "1131": 8, "1132": 8, "1133": 8, "1134": 8, "1135": 8, "1136": 8, "1137": 8, "1138": 8, "1139": 8, "1140": 8, "1141": 8, "1142": 8, "1143": 8, "1146": 8, "1147": 8, "1148": 8, "1149": 8, "1150": 8, "1151": 8, "1362": 8, "1857": 8, "1859": 8, "1920": 7},
|
||||
"2": {"189": 7, "193": 8, "197": 8, "201": 8, "209": 7, "211": 2, "241": 6, "298": 8, "304": 1, "308": 4, "309": 8, "311": 8, "313": 8, "320": 3, "328": 1, "352": 5, "381": 6, "384": 4, "386": 8, "388": 8, "451": 8, "452": 8, "453": 6, "479": 3, "481": 7, "485": 8, "489": 8, "493": 8, "497": 8, "500": 6, "501": 8, "528": 4, "532": 6, "560": 8, "562": 8, "563": 5, "565": 5, "566": 5, "608": 8, "609": 6, "610": 6, "611": 6, "612": 8, "613": 8, "707": 8, "715": 8, "717": 5, "761": 7, "767": 4, "810": 8, "840": 5, "842": 5, "844": 8, "869": 4, "880": 6, "977": 8, "1001": 8, "1017": 8, "1020": 8, "1033": 7, "1034": 7, "1217": 8, "1221": 5, "1233": 8, "1249": 8, "1265": 8, "1267": 1, "1280": 4, "1296": 4, "1300": 8, "1922": 7, "1930": 7}
|
||||
}
|
||||
@@ -951,6 +951,11 @@ def is_bolt_pedal_profile(cp, *, stock_only=False):
|
||||
return _bolt_pedal_profile(cp, stock_only=stock_only)
|
||||
|
||||
|
||||
def bolt_pedal_in_drive_requires_low(cp, gear):
|
||||
return (gear == 'drive' and getattr(cp, 'carFingerprint', None) in (CAR.CHEVROLET_BOLT_CC_2017, CAR.CHEVROLET_BOLT_CC_2018_2021) and
|
||||
is_bolt_pedal_profile(cp))
|
||||
|
||||
|
||||
@cached_config
|
||||
def _bolt_pedal_profile(cp, *, stock_only=False):
|
||||
"""Exact selected interceptor profile, including its startup authority reduction."""
|
||||
|
||||
@@ -7,14 +7,26 @@ NORMAL_BUS_LAYOUT = {(1, 0x158): 8, (1, 0x17C): 8, (1, 0x18F): 7,
|
||||
(1, 0x296): 4, (2, 0xE4): 5, (2, 0x400): 4}
|
||||
|
||||
|
||||
def normal_bus_topology(packets):
|
||||
# Nidec uses two SCM layouts and two EPS status lengths on normal bus 0.
|
||||
NIDEC_BUS0_COMMON = {(0, 0x158): 8, (0, 0x17C): 8}
|
||||
NIDEC_BUS0_LAYOUTS = (
|
||||
*({**NIDEC_BUS0_COMMON, (0, 0x18F): eps_length, (0, 0x1A6): 8, (0, 0x156): 6} for eps_length in (6, 7)),
|
||||
{**NIDEC_BUS0_COMMON, (0, 0x18F): 7, (0, 0x296): 4, (0, 0x326): 8},
|
||||
)
|
||||
|
||||
|
||||
def normal_bus_topology(packets, *, layout=NORMAL_BUS_LAYOUT):
|
||||
observed = set()
|
||||
for packet in packets:
|
||||
for frame in packet:
|
||||
key = (frame.src, frame.address)
|
||||
if key in NORMAL_BUS_LAYOUT:
|
||||
if (len(frame.dat) != NORMAL_BUS_LAYOUT[key] or
|
||||
if key in layout:
|
||||
if (len(frame.dat) != layout[key] or
|
||||
honda_checksum(frame.address, None, frame.dat) != frame.dat[-1] & 0xF):
|
||||
return False
|
||||
observed.add(key)
|
||||
return observed == NORMAL_BUS_LAYOUT.keys()
|
||||
return observed == layout.keys()
|
||||
|
||||
|
||||
def nidec_bus0_topology(packets):
|
||||
return any(normal_bus_topology(packets, layout=layout) for layout in NIDEC_BUS0_LAYOUTS)
|
||||
|
||||
@@ -186,7 +186,7 @@ class CANFDLfaStatus:
|
||||
return True
|
||||
return 0 < self.popup_last_applied_ns <= now_ns <= self.popup_last_applied_ns + DISPLAY_RELEASE_NS
|
||||
|
||||
def owns_ccnc_fault_status(self, now_ns, *, healthy=False, qualified_warning=False):
|
||||
def owns_ccnc_fault_status(self, now_ns, *, display_sample_ns, healthy=False, qualified_warning=False):
|
||||
body = self.current(now_ns)
|
||||
eps_fresh = 0 < self.eps_observed_ns <= now_ns and now_ns - self.eps_observed_ns <= MAX_AGE_NS
|
||||
indication = ((body[4] >> 6) | ((body[5] & 1) << 2)) if body is not None else 7
|
||||
@@ -198,7 +198,13 @@ class CANFDLfaStatus:
|
||||
if qualified_warning:
|
||||
self.ccnc_last_owned_ns = now_ns
|
||||
return True
|
||||
return 0 < self.ccnc_last_owned_ns <= now_ns <= self.ccnc_last_owned_ns + MAX_AGE_NS
|
||||
last_owned_ns = self.ccnc_last_owned_ns
|
||||
if not 0 < last_owned_ns <= now_ns:
|
||||
return False
|
||||
if now_ns - last_owned_ns <= MAX_AGE_NS:
|
||||
return True
|
||||
return (last_owned_ns <= display_sample_ns <= last_owned_ns + MAX_AGE_NS and
|
||||
display_sample_ns <= now_ns <= display_sample_ns + MAX_AGE_NS)
|
||||
|
||||
def last_fault(self):
|
||||
body = self.body
|
||||
|
||||
@@ -115,16 +115,47 @@ def qualified(cp, *, marked_only=False):
|
||||
SPORTAGE_LONG_AOL_WORDS = frozenset(0x0804 | fuel | topology for fuel in (0, 2) for topology in (0, 8, 16, 144, 32, 40))
|
||||
CARNIVAL_LONG_AOL_WORD = 0x28B4
|
||||
LONG_AOL_WORDS = frozenset((CARNIVAL_LONG_AOL_WORD, 0x080D, 0x0815, 0x0895, 0x2815, 0x2895)) | SPORTAGE_LONG_AOL_WORDS
|
||||
CCNC_LONG_CARS = frozenset((CAR.HYUNDAI_KONA_2ND_GEN, CAR.HYUNDAI_KONA_HEV_2ND_GEN))
|
||||
CCNC_LONG_AOL_WORDS = frozenset((0x0C0C, 0x0C0E, 0x0C2C, 0x0C2E))
|
||||
LONG_EV_CARS = frozenset((CAR.HYUNDAI_IONIQ_5, CAR.HYUNDAI_KONA_EV_2ND_GEN))
|
||||
LONG_AOL_WORDS |= CCNC_LONG_AOL_WORDS
|
||||
INDEPENDENT_LONG_BUTTON_CARS = LONG_EV_CARS | CCNC_LONG_CARS | {
|
||||
CAR.KIA_EV6, CAR.HYUNDAI_IONIQ_6, CAR.GENESIS_GV70_ELECTRIFIED_1ST_GEN,
|
||||
KONA_IDLE_AOL_WORD = 0x1C0C
|
||||
LONG_AOL_WORDS |= CCNC_LONG_AOL_WORDS | {KONA_IDLE_AOL_WORD}
|
||||
GENERIC_HDA2_CARS = frozenset((
|
||||
CAR.GENESIS_G80_2ND_GEN_FL,
|
||||
CAR.HYUNDAI_IONIQ_5_N,
|
||||
CAR.HYUNDAI_KONA_2ND_GEN,
|
||||
CAR.HYUNDAI_KONA_HEV_2ND_GEN,
|
||||
CAR.HYUNDAI_SANTA_CRUZ_1ST_GEN,
|
||||
CAR.HYUNDAI_SANTA_CRUZ_2025,
|
||||
CAR.HYUNDAI_SONATA_2024,
|
||||
CAR.HYUNDAI_SONATA_HEV_2024,
|
||||
CAR.HYUNDAI_STARIA_4TH_GEN,
|
||||
CAR.HYUNDAI_TUCSON_2025,
|
||||
CAR.HYUNDAI_TUCSON_4TH_GEN,
|
||||
CAR.HYUNDAI_TUCSON_HEV_2025,
|
||||
CAR.HYUNDAI_TUCSON_PHEV_2025,
|
||||
CAR.KIA_CARNIVAL_2025,
|
||||
CAR.KIA_CARNIVAL_HEV_4TH_GEN,
|
||||
CAR.KIA_K4_2025,
|
||||
CAR.KIA_K5_2025,
|
||||
CAR.KIA_K8_HEV_1ST_GEN,
|
||||
CAR.KIA_NIRO_EV_2ND_GEN,
|
||||
CAR.KIA_NIRO_HEV_2ND_GEN,
|
||||
CAR.KIA_SORENTO_2024,
|
||||
CAR.KIA_SPORTAGE_5TH_GEN,
|
||||
))
|
||||
|
||||
INDEPENDENT_LONG_BUTTON_CARS = LONG_EV_CARS | GENERIC_HDA2_CARS | {
|
||||
CAR.KIA_EV6, CAR.KIA_NIRO_EV_2ND_GEN, CAR.HYUNDAI_IONIQ_6, CAR.GENESIS_GV70_ELECTRIFIED_1ST_GEN,
|
||||
CAR.GENESIS_GV60_EV_1ST_GEN, CAR.KIA_SPORTAGE_5TH_GEN, CAR.KIA_CARNIVAL_2025,
|
||||
}
|
||||
|
||||
|
||||
def kona_idle_handoff_profile(cp):
|
||||
return (cp.carFingerprint == CAR.HYUNDAI_KONA_2ND_GEN and len(cp.safetyConfigs) == 1 and
|
||||
cp.alphaLongitudinalAvailable and cp.openpilotLongitudinalControl and not cp.pcmCruise and
|
||||
_base_word(cp, experiences=(0, 32)) == 0x408)
|
||||
|
||||
|
||||
def qualified_long(cp, *, marked_only=False):
|
||||
if cp.carFingerprint == CAR.KIA_EV6 and int(cp.flags) & _FLAG_CANFD_LKA_STEER_MSG:
|
||||
from opendbc.car.hyundai.ev6_aol import qualified as ev6_qualified
|
||||
@@ -139,15 +170,25 @@ def qualified_long(cp, *, marked_only=False):
|
||||
if cp.carFingerprint in (CAR.KIA_EV6, CAR.GENESIS_GV60_EV_1ST_GEN, CAR.HYUNDAI_IONIQ_6):
|
||||
if word != 0x09:
|
||||
return False
|
||||
elif cp.carFingerprint in CCNC_LONG_CARS:
|
||||
if word is None or word | 0x804 not in CCNC_LONG_AOL_WORDS:
|
||||
return False
|
||||
elif cp.carFingerprint == CAR.KIA_SPORTAGE_5TH_GEN:
|
||||
if word is None or word | 0x804 not in SPORTAGE_LONG_AOL_WORDS:
|
||||
return False
|
||||
elif cp.carFingerprint == CAR.KIA_CARNIVAL_2025:
|
||||
if word != 0x20B0:
|
||||
return False
|
||||
elif cp.carFingerprint == CAR.KIA_CARNIVAL_HEV_4TH_GEN:
|
||||
return False
|
||||
elif cp.carFingerprint in GENERIC_HDA2_CARS:
|
||||
if word is None or not cp.alphaLongitudinalAvailable:
|
||||
return False
|
||||
if word & 0x10:
|
||||
if len(cp.safetyConfigs) != 1 or word not in (0x10, 0x11, 0x12, 0x90, 0x91, 0x92):
|
||||
return False
|
||||
elif cp.carFingerprint == CAR.KIA_NIRO_EV_2ND_GEN:
|
||||
if word != 0x09:
|
||||
return False
|
||||
elif word not in (0x08, 0x0A, 0x28, 0x2A, 0x408, 0x40A, 0x428, 0x42A):
|
||||
return False
|
||||
elif word not in (0x11, 0x91) and not (cp.carFingerprint == CAR.HYUNDAI_IONIQ_5 and word == 0x09):
|
||||
return False
|
||||
raw = int(cp.safetyConfigs[config_index(cp)].safetyParam)
|
||||
@@ -155,6 +196,8 @@ def qualified_long(cp, *, marked_only=False):
|
||||
if not raw & 0x2000:
|
||||
return False
|
||||
raw &= ~0x2000
|
||||
if raw == KONA_IDLE_AOL_WORD:
|
||||
return cp.alternativeExperience == 32 and kona_idle_handoff_profile(cp)
|
||||
return (raw == (word | 0x804) and cp.alternativeExperience == 32) or (
|
||||
not marked_only and raw == (word | 4) and cp.alternativeExperience == 0
|
||||
)
|
||||
|
||||
@@ -31,6 +31,7 @@ from opendbc.car.hyundai.canfd_lfa_status import preserves_stock_lfa
|
||||
from opendbc.car.hyundai.classic_scc_aol import qualified as qualified_classic_stock_aol
|
||||
from opendbc.car.hyundai.classic_long_aol import AOL_EXPERIENCE, qualified as qualified_classic_long_aol
|
||||
from opendbc.car.hyundai.canfd_stock_aol import qualified as qualified_canfd_stock_aol, qualified_long as qualified_canfd_long_aol
|
||||
from opendbc.car.hyundai.canfd_stock_aol import KONA_IDLE_AOL_WORD
|
||||
from opendbc.car.hyundai.g90_longitudinal import G90LongitudinalPolicy
|
||||
from opendbc.car.hyundai.gv70_longitudinal import is_gv70, scc_request, suppress_stock_cancel
|
||||
from opendbc.car.hyundai.g90_lead import G90LeadState, eligible as g90_lead_eligible
|
||||
@@ -132,10 +133,16 @@ class CarController(CarControllerBase):
|
||||
self.apply_torque_last = 0
|
||||
self.car_fingerprint = CP.carFingerprint
|
||||
self.last_button_frame = 0
|
||||
from opendbc.car.hyundai.software_cruise import selected as software_cruise_selected
|
||||
self.software_cruise_enabled = software_cruise_selected(self.CP)
|
||||
self.software_cruise_command = 0
|
||||
self.software_cruise_command_ns = 0
|
||||
self.cancel_counter = 0
|
||||
self.blended_longitudinal = None
|
||||
self.blended_previous_lateral = False
|
||||
self.blended_disengage_frame = None
|
||||
self.blended_camera_sent_frame = -5
|
||||
self.blended_camera_sent_counter = None
|
||||
self.last_ccnc_161_ts_ns = 0
|
||||
self.last_ccnc_162_ts_ns = 0
|
||||
self.last_ccnc_now_ns = 0
|
||||
@@ -170,6 +177,7 @@ class CarController(CarControllerBase):
|
||||
int(CP.safetyConfigs[-1].safetyParam) in (0x0811, 0x0891))
|
||||
self.canfd_torque_aol_status = (qualified_canfd_stock_aol(CP) or qualified_canfd_long_aol(CP))
|
||||
self.ccnc_fault_ownership_required = preserves_stock_lfa(CP)
|
||||
self.kona_last_lfa_counter = None
|
||||
self.canfd_dash_icons = CanFDDashIcons() if ioniq6_status or self.canfd_torque_aol_status else None
|
||||
self.classic_dash_icons = CanFDDashIcons() if classic_aol_dash_enabled(CP) else None
|
||||
self.classic_lfa_icon = None
|
||||
@@ -294,6 +302,16 @@ class CarController(CarControllerBase):
|
||||
can_sends.extend(self.create_can_msgs(apply_steer_req, apply_torque, torque_fault, set_speed_in_units, accel,
|
||||
stopping, hud_control, actuators, CS, CC, lead_data=lead_data))
|
||||
|
||||
if (self.software_cruise_enabled and self.cancel_counter <= CANCEL_BUTTON_DELAY_FRAMES and
|
||||
not CC.cruiseControl.resume and not CC.cruiseControl.cancel and not CC.cruiseControl.override):
|
||||
command = self.software_cruise_command
|
||||
if (command in (1, 2) and self.software_cruise_command_ns == now_nanos and
|
||||
(self.frame - self.last_button_frame) * DT_CTRL > 0.10):
|
||||
button = Buttons.RES_ACCEL if command == 1 else Buttons.SET_DECEL
|
||||
can_sends.append(hyundaican.create_clu11(self.packer, self.frame, CS.clu11, button, self.CP))
|
||||
if (self.frame - self.last_button_frame) * DT_CTRL >= 0.15:
|
||||
self.last_button_frame = self.frame
|
||||
|
||||
new_actuators = actuators.as_builder()
|
||||
new_actuators.torque = apply_torque / self.params.STEER_MAX
|
||||
new_actuators.torqueOutputCan = apply_torque
|
||||
@@ -338,9 +356,15 @@ class CarController(CarControllerBase):
|
||||
sys_warning, sys_state, CC.enabled, hud_control.leftLaneVisible, hud_control.rightLaneVisible,
|
||||
left_lane_warning, right_lane_warning, {}, include_alerts=False, counter_mod=0xF,
|
||||
fcw_opt_usm=2 if apply_steer_req or icon == 3 else 1))
|
||||
if (self.frame % 5 == 0 and CS.out.canValid and not CS.out.canTimeout and
|
||||
CS.blended_camera_current):
|
||||
can_sends.append(hyundaicanfd.create_suppress_lfa(self.packer, self.CAN, CS.lfa_block_msg, False))
|
||||
if CS.out.canValid and not CS.out.canTimeout and CS.blended_camera_current:
|
||||
camera_counter = CS.lfa_block_msg["COUNTER"]
|
||||
if (self.frame - self.blended_camera_sent_frame >= 5 and camera_counter != self.blended_camera_sent_counter and
|
||||
(not CC.latActive or CS.blended_camera_updated)):
|
||||
can_sends.append(hyundaicanfd.create_suppress_lfa(self.packer, self.CAN, CS.lfa_block_msg, False))
|
||||
self.blended_camera_sent_frame = self.frame
|
||||
self.blended_camera_sent_counter = camera_counter
|
||||
else:
|
||||
self.blended_camera_sent_counter = None
|
||||
else:
|
||||
_projection_packet_index = len(can_sends) if _projection is not None else 0
|
||||
can_sends.extend(hyundaican.create_lkas11_can_canfd_blended(
|
||||
@@ -552,17 +576,29 @@ class CarController(CarControllerBase):
|
||||
stock_popup_owned = stock_source.owns_disengage_popup(apply_steer_req, clock_boot_ns(), healthy=display_healthy,
|
||||
qualified_warning=stock_owned_status)
|
||||
if ccnc_non_lka:
|
||||
stock_ccnc_owned = stock_source.owns_ccnc_fault_status(clock_boot_ns(), healthy=display_healthy,
|
||||
qualified_warning=stock_owned_status)
|
||||
stock_ccnc_owned = stock_source.owns_ccnc_fault_status(clock_boot_ns(), display_sample_ns=CS.ccnc_162_ts_ns,
|
||||
healthy=display_healthy, qualified_warning=stock_owned_status)
|
||||
damping_source = getattr(CS, "stock_lkas_damping", None)
|
||||
can_sends.extend(hyundaicanfd.create_steering_messages(self.packer, self.CP, self.CAN,
|
||||
steering_status_active, apply_steer_req, apply_torque,
|
||||
stock_lfa=stock_lfa, stock_lfa_faults=stock_faults,
|
||||
stock_lfa_owned_status=stock_owned_status,
|
||||
stock_lkas_damping=(damping_source.current_damping(clock_boot_ns())
|
||||
if damping_source is not None else None)))
|
||||
if _projection is not None:
|
||||
_projection.emit('hyundai.CANFD_TORQUE', apply_torque, apply_steer_req, can_sends[-1])
|
||||
kona_handoff = (self.CP.carFingerprint == CAR.HYUNDAI_KONA_2ND_GEN and
|
||||
self.CP.safetyConfigs[-1].safetyParam == KONA_IDLE_AOL_WORD)
|
||||
lfa_counter = None
|
||||
if kona_handoff:
|
||||
if (CC.enabled or CC.latActive) and stock_lfa is not None:
|
||||
if stock_lfa[2] != self.kona_last_lfa_counter:
|
||||
lfa_counter = stock_lfa[2]
|
||||
self.kona_last_lfa_counter = lfa_counter
|
||||
else:
|
||||
self.kona_last_lfa_counter = None
|
||||
if not kona_handoff or lfa_counter is not None:
|
||||
can_sends.extend(hyundaicanfd.create_steering_messages(self.packer, self.CP, self.CAN,
|
||||
steering_status_active, apply_steer_req, apply_torque,
|
||||
stock_lfa=stock_lfa, stock_lfa_faults=stock_faults,
|
||||
stock_lfa_owned_status=stock_owned_status,
|
||||
stock_lkas_damping=(damping_source.current_damping(clock_boot_ns())
|
||||
if damping_source is not None else None),
|
||||
lfa_counter=lfa_counter))
|
||||
if _projection is not None:
|
||||
_projection.emit('hyundai.CANFD_TORQUE', apply_torque, apply_steer_req, can_sends[-1])
|
||||
|
||||
# prevent LFA from activating on LKA steering cars by sending "no lane lines detected" to ADAS ECU
|
||||
if (
|
||||
|
||||
@@ -150,6 +150,7 @@ class CarState(CarStateBase):
|
||||
|
||||
self.params = CarControllerParams(CP)
|
||||
self.blended_camera_current = False
|
||||
self.blended_camera_updated = False
|
||||
self.ray_pedal_valid = False
|
||||
self.ray_pedal_state = 5
|
||||
|
||||
@@ -347,6 +348,7 @@ class CarState(CarStateBase):
|
||||
self.lfa_block_msg = copy.copy(cp_cam.vl["CAM_0x2a4"])
|
||||
from opendbc.car.hyundai.blended_stock_aol import camera_current
|
||||
self.blended_camera_current = camera_current(cp_cam)
|
||||
self.blended_camera_updated = bool(cp_cam.vl_all["CAM_0x2a4"]["COUNTER"])
|
||||
self.lkas11 = {}
|
||||
else:
|
||||
self.msg_364 = copy.copy(cp_cam.vl["ALERTS_364"])
|
||||
|
||||
@@ -22,6 +22,11 @@ HDA2_NORMAL_BUS_LAYOUT = {(2, 0x50): 16, (2, 0x2A4): 24, (1, 0x35): 32, (1, 0xEA
|
||||
(1, 0xA0): 24, (1, 0x1A0): 32, (1, 0x1CF): 8, (1, 0x130): 16}
|
||||
|
||||
|
||||
MIXED_CAN_NORMAL_BUS_LAYOUT = {(2, 0x50): 16, (2, 0x2A4): 24, (0, 0x251): 16,
|
||||
(1, 0x251): 8, (1, 0x386): 8, (1, 0x394): 8,
|
||||
(1, 0x4F1): 4, (1, 0x420): 8, (1, 0x421): 8}
|
||||
|
||||
|
||||
QUIET_CAMERA_NORMAL_BUS_LAYOUT = {(0, 0xEA): 24, (0, 0xA0): 24, (0, 0x1A0): 32, (0, 0x60): 32,
|
||||
(0, 0x35): 32, (0, 0x1CF): 8, (0, 0x130): 16,
|
||||
**{(1, address): 32 for address in range(0x210, 0x220)}}
|
||||
@@ -59,8 +64,9 @@ def normal_bus_topology(can_recv, *, clock=time.monotonic):
|
||||
hda2_invalid = False
|
||||
hda1_observed = {}
|
||||
hda1_invalid = False
|
||||
variants_observed = [{} for _ in CANFD_VARIANT_LAYOUTS]
|
||||
variants_invalid = [False for _ in CANFD_VARIANT_LAYOUTS]
|
||||
alternate_layouts = (*CANFD_VARIANT_LAYOUTS, MIXED_CAN_NORMAL_BUS_LAYOUT)
|
||||
variants_observed = [{} for _ in alternate_layouts]
|
||||
variants_invalid = [False for _ in alternate_layouts]
|
||||
for _ in range(24):
|
||||
if clock() >= deadline:
|
||||
break
|
||||
@@ -76,7 +82,7 @@ def normal_bus_topology(can_recv, *, clock=time.monotonic):
|
||||
return False
|
||||
original_invalid = True
|
||||
received[key] = length
|
||||
for index, layout in enumerate(CANFD_VARIANT_LAYOUTS):
|
||||
for index, layout in enumerate(alternate_layouts):
|
||||
if key in layout:
|
||||
if len(frame.dat) != layout[key]:
|
||||
variants_invalid[index] = True
|
||||
@@ -98,6 +104,6 @@ def normal_bus_topology(can_recv, *, clock=time.monotonic):
|
||||
not hda1_invalid and hda1_observed == HDA1_NORMAL_BUS_LAYOUT)):
|
||||
return True
|
||||
if any(not invalid and received == layout and (not original_invalid or (2, 0x50) in layout)
|
||||
for layout, received, invalid in zip(CANFD_VARIANT_LAYOUTS, variants_observed, variants_invalid, strict=True)):
|
||||
for layout, received, invalid in zip(alternate_layouts, variants_observed, variants_invalid, strict=True)):
|
||||
return True
|
||||
return False
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
"""Exact Forte non-SCC AOL identity and physical-button observations."""
|
||||
from opendbc.car.structs import CarParams
|
||||
from opendbc.car.hyundai.values import CAR, HyundaiFlags
|
||||
from opendbc.car.hyundai.non_scc_aol import SOFTWARE_CRUISE
|
||||
|
||||
FORTE_IDS = (CAR.KIA_FORTE_2019_NON_SCC, CAR.KIA_FORTE_2021_NON_SCC)
|
||||
FORTE_AOL_MARKER = 0x0400
|
||||
@@ -19,8 +20,10 @@ def qualified(cp):
|
||||
not cp.notCar and not cp.openpilotLongitudinalControl and cp.pcmCruise and
|
||||
bool(cp.flags & HyundaiFlags.NON_SCC) and not int(cp.flags) & ~int(allowed_flags) and
|
||||
len(cp.safetyConfigs) == 1 and cp.safetyConfigs[0].safetyModel == CarParams.SafetyModel.hyundai and
|
||||
cp.safetyConfigs[0].safetyParam in words)
|
||||
(cp.safetyConfigs[0].safetyParam & ~SOFTWARE_CRUISE) in words)
|
||||
|
||||
|
||||
# Keep the public Forte fixture/provider API while sharing the same state machine.
|
||||
from opendbc.car.hyundai.non_scc_aol import NonSccLkasSources as ForteLkasSources
|
||||
from opendbc.car.hyundai.non_scc_aol import NonSccLkasSources
|
||||
|
||||
ForteLkasSources = NonSccLkasSources
|
||||
|
||||
@@ -2,37 +2,12 @@ from copy import deepcopy
|
||||
from typing import Any
|
||||
import time
|
||||
|
||||
from opendbc.car.hyundai.canfd_stock_aol import qualified as stock_qualified, qualified_long
|
||||
from opendbc.car.hyundai.canfd_stock_aol import GENERIC_HDA2_CARS as CARS, qualified as stock_qualified, qualified_long
|
||||
from opendbc.car.hyundai.ecu_continuity import ContinuousECUStartup, StartupKeeper
|
||||
from opendbc.car.hyundai.ecu_startup import Outcome, stock_copy
|
||||
from opendbc.car.hyundai.radar_hda2_startup import RadarHDA2Startup
|
||||
from opendbc.car.hyundai.values import CAR, HyundaiFlags, is_blended
|
||||
|
||||
CARS = frozenset((
|
||||
CAR.GENESIS_G80_2ND_GEN_FL,
|
||||
CAR.HYUNDAI_IONIQ_5_N,
|
||||
CAR.HYUNDAI_KONA_2ND_GEN,
|
||||
CAR.HYUNDAI_KONA_HEV_2ND_GEN,
|
||||
CAR.HYUNDAI_SANTA_CRUZ_1ST_GEN,
|
||||
CAR.HYUNDAI_SANTA_CRUZ_2025,
|
||||
CAR.HYUNDAI_SONATA_2024,
|
||||
CAR.HYUNDAI_SONATA_HEV_2024,
|
||||
CAR.HYUNDAI_STARIA_4TH_GEN,
|
||||
CAR.HYUNDAI_TUCSON_2025,
|
||||
CAR.HYUNDAI_TUCSON_4TH_GEN,
|
||||
CAR.HYUNDAI_TUCSON_HEV_2025,
|
||||
CAR.HYUNDAI_TUCSON_PHEV_2025,
|
||||
CAR.KIA_CARNIVAL_2025,
|
||||
CAR.KIA_CARNIVAL_HEV_4TH_GEN,
|
||||
CAR.KIA_K4_2025,
|
||||
CAR.KIA_K5_2025,
|
||||
CAR.KIA_K8_HEV_1ST_GEN,
|
||||
CAR.KIA_NIRO_EV_2ND_GEN,
|
||||
CAR.KIA_NIRO_HEV_2ND_GEN,
|
||||
CAR.KIA_SORENTO_2024,
|
||||
CAR.KIA_SPORTAGE_5TH_GEN,
|
||||
))
|
||||
|
||||
EXISTING_OWNERS_OR_DISTINCT_RECEIVERS = frozenset((
|
||||
CAR.HYUNDAI_KONA_EV_2ND_GEN,
|
||||
CAR.HYUNDAI_IONIQ_5,
|
||||
|
||||
@@ -45,7 +45,7 @@ LFA_FAULT_MASK = bytes.fromhex("00000000c001c0f00000000000000000")
|
||||
|
||||
|
||||
def create_steering_messages(packer, CP, CAN, enabled, lat_active, apply_torque, *, stock_lfa=None, stock_lfa_faults=None,
|
||||
stock_lkas_damping=None, stock_lfa_owned_status=False):
|
||||
stock_lkas_damping=None, stock_lfa_owned_status=False, lfa_counter=None):
|
||||
values = {
|
||||
"LKA_OptUsmSta": 2,
|
||||
"LKA_SysIndReq": 2 if enabled else 1,
|
||||
@@ -73,6 +73,8 @@ def create_steering_messages(packer, CP, CAN, enabled, lat_active, apply_torque,
|
||||
lkas_values = {**values, "Damping_Gain": damping}
|
||||
ret.append(packer.make_can_msg(lkas_msg, CAN.ACAN, lkas_values))
|
||||
else:
|
||||
if lfa_counter is not None:
|
||||
values["COUNTER"] = lfa_counter
|
||||
message = packer.make_can_msg("LFA", CAN.ECAN, values)
|
||||
source = stock_lfa if stock_lfa is not None else stock_lfa_faults
|
||||
if source is not None:
|
||||
|
||||
@@ -12,6 +12,7 @@ NON_SCC_IDS = frozenset((CAR.HYUNDAI_BAYON_1ST_GEN_NON_SCC, CAR.HYUNDAI_ELANTRA_
|
||||
CAR.HYUNDAI_ELANTRA_HEV_2022_NON_SCC, CAR.HYUNDAI_KONA_NON_SCC, CAR.HYUNDAI_KONA_EV_NON_SCC,
|
||||
CAR.KIA_CEED_PHEV_2022_NON_SCC, CAR.KIA_FORTE_2019_NON_SCC, CAR.KIA_FORTE_2021_NON_SCC,
|
||||
CAR.KIA_SELTOS_2023_NON_SCC, CAR.GENESIS_G70_2021_NON_SCC))
|
||||
SOFTWARE_CRUISE = 0x0020
|
||||
AOL_MARKER = 0x0400
|
||||
AOL_EXPERIENCE = 32
|
||||
AOL_WORDS = frozenset((0x1400, 0x1c00, 0x1440, 0x1c40, 0x1441, 0x1c41, 0x1402, 0x1c02))
|
||||
@@ -47,11 +48,11 @@ def qualified(cp):
|
||||
# ordinary safety may still use its original MAIN-only profile.
|
||||
ordinary = word & ~int(HyundaiSafetyFlags.HAS_LDA_BUTTON)
|
||||
return (safety.safetyModel == structs.CarParams.SafetyModel.hyundai and
|
||||
safety.safetyParam in (word, ordinary, word | AOL_MARKER))
|
||||
(safety.safetyParam & ~SOFTWARE_CRUISE) in (word, ordinary, word | AOL_MARKER))
|
||||
|
||||
|
||||
def aol_word(cp):
|
||||
return stock_word(cp) | AOL_MARKER
|
||||
return stock_word(cp) | AOL_MARKER | (cp.safetyConfigs[0].safetyParam & SOFTWARE_CRUISE)
|
||||
|
||||
|
||||
SOURCE_MAX_AGE_NS = 300_000_000
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
"""Conventional cruise button control for exact classic Hyundai profiles."""
|
||||
|
||||
from opendbc.car.hyundai.non_scc_aol import SOFTWARE_CRUISE, qualified
|
||||
|
||||
|
||||
def eligible(cp):
|
||||
return cp is not None and qualified(cp)
|
||||
|
||||
|
||||
def selected(cp):
|
||||
return (cp is not None and cp.brand == 'hyundai' and len(cp.safetyConfigs) == 1 and
|
||||
bool(cp.safetyConfigs[0].safetyParam & SOFTWARE_CRUISE) and eligible(cp))
|
||||
|
||||
|
||||
def prepare(cp, enabled):
|
||||
if enabled and eligible(cp):
|
||||
cp.safetyConfigs[0].safetyParam |= SOFTWARE_CRUISE
|
||||
return cp
|
||||
@@ -67,7 +67,10 @@ class TestBlendedSender(unittest.TestCase):
|
||||
command.actuators.longControlState = structs.CarControl.Actuators.LongControlState.pid
|
||||
command.hudControl.setSpeed = 25.0
|
||||
for frame in range(32):
|
||||
actuators, messages = ci.apply(command.as_reader(), 2_000_000_000 + frame * 10_000_000)
|
||||
tick = 16 + frame
|
||||
camera = 16 + frame // 5 if frame % 5 == 0 else False
|
||||
feed(ci, tick, camera=camera)
|
||||
actuators, messages = ci.apply(command.as_reader(), 1_000_000_000 + tick * 10_000_000)
|
||||
wanted = []
|
||||
if frame % 100 == 0:
|
||||
wanted.append((0x730 if hdaii else 0x7D0, int(hdaii)))
|
||||
@@ -90,6 +93,8 @@ class TestBlendedSender(unittest.TestCase):
|
||||
wanted.append((0x485, 1))
|
||||
self.assertEqual([(address, bus) for address, _, bus in messages], wanted)
|
||||
packets = {address: data for address, data, _ in messages}
|
||||
if hdaii and frame % 5 == 0:
|
||||
self.assertEqual(decode(ci, 0x2A4, packets[0x2A4], 'COUNTER'), camera)
|
||||
for address, data, _ in messages:
|
||||
if address not in (0x730, 0x7D0, 0x50, 0x51, 0x2A4):
|
||||
self.assertEqual(data[0], hyundai_checksum(data[1:8]), hex(address))
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
from opendbc.car import gen_empty_fingerprint
|
||||
from opendbc.car.hyundai.canfd_stock_aol import qualified_long
|
||||
from opendbc.car.hyundai.interface import CarInterface
|
||||
from opendbc.car.hyundai.values import CAR
|
||||
from openpilot.starpilot.car.hyundai.aol import native_accepts_cp, policy_for
|
||||
from openpilot.starpilot.ui.wheel_feature import WheelFeature
|
||||
|
||||
|
||||
@pytest.mark.parametrize('identity, hybrid, base', [
|
||||
(CAR.HYUNDAI_TUCSON_4TH_GEN, False, 0x08),
|
||||
(CAR.KIA_NIRO_HEV_2ND_GEN, True, 0x0A),
|
||||
(CAR.HYUNDAI_SONATA_2024, False, 0x408),
|
||||
(CAR.HYUNDAI_SONATA_HEV_2024, True, 0x40A),
|
||||
(CAR.KIA_K4_2025, False, 0x408),
|
||||
])
|
||||
@pytest.mark.parametrize('alternate', [False, True])
|
||||
@pytest.mark.parametrize('offset', [0, 4])
|
||||
def test_camera_scc_wheel_choice_survives_alpha_long(identity, hybrid, base, alternate, offset):
|
||||
fp = gen_empty_fingerprint()
|
||||
fp[offset].update({0x35: 32, 0xA0: 24, 0xEA: 24, 0x175: 24, 0x130: 16})
|
||||
fp[offset + 2].update({0x12A: 16, 0x1A0: 32})
|
||||
fp[offset][0x1AA if alternate else 0x1CF] = 16 if alternate else 8
|
||||
if hybrid:
|
||||
fp[offset][0xFA] = 8
|
||||
|
||||
for alpha in (False, True):
|
||||
cp = CarInterface.get_params(identity, fp, [], alpha, False, False)
|
||||
assert cp.alphaLongitudinalAvailable and cp.openpilotLongitudinalControl == alpha
|
||||
assert not CarInterface.startup_required(cp)
|
||||
wheel = WheelFeature(SimpleNamespace(params=SimpleNamespace(get_bool=lambda key: key == 'AlwaysOnLateral'),
|
||||
vehicle_params=lambda cp=cp: cp, configuration_vehicle=lambda: False,
|
||||
configuration_longitudinal=lambda: False, longitudinal_available=lambda alpha=alpha: alpha,
|
||||
authority=lambda _: True))
|
||||
assert 'Toggle AOL' in wheel.choices('LKASButtonControl')
|
||||
assert 'Toggle AOL' in wheel.choices('MainCruiseButtonControl')
|
||||
if alpha:
|
||||
config = cp.safetyConfigs[offset // 4]
|
||||
assert config.safetyParam == base | (0x20 if alternate else 0) | 4
|
||||
assert qualified_long(cp)
|
||||
policy = policy_for(cp)
|
||||
config.safetyParam |= policy.safety_param_addition
|
||||
cp.alternativeExperience |= policy.alternative_experience_addition
|
||||
assert config.safetyParam == base | (0x20 if alternate else 0) | 0x804
|
||||
assert native_accepts_cp(cp, config.safetyModel.raw, config.safetyParam)
|
||||
cp.alternativeExperience = 0
|
||||
assert not qualified_long(cp, marked_only=True)
|
||||
@@ -931,7 +931,7 @@ def test_ccnc_normal_camera_handover_requires_current_health_and_expires(failure
|
||||
eps = packer.make_can_msg('MDPS', 0, {'COUNTER': tick, 'MDPS_LkaToiActvSta': int(tick >= 4)})
|
||||
source.update([(clock[0], [eps, camera])])
|
||||
owned = source.owns_display_status(tick >= 2, clock[0], healthy=True)
|
||||
assert source.owns_ccnc_fault_status(clock[0], healthy=True, qualified_warning=owned) == owned
|
||||
assert source.owns_ccnc_fault_status(clock[0], display_sample_ns=clock[0], healthy=True, qualified_warning=owned) == owned
|
||||
assert owned
|
||||
final_owned_ns = clock[0]
|
||||
for tick in range(16, 23):
|
||||
@@ -952,7 +952,7 @@ def test_ccnc_normal_camera_handover_requires_current_health_and_expires(failure
|
||||
frames.append(camera)
|
||||
source.update([(clock[0], frames)])
|
||||
now = final_owned_ns - 1 if failure == 'backward' else -1 if failure == 'negative' else clock[0]
|
||||
held = source.owns_ccnc_fault_status(now, healthy=failure != 'host_fault',
|
||||
held = source.owns_ccnc_fault_status(now, display_sample_ns=clock[0], healthy=failure != 'host_fault',
|
||||
qualified_warning=failure == 'stale_camera_qualified')
|
||||
if failure == 'expired':
|
||||
assert held == (clock[0] - final_owned_ns <= 50_000_000)
|
||||
@@ -965,7 +965,29 @@ def test_ccnc_normal_camera_handover_requires_current_health_and_expires(failure
|
||||
camera = template(packer, 2, tick)
|
||||
eps = packer.make_can_msg('MDPS', 0, {'COUNTER': tick})
|
||||
source.update([(clock[0], [eps, camera])])
|
||||
assert not source.owns_ccnc_fault_status(clock[0], healthy=True, qualified_warning=False)
|
||||
assert not source.owns_ccnc_fault_status(clock[0], display_sample_ns=clock[0], healthy=True, qualified_warning=False)
|
||||
|
||||
|
||||
def test_ccnc_handover_uses_fresh_display_sample_time(clock):
|
||||
packer = CANPacker(DBC[CAR.HYUNDAI_KONA_2ND_GEN][Bus.pt])
|
||||
source = CANFDLfaStatus(2)
|
||||
for tick in range(21):
|
||||
clock[0] = 51_000_000_000 + tick * 10_000_000
|
||||
camera = template(packer, 2, tick, warning=15 if 14 <= tick < 16 else 0)
|
||||
eps = packer.make_can_msg('MDPS', 0, {'COUNTER': tick, 'MDPS_LkaToiActvSta': int(tick >= 4)})
|
||||
source.update([(clock[0], [eps, camera])])
|
||||
owned = source.owns_display_status(tick >= 2, clock[0], healthy=True)
|
||||
if owned:
|
||||
assert source.owns_ccnc_fault_status(clock[0], display_sample_ns=clock[0], healthy=True, qualified_warning=True)
|
||||
|
||||
assert not owned
|
||||
now = clock[0] + 1_000_000
|
||||
assert source.owns_ccnc_fault_status(now, display_sample_ns=clock[0] - 40_000_000, healthy=True)
|
||||
assert not source.owns_ccnc_fault_status(now, display_sample_ns=clock[0] - 50_000_000, healthy=True)
|
||||
assert not source.owns_ccnc_fault_status(now, display_sample_ns=source.ccnc_last_owned_ns - 1, healthy=True)
|
||||
assert not source.owns_ccnc_fault_status(now, display_sample_ns=now, healthy=True)
|
||||
assert not source.owns_ccnc_fault_status(now, display_sample_ns=now + 1, healthy=True)
|
||||
assert not source.owns_ccnc_fault_status(now, display_sample_ns=clock[0] - 40_000_000, healthy=False)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('fault', range(1, 8))
|
||||
|
||||
@@ -12,6 +12,7 @@ from opendbc.car.hyundai.ecu_startup import Outcome, stock_copy
|
||||
from opendbc.car.hyundai.interface import CarInterface
|
||||
from opendbc.car.hyundai.ioniq6_handoff import TimestampedCanPacket
|
||||
from opendbc.car.hyundai.generic_hda2_startup import GenericHDA2Startup, qualified
|
||||
from openpilot.starpilot.ui.feature_settings_owner import FeatureSettingsOwner
|
||||
from opendbc.car.hyundai.tests.test_generic_hda2_startup import FUEL_CASES
|
||||
from opendbc.car.hyundai.values import CAR
|
||||
from opendbc.safety.tests.libsafety import libsafety_py
|
||||
@@ -183,7 +184,7 @@ def actual_card_lifecycle(identity, hybrid, alternate, gear, mode, aol):
|
||||
assert {key: saved.get(key) for key in keys} == settings and not saved.get_bool("ControlsReady")
|
||||
if mode == "rejected" and aol:
|
||||
expected.safetyConfigs[0].safetyParam |= 0x800
|
||||
elif mode == "sent" and aol and identity == CAR.KIA_SPORTAGE_5TH_GEN:
|
||||
elif mode == "sent" and aol and identity not in (CAR.KIA_CARNIVAL_2025, CAR.KIA_CARNIVAL_HEV_4TH_GEN):
|
||||
expected.safetyConfigs[0].safetyParam |= 0x800
|
||||
expected.alternativeExperience = 32
|
||||
assert card.CP.to_dict() == expected.to_dict()
|
||||
@@ -195,6 +196,11 @@ def actual_card_lifecycle(identity, hybrid, alternate, gear, mode, aol):
|
||||
assert commands == [b"\x10\x03", b"\x28\x83\x01"] and owner.keeper.running
|
||||
assert owner.outcome is Outcome.SENT_UNCONFIRMED and not owner.restored
|
||||
cp = card.CP
|
||||
if aol and (mode == "rejected" or cp.alternativeExperience == 32):
|
||||
features = FeatureSettingsOwner(saved, lambda _: True, vehicle_fingerprint=lambda: str(cp.carFingerprint), vehicle_params=lambda: cp)
|
||||
page = features.snapshot('wheel', parked=True, system_long=True, lateral_context=True, metric=False)
|
||||
row = next(row for row in page.rows if row.key == 'wheel:LKASButtonControl')
|
||||
assert 'Toggle AOL' in row.choices
|
||||
config = cp.safetyConfigs[0]
|
||||
native.set_alternative_experience(cp.alternativeExperience)
|
||||
assert native.set_safety_hooks(int(config.safetyModel.raw), int(config.safetyParam)) == 0
|
||||
|
||||
@@ -8,12 +8,15 @@ from opendbc.car.hyundai.values import CAR, HyundaiFlags
|
||||
from openpilot.starpilot.car.hyundai.aol import independent_cruise_buttons_supported, native_accepts_cp, policy_for
|
||||
|
||||
|
||||
def camera_long(offset, alpha=True):
|
||||
CAMERA_LONG_CARS = (CAR.HYUNDAI_IONIQ_5, CAR.KIA_NIRO_EV_2ND_GEN)
|
||||
|
||||
|
||||
def camera_long(offset, alpha=True, *, identity=CAR.HYUNDAI_IONIQ_5):
|
||||
fp = gen_empty_fingerprint()
|
||||
fp[offset].update({0x1CF: 8, 0x35: 32, 0x175: 24, 0xA0: 24, 0xEA: 24, 0x1BA: 24, 0x1E5: 16})
|
||||
fp[offset + 2].update({0x12A: 16, 0x1A0: 32})
|
||||
fp[offset + 1].update({0x110: 32, 0x100: 24})
|
||||
cp = CarInterface.get_params(CAR.HYUNDAI_IONIQ_5, fp, [], alpha, False, False)
|
||||
cp = CarInterface.get_params(identity, fp, [], alpha, False, False)
|
||||
assert cp.openpilotLongitudinalControl and not cp.pcmCruise
|
||||
assert cp.flags & HyundaiFlags.CANFD_CAMERA_SCC
|
||||
assert not cp.flags & HyundaiFlags.CANFD_LKA_STEER_MSG
|
||||
@@ -23,8 +26,9 @@ def camera_long(offset, alpha=True):
|
||||
|
||||
|
||||
@pytest.mark.parametrize('offset', [0, 4])
|
||||
def test_factory_ioniq5_camera_long_uses_existing_paired_axis_profile(offset):
|
||||
cp = camera_long(offset)
|
||||
@pytest.mark.parametrize('identity', CAMERA_LONG_CARS)
|
||||
def test_factory_camera_long_uses_existing_paired_axis_profile(identity, offset):
|
||||
cp = camera_long(offset, identity=identity)
|
||||
before = cp.to_dict()
|
||||
assert qualified_long(cp)
|
||||
assert independent_cruise_buttons_supported(cp)
|
||||
@@ -44,9 +48,10 @@ def test_factory_ioniq5_camera_long_uses_existing_paired_axis_profile(offset):
|
||||
|
||||
|
||||
@pytest.mark.parametrize('offset', [0, 4])
|
||||
@pytest.mark.parametrize('mutation', ['alternate_buttons', 'unknown_word', 'wrong_experience', 'passive', 'angle'])
|
||||
def test_camera_long_extension_keeps_unrecognized_contracts_closed(offset, mutation):
|
||||
cp = camera_long(offset)
|
||||
@pytest.mark.parametrize('mutation', ['alternate_buttons', 'unknown_word', 'wrong_experience', 'passive', 'angle', 'hda2'])
|
||||
@pytest.mark.parametrize('identity', CAMERA_LONG_CARS)
|
||||
def test_camera_long_extension_keeps_unrecognized_contracts_closed(identity, offset, mutation):
|
||||
cp = camera_long(offset, identity=identity)
|
||||
owner = config_index(cp)
|
||||
cp.safetyConfigs[owner].safetyParam = 0x80D
|
||||
cp.alternativeExperience = 32
|
||||
@@ -59,18 +64,23 @@ def test_camera_long_extension_keeps_unrecognized_contracts_closed(offset, mutat
|
||||
cp.alternativeExperience = 0
|
||||
elif mutation == 'passive':
|
||||
cp.passive = True
|
||||
else:
|
||||
elif mutation == 'angle':
|
||||
cp.flags |= int(HyundaiFlags.CANFD_ANGLE_STEERING)
|
||||
assert not qualified_long(cp, marked_only=True)
|
||||
elif mutation == 'hda2':
|
||||
cp.flags = (cp.flags & ~int(HyundaiFlags.CANFD_CAMERA_SCC)) | int(HyundaiFlags.CANFD_LKA_STEER_MSG)
|
||||
cp.safetyConfigs[owner].safetyParam = 0x815
|
||||
cp.alphaLongitudinalAvailable = False
|
||||
assert qualified_long(cp, marked_only=True) == (mutation == 'hda2' and identity == CAR.HYUNDAI_IONIQ_5)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('offset', [0, 4])
|
||||
@pytest.mark.parametrize('button', ['lkas', 'mainCruise'])
|
||||
def test_default_physical_button_arms_and_brake_cancel_keep_intent(offset, button):
|
||||
@pytest.mark.parametrize('identity', CAMERA_LONG_CARS)
|
||||
def test_default_physical_button_arms_and_brake_cancel_keep_intent(identity, offset, button):
|
||||
from openpilot.starpilot.aol.intent import AolSettings
|
||||
from openpilot.starpilot.car.hyundai.aol import create_intent
|
||||
|
||||
cp = camera_long(offset)
|
||||
cp = camera_long(offset, identity=identity)
|
||||
cp.safetyConfigs[config_index(cp)].safetyParam = 0x80D
|
||||
cp.alternativeExperience = 32
|
||||
settings = AolSettings(enabled=True, pause_brake_mps=0.0, lkas_action=0, main_action=0,
|
||||
@@ -96,7 +106,7 @@ def test_default_physical_button_arms_and_brake_cancel_keep_intent(offset, butto
|
||||
assert not intent.output(cs)[0]
|
||||
|
||||
|
||||
@pytest.mark.parametrize('identity', [CAR.HYUNDAI_KONA_EV_2ND_GEN, CAR.HYUNDAI_IONIQ_5_N, CAR.KIA_NIRO_EV_2ND_GEN])
|
||||
@pytest.mark.parametrize('identity', [CAR.HYUNDAI_KONA_EV_2ND_GEN, CAR.HYUNDAI_IONIQ_5_N, CAR.KIA_NIRO_HEV_2ND_GEN])
|
||||
def test_camera_extension_does_not_admit_unqualified_identities(identity):
|
||||
cp = camera_long(0)
|
||||
cp.carFingerprint = identity
|
||||
@@ -108,15 +118,17 @@ def test_camera_extension_does_not_admit_unqualified_identities(identity):
|
||||
|
||||
@pytest.mark.parametrize('offset', [0, 4])
|
||||
@pytest.mark.parametrize('enabled', [False, True])
|
||||
def test_actual_card_marks_camera_owner_with_recorded_default_buttons(offset, enabled):
|
||||
@pytest.mark.parametrize('identity', CAMERA_LONG_CARS)
|
||||
def test_actual_card_marks_camera_owner_with_recorded_default_buttons(identity, offset, enabled):
|
||||
import os
|
||||
from unittest.mock import patch
|
||||
from opendbc.car.hyundai.radar_interface import RadarInterface
|
||||
from openpilot.common.params import Params
|
||||
from openpilot.common.prefix import OpenpilotPrefix
|
||||
from openpilot.selfdrive.car.card import Car
|
||||
from openpilot.starpilot.ui.feature_settings_owner import FeatureSettingsOwner
|
||||
|
||||
cp = camera_long(offset)
|
||||
cp = camera_long(offset, identity=identity)
|
||||
with OpenpilotPrefix(), patch.dict(os.environ, {'SIMULATION': '1'}):
|
||||
saved = Params()
|
||||
saved.put_bool('OpenpilotEnabledToggle', True, block=True)
|
||||
@@ -135,6 +147,11 @@ def test_actual_card_marks_camera_owner_with_recorded_default_buttons(offset, en
|
||||
assert qualified_long(published, marked_only=enabled)
|
||||
assert config_index(published) == offset // 4
|
||||
assert not CarInterface.startup_required(published)
|
||||
features = FeatureSettingsOwner(saved, lambda _: True, vehicle_fingerprint=lambda: str(published.carFingerprint),
|
||||
vehicle_params=lambda: published)
|
||||
page = features.snapshot('wheel', parked=True, system_long=True, lateral_context=True, metric=False)
|
||||
row = next(row for row in page.rows if row.key == 'wheel:LKASButtonControl')
|
||||
assert 'Toggle AOL' in row.choices
|
||||
assert card.aol_qualified == enabled
|
||||
if enabled:
|
||||
assert card.aol_card_intent.explicit_latch and card.aol_card_intent.independent_cruise_buttons
|
||||
|
||||
@@ -37,9 +37,10 @@ def test_factory_ccnc_alpha_admits_only_matching_owner(car, alternate, offset):
|
||||
assert qualified_long(cp) and independent_cruise_buttons_supported(cp)
|
||||
policy = policy_for(cp)
|
||||
assert policy.intent_supported and policy.runtime_supported and policy.explicit_latch
|
||||
assert policy.safety_param_addition == 0x800 and policy.alternative_experience_addition == 32
|
||||
expected = 0x800
|
||||
assert policy.safety_param_addition == expected and policy.alternative_experience_addition == 32
|
||||
assert cp.to_dict() == original
|
||||
word = int(cp.safetyConfigs[-1].safetyParam) | 0x800
|
||||
word = int(cp.safetyConfigs[-1].safetyParam) | expected
|
||||
cp.safetyConfigs[-1].safetyParam = word
|
||||
cp.alternativeExperience = 32
|
||||
assert qualified_long(cp, marked_only=True)
|
||||
@@ -199,3 +200,29 @@ def test_wheel_choices_keep_aol_with_either_longitudinal_owner(car, alternate, a
|
||||
feature = WheelFeature(Owner())
|
||||
assert 'Toggle AOL' in feature.choices('LKASButtonControl')
|
||||
assert 'Toggle AOL' in feature.choices('MainCruiseButtonControl')
|
||||
|
||||
|
||||
def test_idle_handoff_omits_only_kona_steering_packet():
|
||||
reference_cp = kona_params(CARS[0])
|
||||
handoff_cp = kona_params(CARS[0])
|
||||
for cp, word in ((reference_cp, 0x0C0C), (handoff_cp, 0x1C0C)):
|
||||
cp.safetyConfigs[0].safetyParam = word
|
||||
cp.alternativeExperience = 32
|
||||
reference, candidate = CarInterface(reference_cp), CarInterface(handoff_cp)
|
||||
source = Mock()
|
||||
source.owns_display_status.return_value = False
|
||||
candidate.CS.stock_lfa_status = source
|
||||
states = ((False, False, 10), (True, True, 11), (False, True, 11), (True, False, 12),
|
||||
(True, True, None), (False, False, 13), (True, True, 14))
|
||||
expected_counters = (None, 11, None, 12, None, None, 14)
|
||||
for (enabled, lateral, camera_counter), expected in zip(states, expected_counters, strict=True):
|
||||
if camera_counter is None:
|
||||
source.current.return_value = None
|
||||
else:
|
||||
source.current.return_value = bytes([0, 0, camera_counter] + [0] * 13)
|
||||
ctrl = structs.CarControl(enabled=enabled, latActive=lateral).as_reader()
|
||||
_, before = reference.apply(ctrl, 1_000_000_000)
|
||||
_, after = candidate.apply(ctrl, 1_000_000_000)
|
||||
assert [frame for frame in after if frame[0] != 0x12A] == [frame for frame in before if frame[0] != 0x12A]
|
||||
assert any(frame[0] == 0x12A for frame in before)
|
||||
assert [data[2] for addr, data, _ in after if addr == 0x12A] == ([] if expected is None else [expected])
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
from unittest.mock import patch
|
||||
|
||||
import pytest
|
||||
|
||||
from opendbc.car.can_definitions import CanData
|
||||
from opendbc.car.car_helpers import fingerprint
|
||||
from opendbc.car.hyundai.discovery import normal_bus_topology
|
||||
from opendbc.car.vin import VIN_UNKNOWN
|
||||
|
||||
|
||||
def mixed_can_frames():
|
||||
return [CanData(addr, bytes(length), bus) for bus, addr, length in (
|
||||
(0, 0x251, 16), (2, 0x50, 16), (2, 0x2A4, 24),
|
||||
(1, 0x251, 8), (1, 0x386, 8), (1, 0x394, 8), (1, 0x4F1, 4), (1, 0x420, 8), (1, 0x421, 8),
|
||||
)]
|
||||
|
||||
|
||||
@pytest.mark.parametrize('index', range(9))
|
||||
@pytest.mark.parametrize('defect', ['missing', 'length', 'bus', 'echo', 'contradiction'])
|
||||
def test_mixed_can_probe_requires_consistent_physical_sources(index, defect):
|
||||
frames = mixed_can_frames()
|
||||
original = frames.pop(index)
|
||||
if defect in ('length', 'contradiction'):
|
||||
frames.append(CanData(original.address, original.dat[:-1], original.src))
|
||||
if defect == 'contradiction':
|
||||
frames.append(original)
|
||||
elif defect in ('bus', 'echo'):
|
||||
frames.append(CanData(original.address, original.dat, original.src + (128 if defect == 'echo' else 1)))
|
||||
assert not normal_bus_topology(lambda **kwargs: [frames])
|
||||
|
||||
|
||||
def test_mixed_can_probe_spans_can_reads():
|
||||
frames = iter([frame] for frame in mixed_can_frames())
|
||||
assert normal_bus_topology(lambda **kwargs: [next(frames, [])], clock=lambda: 0.)
|
||||
|
||||
|
||||
def test_mixed_can_fingerprint_keeps_fresh_queries_on_normal_wiring():
|
||||
switches = []
|
||||
with patch('opendbc.car.car_helpers.get_vin', return_value=(-1, -1, VIN_UNKNOWN)) as vin, \
|
||||
patch('opendbc.car.car_helpers.get_fw_versions', return_value=[]) as query, \
|
||||
patch('opendbc.car.car_helpers.get_present_ecus', return_value=set()) as present, \
|
||||
patch('opendbc.car.car_helpers.get_fw_versions_ordered', return_value=[]) as generic, \
|
||||
patch('opendbc.car.car_helpers.can_fingerprint', return_value=(None, {})):
|
||||
result = fingerprint(lambda **kwargs: [mixed_can_frames()], lambda packets: None, switches.append, None)
|
||||
assert result[0] is None
|
||||
assert switches and not any(switches)
|
||||
vin.assert_called_once()
|
||||
assert vin.call_args.args[2] == (0, 1)
|
||||
query.assert_called_once()
|
||||
assert query.call_args.kwargs == {'query_brand': 'hyundai', 'normal_bus_only': True}
|
||||
present.assert_not_called()
|
||||
generic.assert_not_called()
|
||||
@@ -23,13 +23,17 @@ def params(topology='hdai', *, adas=False, alpha=False, release=False):
|
||||
return CarInterface.get_params(CAR.HYUNDAI_PALISADE_2023, fp, fw, alpha, release, False)
|
||||
|
||||
|
||||
def feed(ci, tick, *, main=True, cruise=1, display=0, gas=False, brake=False, torque=0):
|
||||
def feed(ci, tick, *, main=True, cruise=1, display=0, gas=False, brake=False, torque=0, camera=True):
|
||||
packer = CANPacker(DBC[ci.CP.carFingerprint][Bus.pt])
|
||||
messages = []
|
||||
for parser in ci.can_parsers.values():
|
||||
for address in parser.addresses:
|
||||
if address == 0x2A4 and camera is False:
|
||||
continue
|
||||
message = parser.dbc.addr_to_msg[address]
|
||||
values = {'COUNTER': tick % 16} if 'COUNTER' in message.sigs else {}
|
||||
if address == 0x2A4 and type(camera) is int:
|
||||
values['COUNTER'] = camera
|
||||
if message.name == 'SCC12':
|
||||
values.update(MainMode_ACC=int(main), ACCMode=cruise, SCCInfoDisplay=display, VSetDis=90)
|
||||
elif message.name == 'EMS16':
|
||||
@@ -100,13 +104,14 @@ class TestPalisade2023(unittest.TestCase):
|
||||
command.hudControl.setSpeed = 25.
|
||||
previous = 0
|
||||
for tick in range(20):
|
||||
feed(ci, tick + 12, camera=12 + (tick + 3) // 5 if tick == 0 or tick % 5 == 2 else False)
|
||||
actuators, messages = ci.apply(command.as_reader(), 1_200_000_000 + tick * 10_000_000)
|
||||
self.assertEqual(actuators.torqueOutputCan - previous, 3 if topology == 'hdaii' else 2)
|
||||
previous = actuators.torqueOutputCan
|
||||
addresses = {a for a, _, _ in messages}
|
||||
self.assertFalse(addresses & {0x420, 0x421, 0x389, 0x7D0, 0x730})
|
||||
if topology == 'hdaii':
|
||||
self.assertEqual(addresses, {0x50, 0x2A4} if tick % 5 == 0 else {0x50})
|
||||
self.assertEqual(addresses, {0x50, 0x2A4} if tick in (0, 7, 12, 17) else {0x50})
|
||||
self.assertTrue(all(bus == 0 for _, _, bus in messages))
|
||||
else:
|
||||
self.assertEqual(addresses, {0x340, 0x364})
|
||||
@@ -123,6 +128,37 @@ class TestPalisade2023(unittest.TestCase):
|
||||
actuators, _ = ci.apply(command.as_reader(), 1_500_000_000)
|
||||
self.assertEqual(actuators.torqueOutputCan, 0)
|
||||
|
||||
def test_hda2_camera_copy_skips_samples_that_miss_the_send_slot(self):
|
||||
ci = CarInterface(params('hdaii'))
|
||||
for tick in range(12):
|
||||
feed(ci, tick)
|
||||
command = structs.CarControl(enabled=True, latActive=True)
|
||||
copied = []
|
||||
for frame in range(20):
|
||||
tick = frame + 12
|
||||
feed(ci, tick, camera={0: 12, 4: 13, 9: 14, 14: 15, 19: 16}.get(frame, False))
|
||||
_, messages = ci.apply(command.as_reader(), 1_000_000_000 + tick * 10_000_000)
|
||||
copied.extend((frame, data[2]) for address, data, _ in messages if address == 0x2A4)
|
||||
self.assertEqual(copied, [(0, 12), (9, 14), (14, 15), (19, 16)])
|
||||
|
||||
def test_hda2_alpha_long_keeps_primary_steering_payload(self):
|
||||
from opendbc.car.hyundai.blended_longitudinal import candidate_from_stock
|
||||
|
||||
stock = params('hdaii')
|
||||
alpha = candidate_from_stock(stock, alpha_requested=True, native_qualified=True)
|
||||
self.assertTrue(alpha.openpilotLongitudinalControl)
|
||||
interfaces = [CarInterface(cp) for cp in (stock, alpha)]
|
||||
command = structs.CarControl(enabled=True, latActive=True)
|
||||
command.actuators.torque = .25
|
||||
for tick in range(12):
|
||||
steering = []
|
||||
for ci in interfaces:
|
||||
feed(ci, tick)
|
||||
_, messages = ci.apply(command.as_reader(), 1_000_000_000 + tick * 10_000_000)
|
||||
steering.append(next((data, bus) for address, data, bus in messages if address == 0x50))
|
||||
self.assertEqual(steering[0], steering[1])
|
||||
self.assertEqual(steering[0][0][8], 0)
|
||||
|
||||
def test_cancel_resume_route_to_exact_pt_bus_and_sibling_params_unchanged(self):
|
||||
for topology in ('hdai', 'hdaii'):
|
||||
ci = CarInterface(params(topology))
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
# Legacy Mazda powertrain and camera traffic selects diagnostic wiring only.
|
||||
# Identification still requires the normal live firmware/CAN match.
|
||||
NORMAL_BUS0_LAYOUT = {(0, 0x09D), (0, 0x165), (0, 0x202),
|
||||
(0, 0x21C), (0, 0x240), (2, 0x243)}
|
||||
|
||||
|
||||
def normal_bus0_topology(packets):
|
||||
seen = set()
|
||||
for packet in packets:
|
||||
for frame in packet:
|
||||
key = (frame.src, frame.address)
|
||||
if key in NORMAL_BUS0_LAYOUT:
|
||||
if len(frame.dat) != 8:
|
||||
return False
|
||||
seen.add(key)
|
||||
return seen == NORMAL_BUS0_LAYOUT
|
||||
@@ -78,6 +78,7 @@ FW_VERSIONS = {
|
||||
b'PX2G-188K2-D\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00',
|
||||
b'PX2H-188K2-B\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00',
|
||||
b'PX2H-188K2-D\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00',
|
||||
b'PX2H-188K2-E\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00',
|
||||
b'PX2H-188K2-G\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00',
|
||||
b'PX2K-188K2-B\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00',
|
||||
b'PX38-188K2-B\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00',
|
||||
|
||||
@@ -7,6 +7,20 @@ from opendbc.car.mazda.carstate import CarState
|
||||
from opendbc.car.mazda.values import CAR, LKAS_LIMITS
|
||||
|
||||
|
||||
_CX5_EPS_SWAP_FW = {
|
||||
('engine', 0x7E0): b'PX2H-188K2-E'.ljust(24, b'\x00'),
|
||||
('transmission', 0x7E1): b'PYB2-21PS1-G'.ljust(24, b'\x00'),
|
||||
('eps', 0x730): b'KSD5-3210X-C-00'.ljust(24, b'\x00'),
|
||||
}
|
||||
|
||||
|
||||
def _has_cx5_eps_swap(car_fw):
|
||||
observed = {(str(fw.ecu), fw.address, bytes(fw.fwVersion)) for fw in car_fw
|
||||
if fw.brand == 'mazda' and fw.bus == 0 and fw.subAddress == 0 and not fw.logging and
|
||||
(str(fw.ecu), fw.address) in _CX5_EPS_SWAP_FW}
|
||||
return observed == {(ecu, address, version) for (ecu, address), version in _CX5_EPS_SWAP_FW.items()}
|
||||
|
||||
|
||||
class CarInterface(CarInterfaceBase):
|
||||
CarState = CarState
|
||||
CarController = CarController
|
||||
@@ -18,14 +32,16 @@ class CarInterface(CarInterfaceBase):
|
||||
ret.radarUnavailable = True
|
||||
ret.deprecated.enableBsm = True
|
||||
|
||||
ret.dashcamOnly = candidate not in (CAR.MAZDA_CX5_2022, CAR.MAZDA_CX9_2021)
|
||||
ret.dashcamOnly = candidate not in (CAR.MAZDA_CX5, CAR.MAZDA_CX5_2022, CAR.MAZDA_CX9_2021)
|
||||
|
||||
ret.steerActuatorDelay = 0.1
|
||||
ret.steerLimitTimer = 0.8
|
||||
|
||||
CarInterfaceBase.configure_torque_tune(candidate, ret.lateralTuning)
|
||||
|
||||
if candidate not in (CAR.MAZDA_CX5_2022,):
|
||||
eps_swap = candidate == CAR.MAZDA_CX5 and _has_cx5_eps_swap(car_fw)
|
||||
# Both low-speed profiles still use the EPS LKAS_BLOCK signal in CarState.
|
||||
if candidate != CAR.MAZDA_CX5_2022 and not eps_swap:
|
||||
ret.minSteerSpeed = LKAS_LIMITS.DISABLE_SPEED * CV.KPH_TO_MS
|
||||
|
||||
ret.centerToFront = ret.wheelbase * 0.41
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
from opendbc.car import structs
|
||||
from opendbc.car.mazda.values import CAR, MazdaFlags
|
||||
|
||||
CARS = frozenset((CAR.MAZDA_CX5_2022, CAR.MAZDA_CX9_2021))
|
||||
CARS = frozenset((CAR.MAZDA_CX5, CAR.MAZDA_CX5_2022, CAR.MAZDA_CX9_2021))
|
||||
|
||||
|
||||
def qualified(cp, *, marked_only=False):
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
import pytest
|
||||
|
||||
from opendbc.can import CANPacker
|
||||
from opendbc.car import gen_empty_fingerprint, structs
|
||||
from opendbc.car.mazda.interface import CarInterface
|
||||
from opendbc.car.mazda.stock_aol import temporary_restriction
|
||||
from opendbc.car.mazda.tests.test_stock_startup import complete_frames
|
||||
from opendbc.car.mazda.values import CAR
|
||||
|
||||
|
||||
def recorded_firmware():
|
||||
return [structs.CarParams.CarFw(ecu=ecu, address=address, brand='mazda', fwVersion=part.ljust(24, b'\x00'))
|
||||
for ecu, address, part in (
|
||||
('engine', 0x7E0, b'PX2H-188K2-E'),
|
||||
('transmission', 0x7E1, b'PYB2-21PS1-G'),
|
||||
('eps', 0x730, b'KSD5-3210X-C-00'),
|
||||
)]
|
||||
|
||||
|
||||
@pytest.mark.parametrize('profile,defect,expected', [
|
||||
(CAR.MAZDA_CX5, None, 0.),
|
||||
(CAR.MAZDA_CX5, 'missing_eps', 12.5),
|
||||
(CAR.MAZDA_CX5, 'missing_engine', 12.5),
|
||||
(CAR.MAZDA_CX5, 'wrong_transmission', 12.5),
|
||||
(CAR.MAZDA_CX5, 'wrong_eps_bus', 12.5),
|
||||
(CAR.MAZDA_CX5, 'conflicting_eps', 12.5),
|
||||
(CAR.MAZDA_CX5_2022, 'no_fw', 0.),
|
||||
(CAR.MAZDA_CX9_2021, None, 12.5),
|
||||
])
|
||||
def test_low_speed_eligibility_is_limited_to_verified_cx5(profile, defect, expected):
|
||||
fw = recorded_firmware()
|
||||
if defect == 'missing_eps':
|
||||
del fw[2]
|
||||
elif defect == 'missing_engine':
|
||||
del fw[0]
|
||||
elif defect == 'wrong_transmission':
|
||||
fw[1].fwVersion = b'unknown'
|
||||
elif defect == 'wrong_eps_bus':
|
||||
fw[2].bus = 1
|
||||
elif defect == 'conflicting_eps':
|
||||
fw.append(structs.CarParams.CarFw(ecu='eps', address=0x730, brand='mazda', fwVersion=b'unknown'))
|
||||
elif defect == 'no_fw':
|
||||
fw.clear()
|
||||
cp = CarInterface.get_params(profile, gen_empty_fingerprint(), fw, False, False, False)
|
||||
assert cp.minSteerSpeed == expected
|
||||
assert cp.pcmCruise and not cp.openpilotLongitudinalControl and not cp.dashcamOnly
|
||||
assert [(str(s.safetyModel), s.safetyParam) for s in cp.safetyConfigs] == [('mazda', 0)]
|
||||
|
||||
|
||||
def test_eps_readiness_still_blocks_lateral_at_low_speed():
|
||||
cp = CarInterface.get_params(CAR.MAZDA_CX5, gen_empty_fingerprint(), recorded_firmware(), False, False, False)
|
||||
cp.alternativeExperience = 32
|
||||
ci = CarInterface(cp)
|
||||
packer = CANPacker('mazda_2017')
|
||||
ci.update([(10_000_000, complete_frames(packer, cp, 1, main=True, speed_kph=16., temporary=True))])
|
||||
for tick, (speed, blocked, restricted) in enumerate(((16., True, True), (16., False, False),
|
||||
(16., True, True), (0., False, True)), 2):
|
||||
frames = complete_frames(packer, cp, tick, main=True, speed_kph=speed, temporary=blocked)
|
||||
state = ci.update([(tick * 10_000_000, frames)])
|
||||
assert state.canValid and not state.canTimeout
|
||||
assert state.steerFaultTemporary == blocked
|
||||
assert temporary_restriction(cp, state) == restricted
|
||||
@@ -8,7 +8,7 @@ from opendbc.car.mazda.values import CAR, DBC
|
||||
from opendbc.car.mazda.tests.test_stock_startup import complete_frames, exercise_startup
|
||||
from openpilot.starpilot.car.mazda import dashboard
|
||||
|
||||
SUPPORTED = (CAR.MAZDA_CX5_2022, CAR.MAZDA_CX9_2021)
|
||||
SUPPORTED = (CAR.MAZDA_CX5, CAR.MAZDA_CX5_2022, CAR.MAZDA_CX9_2021)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('identity', list(CAR))
|
||||
|
||||
@@ -14,17 +14,17 @@ from opendbc.car.mazda.values import CAR, DBC
|
||||
from opendbc.car.mazda.tests.test_stock_startup import complete_frames, exercise_startup
|
||||
|
||||
|
||||
@pytest.mark.parametrize('identity', (CAR.MAZDA_CX5_2022, CAR.MAZDA_CX9_2021))
|
||||
@pytest.mark.parametrize('identity', (CAR.MAZDA_CX5, CAR.MAZDA_CX5_2022, CAR.MAZDA_CX9_2021))
|
||||
def test_ordinary_engagement_brake_actual_family_callers(identity, monkeypatch):
|
||||
_exercise_actual_family_callers(identity, monkeypatch)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('identity', (CAR.MAZDA_CX5_2022, CAR.MAZDA_CX9_2021))
|
||||
@pytest.mark.parametrize('identity', (CAR.MAZDA_CX5, CAR.MAZDA_CX5_2022, CAR.MAZDA_CX9_2021))
|
||||
def test_unassigned_cancel_retains_lateral_main_off_revokes_actual_callers(identity, monkeypatch):
|
||||
_exercise_actual_family_callers(identity, monkeypatch, scenario='cancel', cancel_action=0)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('identity', (CAR.MAZDA_CX5_2022, CAR.MAZDA_CX9_2021))
|
||||
@pytest.mark.parametrize('identity', (CAR.MAZDA_CX5, CAR.MAZDA_CX5_2022, CAR.MAZDA_CX9_2021))
|
||||
def test_longitudinal_cancel_assignment_keeps_lateral_actual_callers(identity, monkeypatch):
|
||||
_exercise_actual_family_callers(identity, monkeypatch, scenario='long_cancel', cancel_action=4)
|
||||
|
||||
@@ -59,29 +59,29 @@ extern "C" bool mazda_test_armed(const unsigned char *data, size_t size, uint64_
|
||||
yield armed
|
||||
|
||||
|
||||
@pytest.mark.parametrize('identity', (CAR.MAZDA_CX5_2022, CAR.MAZDA_CX9_2021))
|
||||
@pytest.mark.parametrize('identity', (CAR.MAZDA_CX5, CAR.MAZDA_CX5_2022, CAR.MAZDA_CX9_2021))
|
||||
def test_reverse_return_retains_lateral_actual_callers(identity, monkeypatch, armed_intent_decoder):
|
||||
_exercise_actual_family_callers(identity, monkeypatch, scenario='reverse', armed_intent=armed_intent_decoder)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('identity', (CAR.MAZDA_CX5_2022, CAR.MAZDA_CX9_2021))
|
||||
@pytest.mark.parametrize('identity', (CAR.MAZDA_CX5, CAR.MAZDA_CX5_2022, CAR.MAZDA_CX9_2021))
|
||||
def test_standstill_return_retains_lateral_actual_callers(identity, monkeypatch, armed_intent_decoder):
|
||||
_exercise_actual_family_callers(identity, monkeypatch, scenario='standstill', armed_intent=armed_intent_decoder)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('identity', (CAR.MAZDA_CX5_2022, CAR.MAZDA_CX9_2021))
|
||||
@pytest.mark.parametrize('identity', (CAR.MAZDA_CX5, CAR.MAZDA_CX5_2022, CAR.MAZDA_CX9_2021))
|
||||
def test_permanent_fault_while_stopped_disarms_actual_callers(identity, monkeypatch, armed_intent_decoder):
|
||||
_exercise_actual_family_callers(identity, monkeypatch, scenario='stop_fault', armed_intent=armed_intent_decoder)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('identity', (CAR.MAZDA_CX5_2022, CAR.MAZDA_CX9_2021))
|
||||
@pytest.mark.parametrize('identity', (CAR.MAZDA_CX5, CAR.MAZDA_CX5_2022, CAR.MAZDA_CX9_2021))
|
||||
@pytest.mark.parametrize('cancel_action', (3, 9))
|
||||
def test_mapped_cancel_pause_and_toggle_actual_callers(identity, cancel_action, monkeypatch, armed_intent_decoder):
|
||||
_exercise_actual_family_callers(identity, monkeypatch, scenario='mapped_cancel', cancel_action=cancel_action,
|
||||
armed_intent=armed_intent_decoder)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('identity', (CAR.MAZDA_CX5_2022, CAR.MAZDA_CX9_2021))
|
||||
@pytest.mark.parametrize('identity', (CAR.MAZDA_CX5, CAR.MAZDA_CX5_2022, CAR.MAZDA_CX9_2021))
|
||||
@pytest.mark.parametrize('lateral_only', (False, True))
|
||||
def test_eps_recovery_actual_callers(identity, lateral_only, monkeypatch, armed_intent_decoder):
|
||||
_exercise_actual_family_callers(identity, monkeypatch, scenario='temporary', lateral_only=lateral_only,
|
||||
@@ -489,23 +489,23 @@ def _exercise_actual_family_callers(identity, monkeypatch, *, scenario='brake',
|
||||
mapping=(0, 0) if scenario in ('startup', 'startup_stopped') else (9, 9))
|
||||
|
||||
|
||||
@pytest.mark.parametrize('identity', (CAR.MAZDA_CX5_2022, CAR.MAZDA_CX9_2021))
|
||||
@pytest.mark.parametrize('identity', (CAR.MAZDA_CX5, CAR.MAZDA_CX5_2022, CAR.MAZDA_CX9_2021))
|
||||
def test_main_already_on_startup_actual_callers(identity, monkeypatch, armed_intent_decoder):
|
||||
_exercise_actual_family_callers(identity, monkeypatch, scenario='startup', cancel_action=9, armed_intent=armed_intent_decoder)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('identity', (CAR.MAZDA_CX5_2022, CAR.MAZDA_CX9_2021))
|
||||
@pytest.mark.parametrize('identity', (CAR.MAZDA_CX5, CAR.MAZDA_CX5_2022, CAR.MAZDA_CX9_2021))
|
||||
def test_main_on_startup_respects_button_managed_aol(identity, monkeypatch, armed_intent_decoder):
|
||||
_exercise_actual_family_callers(identity, monkeypatch, scenario='startup_managed', armed_intent=armed_intent_decoder)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('identity', (CAR.MAZDA_CX5_2022, CAR.MAZDA_CX9_2021))
|
||||
@pytest.mark.parametrize('identity', (CAR.MAZDA_CX5, CAR.MAZDA_CX5_2022, CAR.MAZDA_CX9_2021))
|
||||
def test_main_on_startup_stopped_then_drive_actual_callers(identity, monkeypatch, armed_intent_decoder):
|
||||
_exercise_actual_family_callers(identity, monkeypatch, scenario='startup_stopped', cancel_action=9,
|
||||
armed_intent=armed_intent_decoder)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('identity', (CAR.MAZDA_CX5_2022, CAR.MAZDA_CX9_2021))
|
||||
@pytest.mark.parametrize('identity', (CAR.MAZDA_CX5, CAR.MAZDA_CX5_2022, CAR.MAZDA_CX9_2021))
|
||||
def test_main_on_startup_disabled_aol_actual_card_controls_native(identity, monkeypatch):
|
||||
from openpilot.cereal import messaging
|
||||
from openpilot.selfdrive.car import card as card_module
|
||||
@@ -566,19 +566,19 @@ def test_main_on_startup_disabled_aol_actual_card_controls_native(identity, monk
|
||||
exercise_startup(identity, False, False, False, monkeypatch, probe=probe)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('identity', (CAR.MAZDA_CX5_2022, CAR.MAZDA_CX9_2021))
|
||||
@pytest.mark.parametrize('identity', (CAR.MAZDA_CX5, CAR.MAZDA_CX5_2022, CAR.MAZDA_CX9_2021))
|
||||
@pytest.mark.parametrize('warning', ('calibrationInvalid', 'lowMemory', 'processNotRunning', 'radarTempUnavailable'))
|
||||
def test_ordinary_warning_retains_intent_actual_callers(identity, warning, monkeypatch, armed_intent_decoder):
|
||||
_exercise_actual_family_callers(identity, monkeypatch, scenario='warning', warning=warning, armed_intent=armed_intent_decoder)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('identity', (CAR.MAZDA_CX5_2022, CAR.MAZDA_CX9_2021))
|
||||
@pytest.mark.parametrize('identity', (CAR.MAZDA_CX5, CAR.MAZDA_CX5_2022, CAR.MAZDA_CX9_2021))
|
||||
@pytest.mark.parametrize('scenario', ('mapped_cancel', 'temporary'))
|
||||
def test_unbelted_lateral_pause_recovery_actual_callers(identity, scenario, monkeypatch, armed_intent_decoder):
|
||||
_exercise_actual_family_callers(identity, monkeypatch, scenario=scenario, cancel_action=3,
|
||||
armed_intent=armed_intent_decoder, unbelted=True)
|
||||
|
||||
@pytest.mark.parametrize('identity', (CAR.MAZDA_CX5_2022, CAR.MAZDA_CX9_2021))
|
||||
@pytest.mark.parametrize('identity', (CAR.MAZDA_CX5, CAR.MAZDA_CX5_2022, CAR.MAZDA_CX9_2021))
|
||||
@pytest.mark.parametrize('warning', ('calibrationInvalid', 'lowMemory', 'processNotRunning', 'radarTempUnavailable'))
|
||||
def test_active_ordinary_warning_retains_intent_actual_callers(identity, warning, monkeypatch, armed_intent_decoder):
|
||||
_exercise_actual_family_callers(identity, monkeypatch, scenario='warning_active', warning=warning, armed_intent=armed_intent_decoder)
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
from unittest.mock import patch
|
||||
|
||||
import pytest
|
||||
|
||||
from opendbc.car.can_definitions import CanData
|
||||
from opendbc.car.car_helpers import fingerprint
|
||||
from opendbc.car.mazda.values import CAR
|
||||
from opendbc.car.structs import CarParams
|
||||
from opendbc.car.vin import VIN_UNKNOWN
|
||||
|
||||
|
||||
def legacy_frames():
|
||||
return [CanData(address, bytes(8), bus) for bus, address in (
|
||||
(0, 0x09D), (0, 0x165), (0, 0x202), (0, 0x21C), (0, 0x240), (2, 0x243),
|
||||
)]
|
||||
|
||||
|
||||
@pytest.mark.parametrize('layout', ['normal', 'missing_camera', 'camera_echo', 'wrong_dlc'])
|
||||
@pytest.mark.parametrize('observed_engine', [True, False])
|
||||
def test_legacy_mazda_discovery_selects_normal_wiring_and_requires_firmware(layout, observed_engine):
|
||||
frames = legacy_frames()
|
||||
if layout != 'normal':
|
||||
frame = frames.pop()
|
||||
if layout == 'camera_echo':
|
||||
frames.append(CanData(frame.address, frame.dat, frame.src + 128))
|
||||
if layout == 'wrong_dlc':
|
||||
frames.extend((frame, CanData(frame.address, frame.dat[:-1], frame.src)))
|
||||
|
||||
firmware = [CarParams.CarFw(address=address, brand='mazda', fwVersion=version.ljust(24, b'\0')) for address, version in (
|
||||
(0x7E1, b'PYB2-21PS1-G'), (0x730, b'KSD5-3210X-C-00'),
|
||||
)]
|
||||
if observed_engine:
|
||||
firmware.append(CarParams.CarFw(address=0x7E0, brand='mazda', fwVersion=b'PX2H-188K2-E'.ljust(24, b'\0')))
|
||||
|
||||
mux = []
|
||||
with patch('opendbc.car.car_helpers.get_vin', return_value=(-1, -1, VIN_UNKNOWN)) as vin, \
|
||||
patch('opendbc.car.car_helpers.get_fw_versions', return_value=firmware) as fw, \
|
||||
patch('opendbc.car.car_helpers.get_present_ecus', return_value=set()), \
|
||||
patch('opendbc.car.car_helpers.get_fw_versions_ordered', return_value=[]), \
|
||||
patch('opendbc.car.car_helpers.can_fingerprint', return_value=(None, {})), \
|
||||
patch('opendbc.car.car_helpers.time.sleep'):
|
||||
result = fingerprint(lambda **kwargs: [frames], lambda _: None, mux.append, None)
|
||||
|
||||
if layout == 'normal':
|
||||
assert mux and not any(mux)
|
||||
assert vin.call_args.args[2] == (0,)
|
||||
assert fw.call_args.kwargs == {'query_brand': 'mazda', 'normal_bus_only': True}
|
||||
assert result[0] == (CAR.MAZDA_CX5 if observed_engine else None)
|
||||
else:
|
||||
fw.assert_not_called()
|
||||
assert result[0] is None
|
||||
@@ -8,7 +8,7 @@ from opendbc.car.mazda.values import CAR
|
||||
|
||||
class TestStockCancelEvents(unittest.TestCase):
|
||||
def test_actual_parser_cancel_is_scoped_to_marked_profile(self):
|
||||
for identity in (CAR.MAZDA_CX5_2022, CAR.MAZDA_CX9_2021):
|
||||
for identity in (CAR.MAZDA_CX5, CAR.MAZDA_CX5_2022, CAR.MAZDA_CX9_2021):
|
||||
for experience in (0, 32):
|
||||
with self.subTest(identity=identity, experience=experience):
|
||||
cp = CarInterface.get_params(identity, gen_empty_fingerprint(), [], False, False, False)
|
||||
|
||||
@@ -9,7 +9,7 @@ from opendbc.car.mazda.interface import CarInterface
|
||||
from opendbc.car.mazda.values import CAR, DBC
|
||||
|
||||
|
||||
CARS = (CAR.MAZDA_CX5_2022, CAR.MAZDA_CX9_2021)
|
||||
CARS = (CAR.MAZDA_CX5, CAR.MAZDA_CX5_2022, CAR.MAZDA_CX9_2021)
|
||||
|
||||
|
||||
def exercise_startup(identity, alpha, release, aol, monkeypatch, mapping=(0, 0), probe=None, cancel_action=3):
|
||||
@@ -143,7 +143,7 @@ def test_saved_button_mappings_reach_actual_card_owner(identity, mapping, monkey
|
||||
exercise_startup(identity, False, False, True, monkeypatch, mapping=mapping)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("identity", (CAR.MAZDA_CX5, CAR.MAZDA_CX9, CAR.MAZDA_3, CAR.MAZDA_6))
|
||||
@pytest.mark.parametrize("identity", (CAR.MAZDA_CX9, CAR.MAZDA_3, CAR.MAZDA_6))
|
||||
def test_unchanged_dashcam_configuration_denies_independent_owner(identity):
|
||||
from opendbc.car.mazda.stock_aol import qualified
|
||||
from openpilot.starpilot.car.mazda.aol import policy_for
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
"""One bounded Legacy AVH ON request; 0x32B is status, never a TX command."""
|
||||
"""One bounded Subaru AVH ON request; 0x32B is status, never a TX command."""
|
||||
|
||||
AVH_REQUEST = 0x6BB
|
||||
AVH_STATUS = 0x32B
|
||||
@@ -10,7 +10,7 @@ def checksum(address, data):
|
||||
|
||||
|
||||
def avh_request(template, step):
|
||||
if len(template) != 8 or checksum(AVH_REQUEST, template) != template[0] or template[2] & 3 or step not in (1, 2):
|
||||
if len(template) != 8 or checksum(AVH_REQUEST, template) != template[0] or template[2] & 3 or step not in (1, 2, 3, 4):
|
||||
raise ValueError("Invalid AVH template or counter step")
|
||||
data = bytearray(template)
|
||||
data[1] = (data[1] & 0xF0) | ((data[1] + step) & 0xF)
|
||||
@@ -27,6 +27,8 @@ class AvhStartup:
|
||||
self.last_time = None
|
||||
self.stable_since = None
|
||||
self.frames = {}
|
||||
self.avh_req_gap = None
|
||||
self.avh_req_same_payload = False
|
||||
self.done = False
|
||||
self.followup = None
|
||||
|
||||
@@ -85,6 +87,9 @@ class AvhStartup:
|
||||
# checks their full counter stream; require consecutive head-unit frames here.
|
||||
sequential = bool(previous and (address not in (AVH_REQUEST, AVH_STATUS) or
|
||||
(data[1] & 15) == ((previous[1][1] + 1) & 15)))
|
||||
if address == AVH_REQUEST and previous is not None and timestamp > previous[0]:
|
||||
self.avh_req_gap = timestamp - previous[0]
|
||||
self.avh_req_same_payload = data[2:] == previous[1][2:]
|
||||
self.frames[address] = (timestamp, data, sequential)
|
||||
|
||||
fresh = all(a in self.frames and self.frames[a][2] and
|
||||
@@ -104,31 +109,37 @@ class AvhStartup:
|
||||
if self.stable_since is None:
|
||||
self.stable_since = now
|
||||
if self.followup is not None:
|
||||
sent, timestamp, template = self.followup
|
||||
sent, timestamp, template, step = self.followup
|
||||
if now - sent > 0.075 or self.frames[AVH_REQUEST][0] != timestamp:
|
||||
self.done = True
|
||||
elif now - sent >= 0.05:
|
||||
self.done = True
|
||||
return [avh_request(template, 2)]
|
||||
next_step = step + 1
|
||||
if next_step == 4:
|
||||
self.done = True
|
||||
self.followup = None
|
||||
else:
|
||||
self.followup = (now, timestamp, template, next_step)
|
||||
return [avh_request(template, next_step)]
|
||||
return []
|
||||
if (now - self.started < 10 or now - self.stable_since < 3 or
|
||||
(self.configured_since is not None and now - self.configured_since < 10)):
|
||||
return []
|
||||
timestamp, template, _ = self.frames[AVH_REQUEST]
|
||||
if now - timestamp > 0.010:
|
||||
if now - timestamp > 0.010 or self.avh_req_gap is None or self.avh_req_gap < 0.80 or not self.avh_req_same_payload:
|
||||
return []
|
||||
self.followup = (now, timestamp, template)
|
||||
self.followup = (now, timestamp, template, 1)
|
||||
return [avh_request(template, 1)]
|
||||
|
||||
|
||||
def eligible(cp):
|
||||
from opendbc.car.subaru.startup import supported
|
||||
return bool(supported(cp) and cp.carFingerprint == 'SUBARU_LEGACY_2025')
|
||||
from opendbc.car.subaru.stock_aol import qualified
|
||||
from opendbc.car.subaru.values import CAR, FROGGER_ANGLE_SIBLINGS
|
||||
return bool(qualified(cp) and cp.carFingerprint in FROGGER_ANGLE_SIBLINGS | {CAR.SUBARU_LEGACY_2025})
|
||||
|
||||
|
||||
def selected(cp):
|
||||
from opendbc.car.subaru.values import SubaruFlags
|
||||
return bool(eligible(cp) and cp.flags & SubaruFlags.AVH_STARTUP and cp.safetyConfigs[0].safetyParam in (1169, 1425))
|
||||
return bool(eligible(cp) and cp.flags & SubaruFlags.AVH_STARTUP and cp.safetyConfigs[0].safetyParam in (1041, 1169, 1425, 3089))
|
||||
|
||||
|
||||
def prepare(cp, enabled):
|
||||
@@ -143,6 +154,7 @@ class AvhSources:
|
||||
def __init__(self):
|
||||
self.frames = {}
|
||||
self.sequential = {}
|
||||
self.source_ns = {}
|
||||
self.blocked = False
|
||||
|
||||
def observe(self, packets, *, boot_ns, mono_ns):
|
||||
@@ -163,10 +175,12 @@ class AvhSources:
|
||||
if data != previous[1]:
|
||||
self.blocked = True
|
||||
continue
|
||||
if source <= previous[0] * 1e9:
|
||||
prev_ns = self.source_ns[address]
|
||||
if source < prev_ns or (source == prev_ns and counter != ((previous[1][1] + 1) & 15)):
|
||||
self.blocked = True
|
||||
continue
|
||||
self.sequential[address] = previous is not None and counter == ((previous[1][1] + 1) & 15)
|
||||
self.source_ns[address] = source
|
||||
self.frames[address] = source / 1e9, data
|
||||
|
||||
def fresh(self, now):
|
||||
|
||||
@@ -8,7 +8,7 @@ from opendbc.car.interfaces import CarControllerBase
|
||||
from opendbc.car.subaru import subarucan
|
||||
from opendbc.car.subaru.jacobw_angle import MAX_ANGLE as JACOBW_MAX_ANGLE, filter_angle as jacobw_filter_angle, limit_angle as jacobw_limit_angle
|
||||
from opendbc.car.subaru.stock_aol import qualified as subaru_aol_qualified
|
||||
from opendbc.car.subaru.values import CAR, DBC, GLOBAL_ES_ADDR, CanBus, CarControllerParams, SubaruFlags
|
||||
from opendbc.car.subaru.values import CAR, FROGGER_ANGLE_SIBLINGS, DBC, GLOBAL_ES_ADDR, CanBus, CarControllerParams, SubaruFlags
|
||||
from opendbc.car.vehicle_model import VehicleModel
|
||||
|
||||
# FIXME: These limits aren't exact. The real limit is more than likely over a larger time period and
|
||||
@@ -27,13 +27,18 @@ class CarController(CarControllerBase):
|
||||
from opendbc.car.subaru.avh import selected as avh_selected, AvhStartup
|
||||
self.avh_startup = AvhStartup() if avh_selected(CP) else None
|
||||
self.apply_torque_last = 0
|
||||
self.angle_filter = FirstOrderFilter(0.0, 0.3, DT_CTRL) if CP.carFingerprint in (CAR.SUBARU_CROSSTREK_2025, CAR.SUBARU_IMPREZA_2025) else None
|
||||
self.angle_filter = (FirstOrderFilter(0.0, 0.3, DT_CTRL)
|
||||
if CP.carFingerprint in (CAR.SUBARU_CROSSTREK_2025, CAR.SUBARU_IMPREZA_2025, CAR.SUBARU_LEGACY_2025)
|
||||
else None)
|
||||
self.apply_angle_last = 0.
|
||||
self.angle_was_active = False
|
||||
self.angle_override_frames = 0
|
||||
self.eps_stall_count = 0
|
||||
self.ascent_angle_initialized = False
|
||||
self.ascent_es_distance_counter_last = None
|
||||
self.ascent_lkas_alert_counter_last = None
|
||||
self.aol_non_drive_ticks = 0
|
||||
self.aol_dash_green_last = False
|
||||
self.angle_driver_override = False
|
||||
self.angle_handoff_active = False
|
||||
self.VM = VehicleModel(CP) if CP.carFingerprint in GEN2_ANGLE_PORTS else None
|
||||
@@ -62,7 +67,7 @@ class CarController(CarControllerBase):
|
||||
self.angle_handoff_active = False
|
||||
return False
|
||||
high, low = (150, 100) if self.CP.carFingerprint in (CAR.SUBARU_CROSSTREK_2025, CAR.SUBARU_IMPREZA_2025) else (200, 150)
|
||||
torque = abs(CS.out.steeringTorque)
|
||||
torque = abs(float(CS.out.steeringTorque))
|
||||
if self.angle_driver_override:
|
||||
if torque < low:
|
||||
self.angle_driver_override = False
|
||||
@@ -85,12 +90,73 @@ class CarController(CarControllerBase):
|
||||
return False
|
||||
return True
|
||||
|
||||
@staticmethod
|
||||
def _legacy_2025_effective_lateral_off(CS, CC) -> bool:
|
||||
if bool(getattr(CS, "aol_enabled", True)):
|
||||
return bool(getattr(CS, "lateral_off", False))
|
||||
return not bool(CC.enabled)
|
||||
|
||||
def _legacy_2025_aol_dash_green(self, hud_control, CS, cruise_available: bool, lateral_off: bool) -> bool:
|
||||
if (
|
||||
lateral_off or not cruise_available or
|
||||
CS.out.steerFaultTemporary or CS.out.steerFaultPermanent
|
||||
):
|
||||
self.aol_non_drive_ticks = 0
|
||||
self.aol_dash_green_last = False
|
||||
return False
|
||||
Gear = structs.CarState.GearShifter
|
||||
if CS.out.gearShifter == Gear.park:
|
||||
self.aol_non_drive_ticks = 0
|
||||
green = bool(hud_control.lanesVisible)
|
||||
self.aol_dash_green_last = green
|
||||
return green
|
||||
if CS.out.gearShifter in (Gear.drive, Gear.manumatic):
|
||||
self.aol_non_drive_ticks = 0
|
||||
stationary_aol_green = bool(
|
||||
hud_control.lanesVisible and
|
||||
(CS.out.standstill or CS.out.vEgoRaw <= 0.44704) and
|
||||
not CS.out.steeringPressed and
|
||||
not self.angle_driver_override and not self.angle_handoff_active
|
||||
)
|
||||
green = bool(self.angle_was_active or stationary_aol_green)
|
||||
self.aol_dash_green_last = green
|
||||
return green
|
||||
self.aol_non_drive_ticks += 1
|
||||
if self.aol_non_drive_ticks >= 80:
|
||||
self.aol_dash_green_last = False
|
||||
return False
|
||||
return self.aol_dash_green_last
|
||||
|
||||
def _ascent_lkas_alert(self, CC, CS):
|
||||
if self.CP.carFingerprint != CAR.SUBARU_ASCENT_2023 or not self.CP.flags & SubaruFlags.ASCENT_LKAS_ALERT:
|
||||
if (self.CP.carFingerprint not in FROGGER_ANGLE_SIBLINGS | {CAR.SUBARU_ASCENT_2023, CAR.SUBARU_LEGACY_2025} or
|
||||
not self.CP.flags & SubaruFlags.ASCENT_LKAS_ALERT):
|
||||
return None
|
||||
dat = CS.es_lkas_alert_dat
|
||||
lateral_active = self.angle_was_active and CC.latActive and (CC.enabled or subaru_aol_qualified(self.CP, marked_only=True))
|
||||
msg = subarucan.create_ascent_lkas_alert(dat, lateral_active, CC.hudControl.visualAlert)
|
||||
frogger_hud = self.CP.carFingerprint != CAR.SUBARU_ASCENT_2023
|
||||
lateral_active = self.angle_was_active and CC.latActive and (
|
||||
CC.enabled or subaru_aol_qualified(self.CP, marked_only=True)
|
||||
)
|
||||
if frogger_hud:
|
||||
armed = CS.out.cruiseState.available
|
||||
if self.CP.openpilotLongitudinalControl:
|
||||
acc_lead_visible = bool(CC.longActive and not CS.out.gasPressed and CC.hudControl.leadVisible)
|
||||
else:
|
||||
dashstatus_msg = getattr(CS, "es_dashstatus_msg", None)
|
||||
if dashstatus_msg and ("Cruise_Activated_Dash" in dashstatus_msg or "Cruise_State" in dashstatus_msg):
|
||||
cruise_active = bool(
|
||||
dashstatus_msg.get("Cruise_Activated_Dash", 0) and
|
||||
dashstatus_msg.get("Cruise_State", 1) != 2 and
|
||||
not CS.out.gasPressed
|
||||
)
|
||||
else:
|
||||
cruise_active = bool(CS.out.cruiseState.enabled and not CS.out.gasPressed)
|
||||
acc_lead_visible = bool(cruise_active and dashstatus_msg and dashstatus_msg.get("Car_Follow", 0))
|
||||
msg = subarucan.create_ascent_lkas_alert(
|
||||
dat, lateral_active, CC.hudControl.visualAlert,
|
||||
armed=armed, acc_lead_visible=acc_lead_visible, legacy_2025=True,
|
||||
)
|
||||
else:
|
||||
msg = subarucan.create_ascent_lkas_alert(dat, lateral_active, CC.hudControl.visualAlert)
|
||||
if msg is None or (dat[1] & 0xf) == self.ascent_lkas_alert_counter_last:
|
||||
return None
|
||||
self.ascent_lkas_alert_counter_last = dat[1] & 0xf
|
||||
@@ -127,21 +193,48 @@ class CarController(CarControllerBase):
|
||||
if (self.frame % self.p.STEER_STEP) == 0:
|
||||
if self.CP.carFingerprint in GEN2_ANGLE_PORTS:
|
||||
independent_lateral = subaru_aol_qualified(self.CP, marked_only=True)
|
||||
# Preserve large-turn admission; active Jacobw ports retain their native angle envelope.
|
||||
angle_continuation = (self.angle_was_active and self.angle_filter is not None and
|
||||
abs(CS.out.steeringAngleDeg) < JACOBW_MAX_ANGLE)
|
||||
aol_motion_ok = CC.enabled or (CS.out.vEgoRaw > 0.44704 and
|
||||
(abs(CS.out.steeringAngleDeg) < 120. or angle_continuation))
|
||||
if self.CP.carFingerprint == CAR.SUBARU_LEGACY_2025:
|
||||
if CC.latActive and not CC.enabled:
|
||||
# Hold max AOL angle cleanly inside the 210 deg cutout ceiling instead of steering out of bounds.
|
||||
angle_target = float(np.clip(angle_target, -200., 200.))
|
||||
max_mads_angle = 210. if self.angle_was_active else 200.
|
||||
aol_motion_ok = CC.enabled or (CS.out.vEgoRaw > 0.44704 and abs(CS.out.steeringAngleDeg) <= max_mads_angle)
|
||||
gear_ok = CS.out.gearShifter in (structs.CarState.GearShifter.drive, structs.CarState.GearShifter.manumatic)
|
||||
else:
|
||||
# Preserve large-turn admission; active Jacobw ports retain their native angle envelope.
|
||||
angle_continuation = (self.angle_was_active and self.angle_filter is not None and
|
||||
abs(CS.out.steeringAngleDeg) < JACOBW_MAX_ANGLE)
|
||||
aol_motion_ok = CC.enabled or (CS.out.vEgoRaw > 0.44704 and
|
||||
(abs(CS.out.steeringAngleDeg) < 120. or angle_continuation))
|
||||
gear_ok = CS.out.gearShifter == structs.CarState.GearShifter.drive
|
||||
legacy_lateral_off = self._legacy_2025_effective_lateral_off(CS, CC) if self.CP.carFingerprint == CAR.SUBARU_LEGACY_2025 else False
|
||||
angle_available = (CC.latActive and aol_motion_ok and CS.out.cruiseState.available and
|
||||
(independent_lateral or CC.enabled and CS.out.cruiseState.enabled and not CS.out.brakePressed) and
|
||||
CS.out.gearShifter == structs.CarState.GearShifter.drive and
|
||||
(independent_lateral or (CC.enabled and CS.out.cruiseState.enabled and not CS.out.brakePressed)) and
|
||||
gear_ok and
|
||||
not legacy_lateral_off and
|
||||
not CS.out.standstill and not CS.out.steerFaultTemporary and not CS.out.steerFaultPermanent)
|
||||
angle_active = self.angle_active(CS, angle_available)
|
||||
if self.CP.carFingerprint in FROGGER_ANGLE_SIBLINGS | {CAR.SUBARU_LEGACY_2025}:
|
||||
if angle_active and self.angle_was_active and abs(self.apply_angle_last - CS.out.steeringAngleDeg) > 5.0:
|
||||
self.eps_stall_count += 1
|
||||
if self.eps_stall_count >= 8:
|
||||
# Yield via handoff before EPS rack latches Steer_Error_1, then re-sync next step.
|
||||
self.angle_handoff_active = True
|
||||
angle_active = False
|
||||
self.eps_stall_count = 0
|
||||
else:
|
||||
self.eps_stall_count = 0
|
||||
if not angle_active and self.angle_filter is not None:
|
||||
self.angle_filter.x = CS.out.steeringAngleDeg
|
||||
if self.CP.carFingerprint == CAR.SUBARU_ASCENT_2023 and not self.ascent_angle_initialized:
|
||||
self.apply_angle_last = CS.out.steeringAngleDeg
|
||||
self.ascent_angle_initialized = True
|
||||
angle_active = False
|
||||
if self.CP.carFingerprint in (CAR.SUBARU_LEGACY_2025, CAR.SUBARU_ASCENT_2023, CAR.SUBARU_OUTBACK_2023):
|
||||
if self.CP.carFingerprint == CAR.SUBARU_LEGACY_2025:
|
||||
apply_angle = apply_std_steer_angle_limits(angle_target, self.apply_angle_last,
|
||||
CS.out.vEgoRaw, CS.out.steeringAngleDeg, angle_active,
|
||||
self.p.LEGACY_2025_ANGLE_LIMITS)
|
||||
elif self.CP.carFingerprint in (CAR.SUBARU_ASCENT_2023, CAR.SUBARU_OUTBACK_2023):
|
||||
apply_angle = apply_std_steer_angle_limits(actuators.steeringAngleDeg, self.apply_angle_last,
|
||||
CS.out.vEgoRaw, CS.out.steeringAngleDeg, angle_active,
|
||||
self.p.FIXED_ANGLE_LIMITS)
|
||||
@@ -214,11 +307,20 @@ class CarController(CarControllerBase):
|
||||
can_sends.extend(send_sng(self, CC, CS, now_nanos))
|
||||
|
||||
# *** alerts and pcm cancel ***
|
||||
frogger_hud = self.CP.carFingerprint in FROGGER_ANGLE_SIBLINGS | {CAR.SUBARU_LEGACY_2025}
|
||||
enabled_for_dash_2025 = self.angle_was_active
|
||||
if self.CP.carFingerprint == CAR.SUBARU_LEGACY_2025:
|
||||
enabled_for_dash_2025 = self._legacy_2025_aol_dash_green(
|
||||
hud_control,
|
||||
CS,
|
||||
bool(CS.out.cruiseState.available),
|
||||
self._legacy_2025_effective_lateral_off(CS, CC),
|
||||
)
|
||||
lkas_alert_msg = self._ascent_lkas_alert(CC, CS)
|
||||
if lkas_alert_msg is not None:
|
||||
can_sends.append(lkas_alert_msg)
|
||||
if self.CP.flags & SubaruFlags.PREGLOBAL:
|
||||
if self.frame % 5 == 0:
|
||||
if self.CP.carFingerprint != CAR.SUBARU_OUTBACK_PREGLOBAL and self.frame % 5 == 0:
|
||||
# 1 = main, 2 = set shallow, 3 = set deep, 4 = resume shallow, 5 = resume deep
|
||||
# disengage ACC when OP is disengaged
|
||||
if pcm_cancel_cmd:
|
||||
@@ -241,18 +343,54 @@ class CarController(CarControllerBase):
|
||||
can_sends.append(subarucan.create_es_dashstatus(self.packer, self.frame // 10, CS.es_dashstatus_msg, CC.enabled,
|
||||
self.CP.openpilotLongitudinalControl, CC.longActive, hud_control.leadVisible))
|
||||
|
||||
lkas_active = self.angle_was_active if self.CP.carFingerprint in GEN2_ANGLE_PORTS else CC.enabled
|
||||
lkas_state_msg = CS.es_lkas_state_msg
|
||||
if self.CP.carFingerprint in GEN2_ANGLE_PORTS or subaru_aol_qualified(self.CP, marked_only=True):
|
||||
if self.CP.carFingerprint not in GEN2_ANGLE_PORTS:
|
||||
lkas_active = CC.latActive
|
||||
lkas_state_msg = dict(lkas_state_msg, LKAS_ACTIVE=int(lkas_active))
|
||||
can_sends.append(subarucan.create_es_lkas_state(self.packer, self.frame // 10, lkas_state_msg, lkas_active, hud_control.visualAlert,
|
||||
hud_control.leftLaneVisible, hud_control.rightLaneVisible,
|
||||
hud_control.leftLaneDepart, hud_control.rightLaneDepart))
|
||||
if frogger_hud:
|
||||
in_drive = CS.out.gearShifter in (structs.CarState.GearShifter.drive, structs.CarState.GearShifter.manumatic)
|
||||
cruise_available = CS.out.cruiseState.available
|
||||
lateral_off = self._legacy_2025_effective_lateral_off(CS, CC)
|
||||
aol_enabled = bool(getattr(CS, "aol_enabled", True))
|
||||
if self.CP.carFingerprint in FROGGER_ANGLE_SIBLINGS:
|
||||
aol_enabled = aol_enabled and subaru_aol_qualified(self.CP, marked_only=True)
|
||||
wheel_ready = bool(cruise_available and aol_enabled)
|
||||
lanes_visible = hud_control.lanesVisible or (
|
||||
self.CP.carFingerprint in FROGGER_ANGLE_SIBLINGS and self.angle_was_active)
|
||||
if not (in_drive and cruise_available) or lateral_off or not lanes_visible:
|
||||
left_line = 0
|
||||
right_line = 0
|
||||
left_depart = False
|
||||
right_depart = False
|
||||
else:
|
||||
left_line = 1 if hud_control.leftLaneVisible else 0
|
||||
right_line = 1 if hud_control.rightLaneVisible else 0
|
||||
left_depart = bool(hud_control.leftLaneDepart)
|
||||
right_depart = bool(hud_control.rightLaneDepart)
|
||||
|
||||
can_sends.append(subarucan.create_es_lkas_state(
|
||||
self.packer, self.frame // 10, CS.es_lkas_state_msg, enabled_for_dash_2025, hud_control.visualAlert,
|
||||
left_line, right_line, left_depart, right_depart,
|
||||
ready=wheel_ready, lkas_active=True, in_drive=in_drive,
|
||||
steering_active=self.angle_was_active and CC.latActive,
|
||||
))
|
||||
else:
|
||||
lkas_active = self.angle_was_active if self.CP.carFingerprint in GEN2_ANGLE_PORTS else CC.enabled
|
||||
lkas_state_msg = CS.es_lkas_state_msg
|
||||
if self.CP.carFingerprint in GEN2_ANGLE_PORTS or subaru_aol_qualified(self.CP, marked_only=True):
|
||||
if self.CP.carFingerprint not in GEN2_ANGLE_PORTS:
|
||||
lkas_active = CC.latActive
|
||||
lkas_state_msg = dict(lkas_state_msg, LKAS_ACTIVE=int(lkas_active))
|
||||
can_sends.append(subarucan.create_es_lkas_state(self.packer, self.frame // 10, lkas_state_msg, lkas_active, hud_control.visualAlert,
|
||||
hud_control.leftLaneVisible, hud_control.rightLaneVisible,
|
||||
hud_control.leftLaneDepart, hud_control.rightLaneDepart))
|
||||
|
||||
if self.CP.flags & SubaruFlags.SEND_INFOTAINMENT:
|
||||
can_sends.append(subarucan.create_es_infotainment(self.packer, self.frame // 10, CS.es_infotainment_msg, hud_control.visualAlert))
|
||||
if frogger_hud:
|
||||
can_sends.append(subarucan.create_es_infotainment(
|
||||
self.packer, self.frame // 10, CS.es_infotainment_msg, hud_control.visualAlert,
|
||||
audible_alert=hud_control.audibleAlert, legacy_2025=True,
|
||||
))
|
||||
else:
|
||||
can_sends.append(subarucan.create_es_infotainment(
|
||||
self.packer, self.frame // 10, CS.es_infotainment_msg, hud_control.visualAlert,
|
||||
))
|
||||
|
||||
if self.CP.openpilotLongitudinalControl:
|
||||
if self.frame % 5 == 0:
|
||||
@@ -266,7 +404,7 @@ class CarController(CarControllerBase):
|
||||
self.CP.openpilotLongitudinalControl, cruise_brake > 0, cruise_throttle))
|
||||
else:
|
||||
cancel_frame_ready = True
|
||||
if self.CP.carFingerprint == CAR.SUBARU_ASCENT_2023:
|
||||
if self.CP.carFingerprint in (CAR.SUBARU_ASCENT_2023, CAR.SUBARU_LEGACY_2025):
|
||||
stock_counter = CS.es_distance_msg["COUNTER"]
|
||||
cancel_frame_ready = stock_counter != self.ascent_es_distance_counter_last
|
||||
self.ascent_es_distance_counter_last = stock_counter
|
||||
|
||||
@@ -6,6 +6,10 @@ from opendbc.car.interfaces import CarStateBase
|
||||
from opendbc.car.subaru.values import CAR, DBC, CanBus, SubaruFlags
|
||||
from opendbc.car import CanSignalRateCalculator
|
||||
|
||||
# 8-speed Lineartronic CVT simulated paddle-shift ratios 1..8 on 0x48 Transmission.Gear
|
||||
# (bits 0..2 = 0b001 Drive range, bits 3..6 = simulated gear 1..8 or 0 in shift transition, bit 7 = manual mode)
|
||||
SUBARU_CVT_MANUAL_GEARS = frozenset({129, 137, 145, 153, 161, 169, 177, 185, 193})
|
||||
|
||||
|
||||
class CarState(CarStateBase):
|
||||
def __init__(self, CP):
|
||||
@@ -33,6 +37,32 @@ class CarState(CarStateBase):
|
||||
from opendbc.car.subaru.high_angle_guard import HighAngleGuard, selected
|
||||
self.high_angle_guard = HighAngleGuard() if selected(CP) else None
|
||||
self.high_angle_cut = False
|
||||
self.prev_cam_lkas_toggle: bool | None = None
|
||||
self.prev_cruise_available: bool | None = None
|
||||
self.aol_enabled = True
|
||||
self.lateral_off = False
|
||||
self._prev_aol_enabled: bool | None = None
|
||||
self._lkas_event_hold_frames = 0
|
||||
self._lkas_mode_settle_frames = 0
|
||||
|
||||
def _sync_legacy_2025_lateral_mode(self, cruise_available: bool, lkas_pressed: bool) -> None:
|
||||
aol = bool(getattr(self, "aol_enabled", True))
|
||||
if not cruise_available:
|
||||
self.lateral_off = not aol
|
||||
self._lkas_mode_settle_frames = 0
|
||||
self._prev_aol_enabled = aol
|
||||
return
|
||||
|
||||
entered_mode = (not bool(self.prev_cruise_available)) or (aol != self._prev_aol_enabled)
|
||||
if entered_mode:
|
||||
self._lkas_mode_settle_frames = 15
|
||||
self.lateral_off = not aol
|
||||
elif lkas_pressed:
|
||||
self._lkas_mode_settle_frames = 15
|
||||
self.lateral_off = (not self.lateral_off) if aol else True
|
||||
else:
|
||||
self._lkas_mode_settle_frames = max(0, self._lkas_mode_settle_frames - 1)
|
||||
self._prev_aol_enabled = aol
|
||||
|
||||
def update(self, can_parsers) -> structs.CarState:
|
||||
cp = can_parsers[Bus.pt]
|
||||
@@ -78,7 +108,14 @@ class CarState(CarStateBase):
|
||||
|
||||
cp_transmission = cp_alt if self.CP.flags & SubaruFlags.HYBRID else cp
|
||||
can_gear = int(cp_transmission.vl["Transmission"]["Gear"])
|
||||
ret.gearShifter = self.parse_gear_shifter(self.shifter_values.get(can_gear, None))
|
||||
if self.CP.carFingerprint == CAR.SUBARU_LEGACY_2025 and can_gear in SUBARU_CVT_MANUAL_GEARS:
|
||||
ret.gearShifter = structs.CarState.GearShifter.manumatic
|
||||
elif self.CP.carFingerprint == CAR.SUBARU_IMPREZA_2020 and self.shifter_values.get(can_gear) in ("1", "2", "3", "4", "5", "6"):
|
||||
ret.gearShifter = structs.CarState.GearShifter.manumatic
|
||||
elif self.CP.carFingerprint == CAR.SUBARU_LEGACY_2025 and can_gear == 0:
|
||||
ret.gearShifter = structs.CarState.GearShifter.neutral
|
||||
else:
|
||||
ret.gearShifter = self.parse_gear_shifter(self.shifter_values.get(can_gear, None))
|
||||
|
||||
if not (self.CP.flags & SubaruFlags.LKAS_ANGLE):
|
||||
ret.steeringAngleDeg = cp_angle.vl["Steering_Torque"]["Steering_Angle"]
|
||||
@@ -102,11 +139,14 @@ class CarState(CarStateBase):
|
||||
|
||||
cp_cruise = cp_alt if self.CP.flags & SubaruFlags.GLOBAL_GEN2 else cp
|
||||
cp_es_brake = cp_alt if self.CP.flags & SubaruFlags.GLOBAL_GEN2 else cp_cam
|
||||
soft_disable = False
|
||||
if self.CP.carFingerprint == CAR.SUBARU_LEGACY_2025:
|
||||
soft_disable = cp_cam.vl["ES_DashStatus"].get("Cruise_Soft_Disable", 0) != 0
|
||||
|
||||
if self.CP.carFingerprint in (CAR.SUBARU_CROSSTREK_2025, CAR.SUBARU_IMPREZA_2025, CAR.SUBARU_LEGACY_2025,
|
||||
CAR.SUBARU_ASCENT_2023, CAR.SUBARU_FORESTER_2022, CAR.SUBARU_OUTBACK_2023):
|
||||
ret.cruiseState.enabled = cp_es_brake.vl["ES_Status"]["Cruise_Activated"] != 0
|
||||
ret.cruiseState.available = cp_cam.vl["ES_DashStatus"]["Cruise_On"] != 0
|
||||
ret.cruiseState.available = (cp_cam.vl["ES_DashStatus"]["Cruise_On"] != 0) and not soft_disable
|
||||
elif self.CP.flags & (SubaruFlags.HYBRID | SubaruFlags.LKAS_ANGLE):
|
||||
# ES_DashStatus->Cruise_Activated_Dash is likely intended for the dash display only, as it falls
|
||||
# during user gas override and at standstill. ES_Status is missing on hybrid, so we use ES_Brake instead
|
||||
@@ -115,10 +155,10 @@ class CarState(CarStateBase):
|
||||
# brake while engaged at a stop. ES_Status and ES_DashStatus->Signal7 correctly fell, but is either missing or
|
||||
# always zero on hybrids. Probably need to split angle & hybrid. 0x27 and 0x225 on hybrids may work for them.
|
||||
ret.cruiseState.enabled = cp_es_brake.vl["ES_Brake"]['Cruise_Activated'] != 0
|
||||
ret.cruiseState.available = cp_cam.vl["ES_DashStatus"]['Cruise_On'] != 0
|
||||
ret.cruiseState.available = (cp_cam.vl["ES_DashStatus"]['Cruise_On'] != 0) and not soft_disable
|
||||
else:
|
||||
ret.cruiseState.enabled = cp_cruise.vl["CruiseControl"]["Cruise_Activated"] != 0
|
||||
ret.cruiseState.available = cp_cruise.vl["CruiseControl"]["Cruise_On"] != 0
|
||||
ret.cruiseState.available = (cp_cruise.vl["CruiseControl"]["Cruise_On"] != 0) and not soft_disable
|
||||
ret.cruiseState.speed = cp_cam.vl["ES_DashStatus"]["Cruise_Set_Speed"] * CV.KPH_TO_MS
|
||||
|
||||
if (self.CP.flags & SubaruFlags.PREGLOBAL and cp.vl["Dash_State2"]["UNITS"] == 1) or \
|
||||
@@ -148,6 +188,34 @@ class CarState(CarStateBase):
|
||||
self.es_lkas_state_msg = copy.copy(cp_cam.vl["ES_LKAS_State"])
|
||||
self.es_brake_msg = copy.copy(cp_es_brake.vl["ES_Brake"])
|
||||
|
||||
if self.CP.carFingerprint == CAR.SUBARU_LEGACY_2025:
|
||||
cam_lkas_toggle = int(self.es_lkas_state_msg.get("LKAS_Dash_State", 0)) > 0
|
||||
steer_fault = bool(ret.steerFaultTemporary or ret.steerFaultPermanent)
|
||||
lkas_pressed = False
|
||||
if steer_fault or not ret.cruiseState.available:
|
||||
self.prev_cam_lkas_toggle = None
|
||||
self._lkas_event_hold_frames = 0
|
||||
else:
|
||||
if (
|
||||
self.prev_cam_lkas_toggle is not None
|
||||
and self.prev_cruise_available
|
||||
and cam_lkas_toggle != self.prev_cam_lkas_toggle
|
||||
):
|
||||
lkas_pressed = True
|
||||
self._lkas_event_hold_frames = 5
|
||||
self.prev_cam_lkas_toggle = cam_lkas_toggle
|
||||
if self._lkas_event_hold_frames > 0:
|
||||
button_events = list(ret.buttonEvents) if ret.buttonEvents else []
|
||||
ButtonType = structs.CarState.ButtonEvent.Type
|
||||
button_events.extend([
|
||||
structs.CarState.ButtonEvent(pressed=True, type=ButtonType.lkas),
|
||||
structs.CarState.ButtonEvent(pressed=False, type=ButtonType.lkas),
|
||||
])
|
||||
ret.buttonEvents = button_events
|
||||
self._lkas_event_hold_frames -= 1
|
||||
self._sync_legacy_2025_lateral_mode(bool(ret.cruiseState.available), lkas_pressed)
|
||||
self.prev_cruise_available = bool(ret.cruiseState.available)
|
||||
|
||||
# TODO: Hybrid cars don't have ES_Distance, need a replacement
|
||||
if not (self.CP.flags & SubaruFlags.HYBRID):
|
||||
# 8 is known AEB, there are a few other values related to AEB we ignore
|
||||
@@ -190,8 +258,17 @@ class CarState(CarStateBase):
|
||||
self.es_dashstatus_msg = copy.copy(cp_cam.vl["ES_DashStatus"])
|
||||
if self.CP.flags & SubaruFlags.ASCENT_LKAS_ALERT:
|
||||
alert = cp_cam.vl["ES_LKAS_Alert"]
|
||||
self.es_lkas_alert_dat = (bytes((int(alert["CHECKSUM"]), int(alert["COUNTER"]) | (int(alert["Signal1"]) << 4))) +
|
||||
int(alert["Payload"]).to_bytes(6, "little"))
|
||||
self.es_lkas_alert_dat = (
|
||||
bytes((
|
||||
int(alert["CHECKSUM"]),
|
||||
int(alert["COUNTER"]) | (int(alert["Signal1"]) << 4),
|
||||
int(alert["LKAS_Alert"]),
|
||||
int(alert["LKAS_Alert_Msg"]),
|
||||
int(alert["LKAS_HUD_Lights"]),
|
||||
int(alert["ACC_Lead_LED"]),
|
||||
)) +
|
||||
int(alert["Signal2"]).to_bytes(2, "little")
|
||||
)
|
||||
if self.CP.flags & SubaruFlags.SEND_INFOTAINMENT:
|
||||
self.es_infotainment_msg = copy.copy(cp_cam.vl["ES_Infotainment"])
|
||||
|
||||
|
||||
@@ -5,7 +5,7 @@ from opendbc.car.disable_ecu import disable_ecu
|
||||
from opendbc.car.interfaces import CarInterfaceBase
|
||||
from opendbc.car.subaru.carcontroller import CarController
|
||||
from opendbc.car.subaru.carstate import CarState
|
||||
from opendbc.car.subaru.values import CAR, GLOBAL_ES_ADDR, CanBus, SubaruFlags, SubaruSafetyFlags
|
||||
from opendbc.car.subaru.values import CAR, FROGGER_ANGLE_SIBLINGS, EARLY_GLOBAL_TORQUE_CARS, GLOBAL_ES_ADDR, CanBus, SubaruFlags, SubaruSafetyFlags
|
||||
|
||||
GEN2_ANGLE_PORTS = frozenset((CAR.SUBARU_CROSSTREK_2025, CAR.SUBARU_IMPREZA_2025, CAR.SUBARU_LEGACY_2025,
|
||||
CAR.SUBARU_ASCENT_2023, CAR.SUBARU_FORESTER_2022, CAR.SUBARU_OUTBACK_2023))
|
||||
@@ -14,6 +14,7 @@ GEN2_ANGLE_PORTS = frozenset((CAR.SUBARU_CROSSTREK_2025, CAR.SUBARU_IMPREZA_2025
|
||||
class CarInterface(CarInterfaceBase):
|
||||
CarState = CarState
|
||||
CarController = CarController
|
||||
DRIVABLE_GEARS = (structs.CarState.GearShifter.manumatic,)
|
||||
|
||||
def update(self, can_packets):
|
||||
source = self.CS.startup_sources
|
||||
@@ -58,7 +59,7 @@ class CarInterface(CarInterfaceBase):
|
||||
if not (ret.flags & SubaruFlags.PREGLOBAL) and 0x323 in fingerprint[2]:
|
||||
ret.flags |= SubaruFlags.SEND_INFOTAINMENT.value
|
||||
|
||||
if candidate == CAR.SUBARU_ASCENT_2023 and fingerprint[CanBus.camera].get(0x3C4) == 8:
|
||||
if candidate in FROGGER_ANGLE_SIBLINGS | {CAR.SUBARU_ASCENT_2023, CAR.SUBARU_LEGACY_2025} and fingerprint[CanBus.camera].get(0x3C4) == 8:
|
||||
ret.flags |= SubaruFlags.ASCENT_LKAS_ALERT.value
|
||||
|
||||
if ret.flags & SubaruFlags.PREGLOBAL:
|
||||
@@ -75,6 +76,8 @@ class CarInterface(CarInterfaceBase):
|
||||
ret.safetyConfigs[0].safetyParam |= SubaruSafetyFlags.LKAS_ANGLE.value
|
||||
if candidate in (CAR.SUBARU_LEGACY_2025, CAR.SUBARU_ASCENT_2023, CAR.SUBARU_OUTBACK_2023):
|
||||
ret.safetyConfigs[0].safetyParam |= SubaruSafetyFlags.FIXED_ANGLE_LIMITS.value
|
||||
if candidate in FROGGER_ANGLE_SIBLINGS and ret.flags & SubaruFlags.ASCENT_LKAS_ALERT:
|
||||
ret.safetyConfigs[0].safetyParam |= SubaruSafetyFlags.ASCENT_LKAS_ALERT.value
|
||||
if candidate == CAR.SUBARU_OUTBACK_2023:
|
||||
ret.safetyConfigs[0].safetyParam |= SubaruSafetyFlags.D_PLATFORM.value
|
||||
if candidate == CAR.SUBARU_ASCENT_2023:
|
||||
@@ -98,7 +101,8 @@ class CarInterface(CarInterfaceBase):
|
||||
ret.lateralTuning.pid.kiBP, ret.lateralTuning.pid.kpBP = [[0., 20.], [0., 20.]]
|
||||
ret.lateralTuning.pid.kpV, ret.lateralTuning.pid.kiV = [[0.0025, 0.1], [0.00025, 0.01]]
|
||||
|
||||
elif candidate == CAR.SUBARU_IMPREZA:
|
||||
elif candidate in EARLY_GLOBAL_TORQUE_CARS:
|
||||
ret.safetyConfigs[0].safetyParam = SubaruSafetyFlags.EARLY_GLOBAL_TORQUE.value
|
||||
ret.steerActuatorDelay = 0.4 # end-to-end angle controller
|
||||
ret.lateralTuning.init('pid')
|
||||
ret.lateralTuning.pid.kf = 0.00005
|
||||
@@ -131,7 +135,8 @@ class CarInterface(CarInterfaceBase):
|
||||
ret.steerActuatorDelay = 0.15
|
||||
|
||||
elif candidate == CAR.SUBARU_OUTBACK_PREGLOBAL:
|
||||
pass
|
||||
ret.dashcamOnly = False
|
||||
ret.safetyConfigs[0].safetyParam = SubaruSafetyFlags.PREGLOBAL_OUTBACK_STOCK_ACC.value
|
||||
else:
|
||||
raise ValueError(f"unknown car: {candidate}")
|
||||
|
||||
|
||||
@@ -2,10 +2,10 @@
|
||||
|
||||
from opendbc.car import structs
|
||||
from opendbc.car.subaru.stock_aol import IMPREZA_MAIN_AOL
|
||||
from opendbc.car.subaru.values import CAR, SubaruFlags
|
||||
from opendbc.car.subaru.values import CAR, EARLY_GLOBAL_TORQUE_CARS, SubaruFlags, SubaruSafetyFlags
|
||||
|
||||
STOP_AND_GO = 8
|
||||
SUPPORTED = frozenset((CAR.SUBARU_ASCENT, CAR.SUBARU_IMPREZA, CAR.SUBARU_IMPREZA_2020, CAR.SUBARU_FORESTER))
|
||||
SUPPORTED = EARLY_GLOBAL_TORQUE_CARS | {CAR.SUBARU_ASCENT, CAR.SUBARU_IMPREZA_2020, CAR.SUBARU_FORESTER}
|
||||
|
||||
|
||||
def eligible(cp):
|
||||
@@ -16,6 +16,8 @@ def eligible(cp):
|
||||
return False
|
||||
word &= ~IMPREZA_MAIN_AOL
|
||||
words = (0, 8, 512, 520) if cp.carFingerprint == CAR.SUBARU_IMPREZA_2020 else (0, 8)
|
||||
if cp.carFingerprint in EARLY_GLOBAL_TORQUE_CARS:
|
||||
words = (SubaruSafetyFlags.EARLY_GLOBAL_TORQUE, SubaruSafetyFlags.EARLY_GLOBAL_TORQUE | STOP_AND_GO)
|
||||
return bool(
|
||||
cp.brand == 'subaru'
|
||||
and cp.carFingerprint in SUPPORTED
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
"""Exact stock-cruise Subaru independent-lateral configuration contract."""
|
||||
from opendbc.car import structs
|
||||
from opendbc.car.subaru.values import CAR, SubaruFlags, SubaruSafetyFlags
|
||||
from opendbc.car.subaru.values import CAR, FROGGER_ANGLE_SIBLINGS, EARLY_GLOBAL_TORQUE_CARS, SubaruFlags, SubaruSafetyFlags
|
||||
|
||||
AOL_EXPERIENCE = 32
|
||||
IMPREZA_MAIN_AOL = 4096
|
||||
TORQUE_CARS = frozenset((CAR.SUBARU_ASCENT, CAR.SUBARU_OUTBACK, CAR.SUBARU_LEGACY,
|
||||
CAR.SUBARU_IMPREZA, CAR.SUBARU_IMPREZA_2020, CAR.SUBARU_FORESTER))
|
||||
CAR.SUBARU_IMPREZA, CAR.SUBARU_IMPREZA_2020, CAR.SUBARU_FORESTER, CAR.SUBARU_CROSSTREK_2018))
|
||||
ANGLE_CARS = frozenset((CAR.SUBARU_CROSSTREK_2025, CAR.SUBARU_IMPREZA_2025, CAR.SUBARU_LEGACY_2025,
|
||||
CAR.SUBARU_ASCENT_2023, CAR.SUBARU_FORESTER_2022, CAR.SUBARU_OUTBACK_2023))
|
||||
|
||||
@@ -24,17 +24,25 @@ def qualified(cp, *, marked_only=False):
|
||||
static = int(CAR[cp.carFingerprint].config.flags)
|
||||
allowed = int(SubaruFlags.HAS_BSM | SubaruFlags.SEND_INFOTAINMENT | SubaruFlags.SMOOTHING_BOUND)
|
||||
expected = int(SubaruSafetyFlags.GEN2) if static & SubaruFlags.GLOBAL_GEN2 else 0
|
||||
if cp.carFingerprint in EARLY_GLOBAL_TORQUE_CARS:
|
||||
expected |= int(SubaruSafetyFlags.EARLY_GLOBAL_TORQUE) | (word & 8)
|
||||
if cp.carFingerprint == CAR.SUBARU_OUTBACK_2023:
|
||||
expected |= int(SubaruSafetyFlags.D_PLATFORM)
|
||||
allowed |= int(SubaruFlags.STOP_START_OFF)
|
||||
if cp.flags & SubaruFlags.STOP_START_OFF:
|
||||
expected |= int(SubaruSafetyFlags.STOP_START_BUTTON)
|
||||
if cp.carFingerprint == CAR.SUBARU_LEGACY_2025:
|
||||
allowed |= int(SubaruFlags.STOP_START_OFF | SubaruFlags.AVH_STARTUP)
|
||||
allowed |= int(SubaruFlags.STOP_START_OFF | SubaruFlags.AVH_STARTUP | SubaruFlags.ASCENT_LKAS_ALERT)
|
||||
if cp.flags & SubaruFlags.AVH_STARTUP:
|
||||
expected |= int(SubaruSafetyFlags.AVH_STARTUP)
|
||||
if cp.flags & SubaruFlags.STOP_START_OFF:
|
||||
expected |= int(SubaruSafetyFlags.STOP_START_BUTTON)
|
||||
if cp.carFingerprint in FROGGER_ANGLE_SIBLINGS:
|
||||
allowed |= int(SubaruFlags.AVH_STARTUP | SubaruFlags.ASCENT_LKAS_ALERT)
|
||||
if cp.flags & SubaruFlags.AVH_STARTUP:
|
||||
expected |= int(SubaruSafetyFlags.AVH_STARTUP)
|
||||
if cp.flags & SubaruFlags.ASCENT_LKAS_ALERT:
|
||||
expected |= int(SubaruSafetyFlags.ASCENT_LKAS_ALERT)
|
||||
angle = cp.carFingerprint in ANGLE_CARS
|
||||
if angle:
|
||||
expected |= int(SubaruSafetyFlags.LKAS_ANGLE)
|
||||
@@ -50,7 +58,7 @@ def qualified(cp, *, marked_only=False):
|
||||
return False
|
||||
if cp.carFingerprint == CAR.SUBARU_IMPREZA_2020 and word == 512:
|
||||
expected |= 512
|
||||
if cp.carFingerprint in (CAR.SUBARU_ASCENT, CAR.SUBARU_IMPREZA, CAR.SUBARU_IMPREZA_2020, CAR.SUBARU_FORESTER) and word in (8, 520):
|
||||
if cp.carFingerprint in (CAR.SUBARU_ASCENT, CAR.SUBARU_IMPREZA_2020, CAR.SUBARU_FORESTER) and word in (8, 520):
|
||||
expected |= 8
|
||||
if cp.carFingerprint == CAR.SUBARU_IMPREZA_2020:
|
||||
expected |= word & 512
|
||||
@@ -59,6 +67,11 @@ def qualified(cp, *, marked_only=False):
|
||||
|
||||
|
||||
def temporary_restriction(cp, state):
|
||||
allowed_gears = (
|
||||
(structs.CarState.GearShifter.drive, structs.CarState.GearShifter.manumatic)
|
||||
if cp is not None and cp.carFingerprint == CAR.SUBARU_LEGACY_2025 else
|
||||
(structs.CarState.GearShifter.drive,)
|
||||
)
|
||||
return bool(state is not None and qualified(cp, marked_only=True) and state.canValid and not state.canTimeout and
|
||||
not state.steerFaultPermanent and not state.accFaulted and state.cruiseState.available and
|
||||
(state.gearShifter != structs.CarState.GearShifter.drive or state.steerFaultTemporary or state.standstill))
|
||||
(state.gearShifter not in allowed_gears or state.steerFaultTemporary or state.standstill))
|
||||
|
||||
@@ -2,6 +2,7 @@ from opendbc.car import structs
|
||||
from opendbc.car.subaru.values import CanBus
|
||||
|
||||
VisualAlert = structs.CarControl.HUDControl.VisualAlert
|
||||
AudibleAlert = structs.CarControl.HUDControl.AudibleAlert
|
||||
|
||||
|
||||
def create_steering_control(packer, apply_torque, steer_req):
|
||||
@@ -67,7 +68,8 @@ def create_es_distance(packer, frame, es_distance_msg, bus, pcm_cancel_cmd, long
|
||||
return packer.make_can_msg("ES_Distance", bus, values)
|
||||
|
||||
|
||||
def create_es_lkas_state(packer, frame, es_lkas_state_msg, enabled, visual_alert, left_line, right_line, left_lane_depart, right_lane_depart):
|
||||
def create_es_lkas_state(packer, frame, es_lkas_state_msg, enabled, visual_alert, left_line, right_line, left_lane_depart, right_lane_depart,
|
||||
ready=None, lkas_active=None, in_drive=False, steering_active=False):
|
||||
values = {s: es_lkas_state_msg[s] for s in [
|
||||
"CHECKSUM",
|
||||
"LKAS_Alert_Msg",
|
||||
@@ -88,29 +90,43 @@ def create_es_lkas_state(packer, frame, es_lkas_state_msg, enabled, visual_alert
|
||||
|
||||
values["COUNTER"] = frame % 0x10
|
||||
|
||||
# Filter the stock LKAS "Keep hands on wheel" alert
|
||||
if values["LKAS_Alert_Msg"] == 1:
|
||||
values["LKAS_Alert_Msg"] = 0
|
||||
legacy_2025_hud = (ready is not None) or (lkas_active is not None)
|
||||
if legacy_2025_hud:
|
||||
# Filter stock EyeSight centering engage/cancel and "Keep hands on wheel" alerts
|
||||
# (25: centering engage beep, 27: centering off beep, 28: hands-on warning beep, 30: hands-on OFF cancel beep)
|
||||
if steering_active and values["LKAS_Alert"] in (25, 27, 28, 30) and values["LKAS_Alert_Msg"] in (0, 1, 7):
|
||||
values["LKAS_Alert"] = 0
|
||||
if steering_active and values["LKAS_Alert_Msg"] in (1, 7) and values["LKAS_Alert"] == 0:
|
||||
values["LKAS_Alert_Msg"] = 0
|
||||
else:
|
||||
# Filter the stock LKAS "Keep hands on wheel" alert
|
||||
if values["LKAS_Alert_Msg"] == 1:
|
||||
values["LKAS_Alert_Msg"] = 0
|
||||
|
||||
# Filter the stock LKAS sending an audible alert when it turns off LKAS
|
||||
if values["LKAS_Alert"] == 27:
|
||||
values["LKAS_Alert"] = 0
|
||||
# Filter the stock LKAS sending an audible alert when it turns off LKAS
|
||||
if values["LKAS_Alert"] == 27:
|
||||
values["LKAS_Alert"] = 0
|
||||
|
||||
# Filter the stock LKAS sending an audible alert when "Keep hands on wheel" alert is active (2020+ models)
|
||||
if values["LKAS_Alert"] == 28 and values["LKAS_Alert_Msg"] == 7:
|
||||
values["LKAS_Alert"] = 0
|
||||
# Filter the stock LKAS sending an audible alert when "Keep hands on wheel" alert is active (2020+ models)
|
||||
if values["LKAS_Alert"] == 28 and values["LKAS_Alert_Msg"] == 7:
|
||||
values["LKAS_Alert"] = 0
|
||||
|
||||
# Filter the stock LKAS sending an audible alert when "Keep hands on wheel OFF" alert is active (2020+ models)
|
||||
if values["LKAS_Alert"] == 30:
|
||||
values["LKAS_Alert"] = 0
|
||||
# Filter the stock LKAS sending an audible alert when "Keep hands on wheel OFF" alert is active (2020+ models)
|
||||
if values["LKAS_Alert"] == 30:
|
||||
values["LKAS_Alert"] = 0
|
||||
|
||||
# Filter the stock LKAS sending "Keep hands on wheel OFF" alert (2020+ models)
|
||||
if values["LKAS_Alert_Msg"] == 7:
|
||||
values["LKAS_Alert_Msg"] = 0
|
||||
# Filter the stock LKAS sending "Keep hands on wheel OFF" alert (2020+ models)
|
||||
if values["LKAS_Alert_Msg"] == 7:
|
||||
values["LKAS_Alert_Msg"] = 0
|
||||
|
||||
# Preserve stock EyeSight Lane Departure Warnings (11, 12) at all times.
|
||||
# Show Keep hands on wheel alert for openpilot steerRequired alert
|
||||
if visual_alert == VisualAlert.steerRequired:
|
||||
values["LKAS_Alert_Msg"] = 1
|
||||
if legacy_2025_hud:
|
||||
if values["LKAS_Alert"] == 0 and values["LKAS_Alert_Msg"] == 0:
|
||||
values["LKAS_Alert_Msg"] = 1
|
||||
else:
|
||||
values["LKAS_Alert_Msg"] = 1
|
||||
|
||||
# Ensure we don't overwrite potentially more important alerts from stock (e.g. FCW)
|
||||
if visual_alert == VisualAlert.ldw and values["LKAS_Alert"] == 0:
|
||||
@@ -119,14 +135,37 @@ def create_es_lkas_state(packer, frame, es_lkas_state_msg, enabled, visual_alert
|
||||
elif right_lane_depart:
|
||||
values["LKAS_Alert"] = 11 # Right lane departure dash alert
|
||||
|
||||
if enabled:
|
||||
values["LKAS_ACTIVE"] = 1 # Show LKAS lane lines
|
||||
values["LKAS_Dash_State"] = 2 # Green enabled indicator
|
||||
else:
|
||||
values["LKAS_Dash_State"] = 0 # LKAS Not enabled
|
||||
if legacy_2025_hud:
|
||||
screen_active = True if lkas_active is None else bool(lkas_active)
|
||||
if screen_active:
|
||||
values["LKAS_ACTIVE"] = 1 # Show LKAS lane lines / keep screen active
|
||||
values["LKAS_Left_Line_Enable"] = 1
|
||||
values["LKAS_Right_Line_Enable"] = 1
|
||||
if enabled:
|
||||
values["LKAS_Dash_State"] = 2 # 2: Green enabled / active steering
|
||||
elif ready:
|
||||
values["LKAS_Dash_State"] = 1 # 1: White ready / override
|
||||
else:
|
||||
values["LKAS_Dash_State"] = 0 # 0: Inactive / no steering wheel icon
|
||||
line_visible = 1 if in_drive else 0
|
||||
else:
|
||||
values["LKAS_ACTIVE"] = 0
|
||||
values["LKAS_Dash_State"] = 0
|
||||
values["LKAS_Left_Line_Enable"] = 0
|
||||
values["LKAS_Right_Line_Enable"] = 0
|
||||
line_visible = 0
|
||||
|
||||
values["LKAS_Left_Line_Visible"] = int(left_line)
|
||||
values["LKAS_Right_Line_Visible"] = int(right_line)
|
||||
values["LKAS_Left_Line_Visible"] = line_visible if left_line else 0
|
||||
values["LKAS_Right_Line_Visible"] = line_visible if right_line else 0
|
||||
else:
|
||||
if enabled:
|
||||
values["LKAS_ACTIVE"] = 1 # Show LKAS lane lines
|
||||
values["LKAS_Dash_State"] = 2 # Green enabled indicator
|
||||
else:
|
||||
values["LKAS_Dash_State"] = 0 # LKAS Not enabled
|
||||
|
||||
values["LKAS_Left_Line_Visible"] = int(left_line)
|
||||
values["LKAS_Right_Line_Visible"] = int(right_line)
|
||||
|
||||
return packer.make_can_msg("ES_LKAS_State", CanBus.main, values)
|
||||
|
||||
@@ -231,7 +270,7 @@ def create_es_status(packer, frame, es_status_msg, long_enabled, long_active, cr
|
||||
return packer.make_can_msg("ES_Status", CanBus.main, values)
|
||||
|
||||
|
||||
def create_es_infotainment(packer, frame, es_infotainment_msg, visual_alert):
|
||||
def create_es_infotainment(packer, frame, es_infotainment_msg, visual_alert, audible_alert=AudibleAlert.none, legacy_2025=False):
|
||||
# Filter stock LKAS disabled and Keep hands on steering wheel OFF alerts
|
||||
values = {s: es_infotainment_msg[s] for s in [
|
||||
"CHECKSUM",
|
||||
@@ -248,7 +287,12 @@ def create_es_infotainment(packer, frame, es_infotainment_msg, visual_alert):
|
||||
|
||||
# Show Keep hands on wheel alert for openpilot steerRequired alert
|
||||
if visual_alert == VisualAlert.steerRequired:
|
||||
values["LKAS_State_Infotainment"] = 3
|
||||
if legacy_2025:
|
||||
# 4 adds wheel OFF icon on lockout without clobbering existing warnings
|
||||
if values["LKAS_State_Infotainment"] == 0:
|
||||
values["LKAS_State_Infotainment"] = 4 if audible_alert == AudibleAlert.warningImmediate else 3
|
||||
else:
|
||||
values["LKAS_State_Infotainment"] = 3
|
||||
|
||||
# Show Obstacle Detected for fcw
|
||||
if visual_alert == VisualAlert.fcw:
|
||||
@@ -257,14 +301,54 @@ def create_es_infotainment(packer, frame, es_infotainment_msg, visual_alert):
|
||||
return packer.make_can_msg("ES_Infotainment", CanBus.main, values)
|
||||
|
||||
|
||||
def create_ascent_lkas_alert(raw_dat: bytes, lateral_active: bool, visual_alert):
|
||||
def create_ascent_lkas_alert(
|
||||
raw_dat: bytes,
|
||||
lateral_active: bool,
|
||||
visual_alert,
|
||||
armed: bool = False,
|
||||
acc_lead_visible: bool = False,
|
||||
legacy_2025: bool = False,
|
||||
):
|
||||
address = 0x3C4
|
||||
if len(raw_dat) != 8 or raw_dat[0] != (((address & 0xff) + (address >> 8) + sum(raw_dat[1:])) & 0xff):
|
||||
return None
|
||||
|
||||
dat = bytearray(raw_dat)
|
||||
if lateral_active and visual_alert != VisualAlert.steerRequired and dat[2:] == b"\x00\x01\x04\x00\x00\x00":
|
||||
dat[3:5] = b"\x00\x00"
|
||||
changed = False
|
||||
|
||||
if legacy_2025 and armed:
|
||||
# 0x3C4 on Legacy 2025: dat[2]=chime (0x18 chirp, 0x1a/0x1b single, 0x1c 2x bouncy, 0x1e 4x strong),
|
||||
# dat[3]=small-screen popup (0x01 hands-on, 0x07 flashing), dat[4]=HUD LEDs (0x01/0x02/0x04 yellow, 0x10/0x20/0x40 red).
|
||||
target_alert = b"\x00\x01\x04" if visual_alert == VisualAlert.steerRequired else None
|
||||
|
||||
# Only deduplicate EyeSight prompts while we are requesting steering.
|
||||
duplicate = dat[2:5] in (
|
||||
b"\x00\x01\x04", b"\x00\x07\x04", b"\x00\x07\x30",
|
||||
b"\x00\x00\x02", b"\x00\x00\x30", b"\x1b\x00\x00", b"\x19\x00\x00",
|
||||
b"\x1c\x07\x04", b"\x1e\x00\x30", b"\x19\x01\x04",
|
||||
)
|
||||
if lateral_active and duplicate and dat[2:5] != target_alert:
|
||||
dat[2:5] = b"\x00\x00\x00"
|
||||
changed = True
|
||||
if target_alert is not None:
|
||||
if dat[2:5] == b"\x00\x00\x00":
|
||||
dat[2:5] = target_alert
|
||||
changed = True
|
||||
if dat[2:5] == target_alert and dat[5] == 0x01:
|
||||
dat[5] = 0x00
|
||||
changed = True
|
||||
|
||||
if not legacy_2025 and lateral_active and visual_alert != VisualAlert.steerRequired:
|
||||
if dat[2:] == b"\x00\x01\x04\x00\x00\x00":
|
||||
dat[3:5] = b"\x00\x00"
|
||||
changed = True
|
||||
|
||||
# Restore dat[5] = 0x01 when ACC is tracking a lead and background LKAS warning cleared dat[5].
|
||||
if legacy_2025 and acc_lead_visible and dat[2:5] == b"\x00\x00\x00" and dat[5] == 0x00:
|
||||
dat[5] = 0x01
|
||||
changed = True
|
||||
|
||||
if changed:
|
||||
dat[0] = ((address & 0xff) + (address >> 8) + sum(dat[1:])) & 0xff
|
||||
return address, bytes(dat), CanBus.main
|
||||
|
||||
|
||||
@@ -59,10 +59,12 @@ class TestIndependentAngleEnvelope(unittest.TestCase):
|
||||
cars = (CAR.SUBARU_CROSSTREK_2025, CAR.SUBARU_IMPREZA_2025, CAR.SUBARU_LEGACY_2025, CAR.SUBARU_ASCENT_2023,
|
||||
CAR.SUBARU_FORESTER_2022, CAR.SUBARU_OUTBACK_2023)
|
||||
for car in cars:
|
||||
for speed, angle, expected in ((5., 119.5, True), (5., -119.5, True),
|
||||
(5., 120., False), (5., -120., False),
|
||||
(5., 200., False), (5., -200., False),
|
||||
(.4, 10., False), (.5, 10., True)):
|
||||
cases = ((5., 199.5, True), (5., -199.5, True), (5., 200., True), (5., -200., True),
|
||||
(5., 201., False), (5., -201., False), (.4, 10., False), (.5, 10., True)) \
|
||||
if car == CAR.SUBARU_LEGACY_2025 else \
|
||||
((5., 119.5, True), (5., -119.5, True), (5., 120., False), (5., -120., False),
|
||||
(5., 200., False), (5., -200., False), (.4, 10., False), (.5, 10., True))
|
||||
for speed, angle, expected in cases:
|
||||
with self.subTest(car=car, speed=speed, angle=angle):
|
||||
cp, controller, command, state = setup_controller(car)
|
||||
cp.alternativeExperience = 32
|
||||
@@ -80,6 +82,88 @@ class TestIndependentAngleEnvelope(unittest.TestCase):
|
||||
expected_angle = max(-190., min(190., angle)) if car in (CAR.SUBARU_CROSSTREK_2025, CAR.SUBARU_IMPREZA_2025) else angle
|
||||
self.assertAlmostEqual(decoded['LKAS_Output'], expected_angle, places=2)
|
||||
|
||||
def test_legacy_2025_mads_hysteresis_and_eps_stall_guard(self):
|
||||
cp, controller, command, state = setup_controller(CAR.SUBARU_LEGACY_2025)
|
||||
cp.alternativeExperience = 32
|
||||
command.enabled = False
|
||||
state.out.cruiseState.enabled = False
|
||||
state.out.vEgoRaw = state.out.vEgo = 5.
|
||||
state.out.standstill = False
|
||||
state.out.steeringTorque = state.out.steeringRateDeg = 0
|
||||
state.out.steeringAngleDeg = 199.
|
||||
command.actuators.steeringAngleDeg = 199.
|
||||
_, decoded = step(controller, command, state)
|
||||
self.assertEqual(decoded['LKAS_Request'], 1)
|
||||
state.out.steeringAngleDeg = 205.
|
||||
command.actuators.steeringAngleDeg = 205.
|
||||
_, decoded = step(controller, command, state)
|
||||
self.assertEqual(decoded['LKAS_Request'], 1)
|
||||
state.out.steeringAngleDeg = 211.
|
||||
_, decoded = step(controller, command, state)
|
||||
self.assertEqual(decoded['LKAS_Request'], 0)
|
||||
|
||||
# 8-frame EPS stall guard releases for 1 frame when wheel angle stops tracking target.
|
||||
_, controller, command, state = setup_controller(CAR.SUBARU_LEGACY_2025)
|
||||
state.out.vEgoRaw = state.out.vEgo = 5.
|
||||
state.out.standstill = False
|
||||
state.out.steeringAngleDeg = 0.
|
||||
command.actuators.steeringAngleDeg = 0.
|
||||
_, decoded = step(controller, command, state)
|
||||
self.assertEqual(decoded['LKAS_Request'], 1)
|
||||
command.actuators.steeringAngleDeg = 40.
|
||||
stalled = 0
|
||||
for _ in range(20):
|
||||
prev_output = decoded['LKAS_Output']
|
||||
_, decoded = step(controller, command, state)
|
||||
if abs(prev_output - state.out.steeringAngleDeg) > 5.0:
|
||||
stalled += 1
|
||||
if stalled == 8:
|
||||
self.assertEqual(decoded['LKAS_Request'], 0)
|
||||
self.assertEqual(decoded['LKAS_Output'], 0.)
|
||||
break
|
||||
self.assertEqual(decoded['LKAS_Request'], 1)
|
||||
else:
|
||||
self.fail("EPS stall guard did not trigger after 8 stalled frames")
|
||||
|
||||
def test_legacy_2025_aol_clamps_target_to_hold_max_turn(self):
|
||||
for sign in (-1, 1):
|
||||
with self.subTest(sign=sign):
|
||||
cp, controller, command, state = setup_controller(CAR.SUBARU_LEGACY_2025)
|
||||
cp.alternativeExperience = 32
|
||||
command.enabled = False
|
||||
state.out.cruiseState.enabled = False
|
||||
state.out.vEgoRaw = state.out.vEgo = 25.
|
||||
state.out.standstill = False
|
||||
state.out.steeringTorque = state.out.steeringRateDeg = 0
|
||||
state.out.steeringAngleDeg = 199. * sign
|
||||
command.latActive = False
|
||||
step(controller, command, state)
|
||||
command.latActive = True
|
||||
command.actuators.steeringAngleDeg = 240. * sign
|
||||
for _ in range(10):
|
||||
_, decoded = step(controller, command, state)
|
||||
state.out.steeringAngleDeg = decoded['LKAS_Output']
|
||||
self.assertEqual(decoded['LKAS_Request'], 1)
|
||||
self.assertAlmostEqual(decoded['LKAS_Output'], 200. * sign, places=2)
|
||||
|
||||
# Active cruise (ACC engaged) is not capped to the AOL 200 deg ceiling.
|
||||
_, controller, command, state = setup_controller(CAR.SUBARU_LEGACY_2025)
|
||||
command.enabled = True
|
||||
state.out.cruiseState.enabled = True
|
||||
state.out.vEgoRaw = state.out.vEgo = 25.
|
||||
state.out.standstill = False
|
||||
state.out.steeringTorque = state.out.steeringRateDeg = 0
|
||||
state.out.steeringAngleDeg = 199.
|
||||
command.latActive = False
|
||||
step(controller, command, state)
|
||||
command.latActive = True
|
||||
command.actuators.steeringAngleDeg = 220.
|
||||
for _ in range(10):
|
||||
_, decoded = step(controller, command, state)
|
||||
state.out.steeringAngleDeg = decoded['LKAS_Output']
|
||||
self.assertEqual(decoded['LKAS_Request'], 1)
|
||||
self.assertGreater(decoded['LKAS_Output'], 200.)
|
||||
|
||||
def test_ordinary_engagement_preserves_transmitted_history_and_other_profiles(self):
|
||||
for car in (CAR.SUBARU_CROSSTREK_2025, CAR.SUBARU_IMPREZA_2025, CAR.SUBARU_LEGACY_2025, CAR.SUBARU_ASCENT_2023,
|
||||
CAR.SUBARU_FORESTER_2022, CAR.SUBARU_OUTBACK_2023):
|
||||
@@ -94,7 +178,7 @@ class TestIndependentAngleEnvelope(unittest.TestCase):
|
||||
for _ in range(3):
|
||||
_, decoded = step(controller, command, state)
|
||||
self.assertTrue(decoded['LKAS_Request'])
|
||||
if car in (CAR.SUBARU_CROSSTREK_2025, CAR.SUBARU_IMPREZA_2025):
|
||||
if car in (CAR.SUBARU_CROSSTREK_2025, CAR.SUBARU_IMPREZA_2025, CAR.SUBARU_LEGACY_2025):
|
||||
# The EPS bound applies to transmitted commands, not measured-angle admission.
|
||||
# Follow the small target without jumping to the measured angle.
|
||||
expected = -1.45 * (1. - (30. / 31.) ** 5)
|
||||
|
||||
@@ -196,7 +196,7 @@ class TestSubaruAscentController(unittest.TestCase):
|
||||
self.assertEqual(values['Close_Distance'], state.es_distance_msg['Close_Distance'])
|
||||
self.assertEqual(observed, [0, 1, 3])
|
||||
|
||||
def test_repeated_stock_cancel_gate_is_ascent_2023_only(self):
|
||||
def test_repeated_stock_cancel_gate_cars(self):
|
||||
for car in (CAR.SUBARU_ASCENT_2023, CAR.SUBARU_CROSSTREK_2025, CAR.SUBARU_IMPREZA_2025,
|
||||
CAR.SUBARU_LEGACY_2025, CAR.SUBARU_OUTBACK_2023, CAR.SUBARU_ASCENT):
|
||||
with self.subTest(car=car):
|
||||
@@ -211,7 +211,7 @@ class TestSubaruAscentController(unittest.TestCase):
|
||||
for tick in range(5):
|
||||
_, sends = controller.update(command.as_reader(), state, 1_000_000_000 + tick * 10_000_000)
|
||||
distance.extend(frame for frame in sends if frame[0] == 0x221)
|
||||
self.assertEqual(len(distance), 1 if car == CAR.SUBARU_ASCENT_2023 else 5)
|
||||
self.assertEqual(len(distance), 1 if car in (CAR.SUBARU_ASCENT_2023, CAR.SUBARU_LEGACY_2025) else 5)
|
||||
self.assertEqual(len(set(distance)), 1)
|
||||
self.assertEqual(distance[0][2], 1 if cp.flags & SubaruFlags.GLOBAL_GEN2 else 0)
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@ from opendbc.car import structs
|
||||
from opendbc.car.subaru.carcontroller import CarController
|
||||
from opendbc.car.subaru.carstate import CarState
|
||||
from opendbc.car.subaru.interface import CarInterface
|
||||
from opendbc.car.subaru.values import CAR, DBC, SubaruFlags, SubaruSafetyFlags
|
||||
from opendbc.car.subaru.values import CAR, DBC, FROGGER_ANGLE_SIBLINGS, SubaruFlags, SubaruSafetyFlags
|
||||
from opendbc.car.subaru import subarucan
|
||||
from opendbc.safety.tests.test_subaru_gen2_angle_pair import TestSubaruGen2AnglePair
|
||||
|
||||
@@ -18,13 +18,14 @@ class TestAscentLkasAlert(unittest.TestCase):
|
||||
def test_platform_bus_length_gate_preserves_native_identity(self):
|
||||
for car in CAR:
|
||||
cp = self.params(car)
|
||||
self.assertEqual(bool(cp.flags & SubaruFlags.ASCENT_LKAS_ALERT), car == CAR.SUBARU_ASCENT_2023)
|
||||
self.assertEqual(bool(cp.safetyConfigs[0].safetyParam & SubaruSafetyFlags.ASCENT_LKAS_ALERT), car == CAR.SUBARU_ASCENT_2023)
|
||||
self.assertEqual(bool(cp.flags & SubaruFlags.ASCENT_LKAS_ALERT), car in FROGGER_ANGLE_SIBLINGS | {CAR.SUBARU_ASCENT_2023, CAR.SUBARU_LEGACY_2025})
|
||||
self.assertEqual(bool(cp.safetyConfigs[0].safetyParam & SubaruSafetyFlags.ASCENT_LKAS_ALERT), car in FROGGER_ANGLE_SIBLINGS | {CAR.SUBARU_ASCENT_2023})
|
||||
for bus, length in ((0, 8), (1, 8), (2, 4), (2, 16)):
|
||||
cp = self.params(bus=bus, length=length)
|
||||
self.assertFalse(cp.flags & SubaruFlags.ASCENT_LKAS_ALERT)
|
||||
self.assertEqual(cp.safetyConfigs[0].safetyParam, 0xB1)
|
||||
self.assertEqual(self.params().safetyConfigs[0].safetyParam, 0x8B1)
|
||||
self.assertEqual(self.params(CAR.SUBARU_LEGACY_2025).safetyConfigs[0].safetyParam, 0x91)
|
||||
|
||||
def test_production_parser_state_controller_and_actual_request(self):
|
||||
cp = self.params()
|
||||
@@ -66,3 +67,29 @@ class TestAscentLkasAlert(unittest.TestCase):
|
||||
self.assertEqual(subarucan.create_ascent_lkas_alert(bytes(dat), True, 0)[1], dat)
|
||||
for dat in (b"", bytes(7), bytes(9), bytes.fromhex("0002000104000000")):
|
||||
self.assertIsNone(subarucan.create_ascent_lkas_alert(dat, True, 0))
|
||||
|
||||
def test_legacy_2025_alert_suppression_and_lead_restore(self):
|
||||
def packet(hex_tail: str):
|
||||
dat = bytearray(bytes.fromhex("0002" + hex_tail))
|
||||
dat[0] = (0xC4 + 3 + sum(dat[1:])) & 0xFF
|
||||
return bytes(dat)
|
||||
|
||||
for payload in ("000104000000", "1c0704000000", "000704000000", "1e0030000000", "1b0000000000", "000002000000"):
|
||||
raw = packet(payload)
|
||||
self.assertEqual(subarucan.create_ascent_lkas_alert(raw, False, 0, armed=True, legacy_2025=True)[1], raw)
|
||||
msg = subarucan.create_ascent_lkas_alert(raw, True, 0, armed=True, acc_lead_visible=False, legacy_2025=True)
|
||||
self.assertEqual(msg[1][2:5], b"\x00\x00\x00", payload)
|
||||
self.assertEqual(msg[1][0], (0xC4 + 3 + sum(msg[1][1:])) & 0xFF)
|
||||
|
||||
# Restore green ACC lead-car LED (dat[5] = 0x01) when tracking a lead and background alert cleared it.
|
||||
msg = subarucan.create_ascent_lkas_alert(packet("000104000000"), True, 0, armed=True, acc_lead_visible=True, legacy_2025=True)
|
||||
self.assertEqual(msg[1][2:], bytes.fromhex("000000010000"))
|
||||
|
||||
# Native LDW (0x0b, 0x0c) and openpilot steerRequired (000104000000) work cleanly.
|
||||
ldw = packet("0b0000010000")
|
||||
self.assertEqual(subarucan.create_ascent_lkas_alert(ldw, True, 0, armed=True, legacy_2025=True)[1], ldw)
|
||||
hands_on = subarucan.create_ascent_lkas_alert(
|
||||
packet("000000010000"), False, structs.CarControl.HUDControl.VisualAlert.steerRequired,
|
||||
armed=True, legacy_2025=True,
|
||||
)
|
||||
self.assertEqual(hands_on[1][2:], bytes.fromhex("000104000000"))
|
||||
|
||||
@@ -34,20 +34,30 @@ def test_captured_legacy_press_bytes():
|
||||
template = bytes.fromhex('5b0b000100800e00')
|
||||
assert avh_request(template, 1) == (0x6BB, bytes.fromhex('5e0c020100800e00'), 1)
|
||||
assert avh_request(template, 2) == (0x6BB, bytes.fromhex('5f0d020100800e00'), 1)
|
||||
assert avh_request(template, 3) == (0x6BB, bytes.fromhex('600e020100800e00'), 1)
|
||||
assert avh_request(template, 4) == (0x6BB, bytes.fromhex('610f020100800e00'), 1)
|
||||
wrap = sample(AVH_REQUEST, 15)
|
||||
assert avh_request(wrap, 1)[1][1] == 0
|
||||
assert avh_request(wrap, 2)[1][1] == 1
|
||||
assert avh_request(wrap, 3)[1][1] == 2
|
||||
assert avh_request(wrap, 4)[1][1] == 3
|
||||
|
||||
def test_two_frames_only_and_no_retry():
|
||||
def test_four_frames_only_and_no_retry():
|
||||
policy, frames = prepare()
|
||||
assert policy.update(110.04, frames, True, True, False) == []
|
||||
assert policy.update(110.06, frames, True, True, False) == [avh_request(frames[AVH_REQUEST][1], 2)]
|
||||
assert policy.update(110.07, frames, True, True, False) == []
|
||||
assert policy.update(110.10, frames, True, True, False) == []
|
||||
assert policy.update(110.12, frames, True, True, False) == [avh_request(frames[AVH_REQUEST][1], 3)]
|
||||
assert policy.update(110.16, frames, True, True, False) == []
|
||||
assert policy.update(110.18, frames, True, True, False) == [avh_request(frames[AVH_REQUEST][1], 4)]
|
||||
assert policy.update(110.20, frames, True, True, False) == []
|
||||
assert policy.update(111, frames, True, True, False) == []
|
||||
|
||||
def test_controller_snapshots_may_skip_fast_can_samples():
|
||||
policy, frames = prepare(fast_counter_step=2)
|
||||
assert policy.update(110.06, frames, True, True, False) == [avh_request(frames[AVH_REQUEST][1], 2)]
|
||||
assert policy.update(110.12, frames, True, True, False) == [avh_request(frames[AVH_REQUEST][1], 3)]
|
||||
assert policy.update(110.18, frames, True, True, False) == [avh_request(frames[AVH_REQUEST][1], 4)]
|
||||
|
||||
@pytest.mark.parametrize('reason', ['late','new_template','manual','ack','moving','gas','gear','invalid','disabled','engaged','stale'])
|
||||
def test_followup_aborts_permanently(reason):
|
||||
@@ -69,3 +79,53 @@ def test_followup_aborts_permanently(reason):
|
||||
assert policy.update(now, frames, reason != 'disabled', reason != 'invalid', reason == 'engaged') == []
|
||||
assert policy.done
|
||||
assert policy.update(111, frames, True, True, False) == []
|
||||
|
||||
|
||||
def test_skips_state_change_and_50ms_burst_waits_for_steady_heartbeat():
|
||||
policy = AvhStartup()
|
||||
frames = {}
|
||||
counter = 0
|
||||
fast_counter = 0
|
||||
for tick in range(100):
|
||||
now = 100.0 + tick / 10
|
||||
fast_counter = tick
|
||||
for address in INPUTS:
|
||||
if address != AVH_REQUEST or tick % 10 == 0:
|
||||
if address == AVH_REQUEST:
|
||||
counter += 1
|
||||
c = counter if address == AVH_REQUEST else fast_counter
|
||||
frames[address] = (now, sample(address, c))
|
||||
assert policy.update(now, frames, True, True, False) == []
|
||||
|
||||
# Event transition (byte 6 changes) -> 1st burst frame at 109.95s, then 50ms burst at 110.00, 110.05, 110.10 (10s met mid-burst).
|
||||
for offset, changed in ((109.95, True), (110.00, False), (110.05, False), (110.10, False)):
|
||||
counter += 1
|
||||
fast_counter += 1
|
||||
data = bytearray(sample(AVH_REQUEST, counter))
|
||||
data[6] = 0x0F if changed else 0x0E
|
||||
data[0] = checksum(AVH_REQUEST, data)
|
||||
frames[AVH_REQUEST] = (offset, bytes(data))
|
||||
for address in INPUTS:
|
||||
if address != AVH_REQUEST:
|
||||
frames[address] = (offset, sample(address, fast_counter))
|
||||
assert policy.update(offset, frames, True, True, False) == []
|
||||
assert not policy.done
|
||||
|
||||
# Wait past 1.20s at 100ms ticks so configured/stable continuity stays intact, then send steady heartbeat at 111.30s.
|
||||
for tick in range(1, 12):
|
||||
now = 110.10 + tick * 0.10
|
||||
fast_counter += 1
|
||||
for address in INPUTS:
|
||||
if address != AVH_REQUEST:
|
||||
frames[address] = (now, sample(address, fast_counter))
|
||||
assert policy.update(now, frames, True, True, False) == []
|
||||
|
||||
counter += 1
|
||||
fast_counter += 1
|
||||
for address in INPUTS:
|
||||
frames[address] = (111.30, sample(address, counter if address == AVH_REQUEST else fast_counter))
|
||||
assert policy.update(111.30, frames, True, True, False) == [avh_request(frames[AVH_REQUEST][1], 1)]
|
||||
assert policy.update(111.36, frames, True, True, False) == [avh_request(frames[AVH_REQUEST][1], 2)]
|
||||
assert policy.update(111.42, frames, True, True, False) == [avh_request(frames[AVH_REQUEST][1], 3)]
|
||||
assert policy.update(111.48, frames, True, True, False) == [avh_request(frames[AVH_REQUEST][1], 4)]
|
||||
assert policy.done
|
||||
|
||||
@@ -145,9 +145,10 @@ def test_hackathon_filter_updates_at_control_rate(speed, tau):
|
||||
assert not any(frame[0] == 0x124 for frame in odd_sends)
|
||||
assert controller.angle_filter.x == pytest.approx(.1 * (1. - (1. - alpha) ** 2))
|
||||
command.latActive = False
|
||||
state.out.steeringAngleDeg = .3
|
||||
command.actuators.steeringAngleDeg = -.2
|
||||
controller.update(command.as_reader(), state, 1_020_000_000)
|
||||
assert controller.angle_filter.x == command.actuators.steeringAngleDeg
|
||||
assert controller.angle_filter.x == state.out.steeringAngleDeg
|
||||
|
||||
|
||||
def test_hackathon_geometry_is_scoped_and_native_bound_remains_strict():
|
||||
|
||||
@@ -0,0 +1,540 @@
|
||||
import unittest
|
||||
|
||||
from opendbc.can import CANPacker, CANParser
|
||||
from opendbc.car import Bus, structs
|
||||
from opendbc.car.subaru import subarucan
|
||||
from opendbc.car.subaru.carcontroller import CarController
|
||||
from opendbc.car.subaru.carstate import CarState
|
||||
from opendbc.car.subaru.interface import CarInterface
|
||||
from opendbc.car.subaru.tests.test_ascent_angle import setup_controller, step
|
||||
from opendbc.car.subaru.values import CAR, CanBus, DBC
|
||||
from opendbc.safety.tests import test_subaru_gen2_angle_pair as pair
|
||||
|
||||
|
||||
def _step_to_hud(controller, command, state):
|
||||
while controller.frame % 10 != 0:
|
||||
controller.update(command.as_reader(), state, 1_000_000_000 + controller.frame * 10_000_000)
|
||||
_, sends = controller.update(command.as_reader(), state, 1_000_000_000 + controller.frame * 10_000_000)
|
||||
hud = next(frame for frame in sends if frame[0] == 0x322)
|
||||
parser = CANParser(DBC[controller.CP.carFingerprint][Bus.pt], [('ES_LKAS_State', 0)], hud[2])
|
||||
parser.update([(1, [hud])])
|
||||
return parser.vl['ES_LKAS_State']
|
||||
|
||||
|
||||
class TestLegacy2025Aol(unittest.TestCase):
|
||||
def test_lkas_dash_state_toggle_emits_button_event_and_toggles_aol(self):
|
||||
cp = CarInterface.get_params(CAR.SUBARU_LEGACY_2025, {0: {}, 1: {}, 2: {}}, [], False, False, False)
|
||||
_, frames = pair.TestSubaruGen2AnglePair.sources(CAR.SUBARU_LEGACY_2025)
|
||||
packer = CANPacker(DBC[CAR.SUBARU_LEGACY_2025][Bus.pt])
|
||||
state = CarState(cp)
|
||||
self.assertTrue(state.aol_enabled)
|
||||
parsers = state.get_can_parsers(cp)
|
||||
state.update(parsers)
|
||||
for parser in parsers.values():
|
||||
parser.update([(1_000_000_000, frames)])
|
||||
ret = state.update(parsers)
|
||||
self.assertTrue(ret.cruiseState.available)
|
||||
self.assertFalse(state.lateral_off)
|
||||
self.assertEqual(len(ret.buttonEvents), 0)
|
||||
|
||||
# Flip LKAS_Dash_State (0 -> 1) on bus 2: toggles AOL off once and holds Type.lkas press/release for 5 frames.
|
||||
lkas_on = packer.make_can_msg('ES_LKAS_State', CanBus.camera, {'LKAS_Dash_State': 1})
|
||||
parsers[Bus.cam].update([(1_020_000_000, [lkas_on])])
|
||||
ret = state.update(parsers)
|
||||
self.assertTrue(state.lateral_off)
|
||||
lkas_events = [be for be in ret.buttonEvents if be.type == structs.CarState.ButtonEvent.Type.lkas]
|
||||
self.assertEqual([be.pressed for be in lkas_events], [True, False])
|
||||
for idx in range(4):
|
||||
ret = state.update(parsers)
|
||||
self.assertTrue(state.lateral_off)
|
||||
lkas_events = [be for be in ret.buttonEvents if be.type == structs.CarState.ButtonEvent.Type.lkas]
|
||||
self.assertEqual([be.pressed for be in lkas_events], [True, False], f"hold frame {idx + 2}")
|
||||
ret = state.update(parsers)
|
||||
self.assertTrue(state.lateral_off)
|
||||
self.assertEqual([be for be in ret.buttonEvents if be.type == structs.CarState.ButtonEvent.Type.lkas], [])
|
||||
|
||||
# Flip LKAS_Dash_State (1 -> 0): restores AOL active cleanly.
|
||||
lkas_off = packer.make_can_msg('ES_LKAS_State', CanBus.camera, {'LKAS_Dash_State': 0})
|
||||
parsers[Bus.cam].update([(1_040_000_000, [lkas_off])])
|
||||
ret = state.update(parsers)
|
||||
self.assertFalse(state.lateral_off)
|
||||
|
||||
# Toggle off, then drop Cruise_On -> lateral_off resets to False when AOL is enabled.
|
||||
parsers[Bus.cam].update([(1_060_000_000, [lkas_on])])
|
||||
state.update(parsers)
|
||||
self.assertTrue(state.lateral_off)
|
||||
dash_off = packer.make_can_msg('ES_DashStatus', CanBus.camera, {'Cruise_On': 0})
|
||||
parsers[Bus.cam].update([(1_080_000_000, [dash_off])])
|
||||
state.update(parsers)
|
||||
self.assertFalse(state.lateral_off)
|
||||
|
||||
def test_aol_mode_transitions_and_lkas_button_behavior(self):
|
||||
cp = CarInterface.get_params(CAR.SUBARU_LEGACY_2025, {0: {}, 1: {}, 2: {}}, [], False, False, False)
|
||||
_, frames = pair.TestSubaruGen2AnglePair.sources(CAR.SUBARU_LEGACY_2025)
|
||||
packer = CANPacker(DBC[CAR.SUBARU_LEGACY_2025][Bus.pt])
|
||||
|
||||
def init_state(aol_enabled: bool):
|
||||
state = CarState(cp)
|
||||
state.aol_enabled = aol_enabled
|
||||
parsers = state.get_can_parsers(cp)
|
||||
state.update(parsers)
|
||||
for parser in parsers.values():
|
||||
parser.update([(1_000_000_000, frames)])
|
||||
state.update(parsers)
|
||||
return state, parsers
|
||||
|
||||
def press_lkas(state, parsers, ts_ns: int, dash_state: int):
|
||||
msg = packer.make_can_msg('ES_LKAS_State', CanBus.camera, {'LKAS_Dash_State': dash_state})
|
||||
parsers[Bus.cam].update([(ts_ns, [msg])])
|
||||
return state.update(parsers)
|
||||
|
||||
# 1. AOL ON: AOL Active <-> AOL Off.
|
||||
state, parsers = init_state(True)
|
||||
self.assertFalse(state.lateral_off)
|
||||
press_lkas(state, parsers, 1_020_000_000, 1)
|
||||
self.assertTrue(state.lateral_off)
|
||||
press_lkas(state, parsers, 1_040_000_000, 0)
|
||||
self.assertFalse(state.lateral_off)
|
||||
|
||||
# 2. AOL OFF: forced Off even after LKAS presses.
|
||||
state, parsers = init_state(False)
|
||||
self.assertTrue(state.lateral_off)
|
||||
press_lkas(state, parsers, 1_020_000_000, 1)
|
||||
self.assertTrue(state.lateral_off)
|
||||
|
||||
# 3. Dynamic transitions across AOL settings changes.
|
||||
state, parsers = init_state(True)
|
||||
self.assertFalse(state.lateral_off)
|
||||
state.aol_enabled = False
|
||||
state.update(parsers)
|
||||
self.assertTrue(state.lateral_off)
|
||||
state.aol_enabled = True
|
||||
state.update(parsers)
|
||||
self.assertFalse(state.lateral_off)
|
||||
|
||||
def test_carcontroller_dash_state_and_steering_across_lateral_modes(self):
|
||||
_, controller, command, state = setup_controller(CAR.SUBARU_LEGACY_2025)
|
||||
state.out.cruiseState.available = True
|
||||
state.out.gearShifter = structs.CarState.GearShifter.drive
|
||||
state.out.vEgo = 20.0
|
||||
state.out.standstill = False
|
||||
|
||||
# AOL active -> LKAS_Dash_State == 2, lines visible, and ES_LKAS_ANGLE LKAS_Request == 1.
|
||||
state.aol_enabled = True
|
||||
state.lateral_off = False
|
||||
command.enabled = True
|
||||
command.latActive = True
|
||||
command.hudControl.lanesVisible = True
|
||||
command.hudControl.leftLaneVisible = True
|
||||
command.hudControl.rightLaneVisible = True
|
||||
command.actuators.steeringAngleDeg = 10.0
|
||||
_, angle = step(controller, command, state)
|
||||
self.assertEqual(angle['LKAS_Request'], 1)
|
||||
hud = _step_to_hud(controller, command, state)
|
||||
self.assertEqual(hud['LKAS_Dash_State'], 2)
|
||||
self.assertEqual(hud['LKAS_Left_Line_Visible'], 1)
|
||||
self.assertEqual(hud['LKAS_Right_Line_Visible'], 1)
|
||||
|
||||
# lateral_off with AOL toggle ON -> LKAS_Dash_State == 1 (white ready wheel), NO lines, and LKAS_Request == 0.
|
||||
state.lateral_off = True
|
||||
state.aol_enabled = True
|
||||
command.hudControl.lanesVisible = False
|
||||
_, angle = step(controller, command, state)
|
||||
self.assertEqual(angle['LKAS_Request'], 0)
|
||||
hud = _step_to_hud(controller, command, state)
|
||||
self.assertEqual(hud['LKAS_Dash_State'], 1)
|
||||
self.assertEqual(hud['LKAS_Left_Line_Visible'], 0)
|
||||
self.assertEqual(hud['LKAS_Right_Line_Visible'], 0)
|
||||
|
||||
# AOL toggle OFF while not engaged -> LKAS_Dash_State == 0 (wheel off) and NO lines (even before lateral_off syncs).
|
||||
state.aol_enabled = False
|
||||
state.lateral_off = False
|
||||
command.enabled = False
|
||||
command.latActive = False
|
||||
command.hudControl.lanesVisible = False
|
||||
_, angle = step(controller, command, state)
|
||||
self.assertEqual(angle['LKAS_Request'], 0)
|
||||
hud = _step_to_hud(controller, command, state)
|
||||
self.assertEqual(hud['LKAS_Dash_State'], 0)
|
||||
self.assertEqual(hud['LKAS_Left_Line_Visible'], 0)
|
||||
self.assertEqual(hud['LKAS_Right_Line_Visible'], 0)
|
||||
|
||||
# AOL toggle OFF with ACC engaged (even when state.lateral_off is still True) -> steers + green wheel + lines.
|
||||
state.lateral_off = True
|
||||
command.enabled = True
|
||||
command.latActive = True
|
||||
command.hudControl.lanesVisible = True
|
||||
_, angle = step(controller, command, state)
|
||||
self.assertEqual(angle['LKAS_Request'], 1)
|
||||
hud = _step_to_hud(controller, command, state)
|
||||
self.assertEqual(hud['LKAS_Dash_State'], 2)
|
||||
self.assertEqual(hud['LKAS_Left_Line_Visible'], 1)
|
||||
|
||||
# Main cruise OFF -> LKAS_Dash_State == 0 (wheel icon off) even with AOL toggle ON.
|
||||
state.aol_enabled = True
|
||||
state.out.cruiseState.available = False
|
||||
hud = _step_to_hud(controller, command, state)
|
||||
self.assertEqual(hud['LKAS_Dash_State'], 0)
|
||||
|
||||
def test_lkas_button_hold_survives_conflation_and_keeps_dash_wheel_in_sync(self):
|
||||
cp, controller, command, state = setup_controller(CAR.SUBARU_LEGACY_2025)
|
||||
_, frames = pair.TestSubaruGen2AnglePair.sources(CAR.SUBARU_LEGACY_2025)
|
||||
packer = CANPacker(DBC[CAR.SUBARU_LEGACY_2025][Bus.pt])
|
||||
state.aol_enabled = True
|
||||
parsers = state.get_can_parsers(cp)
|
||||
state.update(parsers)
|
||||
for parser in parsers.values():
|
||||
parser.update([(1_000_000_000, frames)])
|
||||
state.update(parsers)
|
||||
self.assertFalse(state.lateral_off)
|
||||
|
||||
controlsd_lateral_off = False
|
||||
prev_lkas_pressed = False
|
||||
|
||||
def step_controlsd_from_ret(car_state):
|
||||
nonlocal controlsd_lateral_off, prev_lkas_pressed
|
||||
raw_pressed = any(
|
||||
be.type == structs.CarState.ButtonEvent.Type.lkas and be.pressed
|
||||
for be in car_state.buttonEvents
|
||||
)
|
||||
if not car_state.cruiseState.available:
|
||||
prev_lkas_pressed = False
|
||||
lkas_pressed = raw_pressed and not prev_lkas_pressed
|
||||
prev_lkas_pressed = raw_pressed
|
||||
if lkas_pressed:
|
||||
controlsd_lateral_off = not controlsd_lateral_off
|
||||
|
||||
# 1. Press LKAS (0 -> 1): simulate SubMaster dropping the first two carState frames.
|
||||
parsers[Bus.cam].update([(1_020_000_000, [packer.make_can_msg('ES_LKAS_State', CanBus.camera, {'LKAS_Dash_State': 1})])])
|
||||
cs_frames = [state.update(parsers) for _ in range(6)]
|
||||
self.assertEqual([any(be.type == structs.CarState.ButtonEvent.Type.lkas for be in f.buttonEvents) for f in cs_frames],
|
||||
[True, True, True, True, True, False])
|
||||
self.assertTrue(state.lateral_off)
|
||||
for f in cs_frames[2:]:
|
||||
step_controlsd_from_ret(f)
|
||||
self.assertTrue(controlsd_lateral_off)
|
||||
self.assertEqual(state.lateral_off, controlsd_lateral_off)
|
||||
|
||||
# With AOL toggled off, wheel icon must stay white (1) with no lane lines and no steering request.
|
||||
state.out.cruiseState.available = True
|
||||
state.out.gearShifter = structs.CarState.GearShifter.drive
|
||||
state.out.vEgo = 20.0
|
||||
state.out.standstill = False
|
||||
command.enabled = False
|
||||
command.latActive = True
|
||||
command.hudControl.lanesVisible = False
|
||||
command.hudControl.leftLaneVisible = True
|
||||
command.actuators.steeringAngleDeg = -8.0
|
||||
_, decoded = step(controller, command, state)
|
||||
self.assertEqual(decoded['LKAS_Request'], 0)
|
||||
hud = _step_to_hud(controller, command, state)
|
||||
self.assertEqual(hud['LKAS_Dash_State'], 1)
|
||||
self.assertEqual(hud['LKAS_Left_Line_Visible'], 0)
|
||||
|
||||
# 2. Press LKAS (1 -> 0) back to AOL: again drop first two carState frames via conflation.
|
||||
parsers[Bus.cam].update([(1_100_000_000, [packer.make_can_msg('ES_LKAS_State', CanBus.camera, {'LKAS_Dash_State': 0})])])
|
||||
cs_frames_2 = [state.update(parsers) for _ in range(6)]
|
||||
self.assertEqual([any(be.type == structs.CarState.ButtonEvent.Type.lkas for be in f.buttonEvents) for f in cs_frames_2],
|
||||
[True, True, True, True, True, False])
|
||||
self.assertFalse(state.lateral_off)
|
||||
for f in cs_frames_2[2:]:
|
||||
step_controlsd_from_ret(f)
|
||||
self.assertFalse(controlsd_lateral_off)
|
||||
self.assertEqual(state.lateral_off, controlsd_lateral_off)
|
||||
|
||||
# In AOL mode with active steering, wheel icon turns back to green (2) and lines reappear.
|
||||
command.enabled = True
|
||||
command.latActive = True
|
||||
command.hudControl.lanesVisible = True
|
||||
command.actuators.steeringAngleDeg = 8.0
|
||||
_, decoded = step(controller, command, state)
|
||||
self.assertEqual(decoded['LKAS_Request'], 1)
|
||||
hud = _step_to_hud(controller, command, state)
|
||||
self.assertEqual(hud['LKAS_Dash_State'], 2)
|
||||
self.assertEqual(hud['LKAS_Left_Line_Visible'], 1)
|
||||
|
||||
def test_carcontroller_aol_green_wheel_park_override_and_alerts(self):
|
||||
_, controller, command, state = setup_controller(CAR.SUBARU_LEGACY_2025)
|
||||
state.out.cruiseState.available = True
|
||||
state.out.gearShifter = structs.CarState.GearShifter.park
|
||||
state.out.vEgo = 0.0
|
||||
state.out.standstill = True
|
||||
state.aol_enabled = True
|
||||
|
||||
# AOL active in Park / standstill (latActive=False, lanesVisible=True) -> green wheel icon (2).
|
||||
state.lateral_off = False
|
||||
command.enabled = False
|
||||
command.latActive = False
|
||||
command.hudControl.lanesVisible = True
|
||||
hud = _step_to_hud(controller, command, state)
|
||||
self.assertEqual(hud['LKAS_Dash_State'], 2)
|
||||
|
||||
# Toggle LKAS off in Park -> immediately drops to white wheel icon (1).
|
||||
state.lateral_off = True
|
||||
command.hudControl.lanesVisible = False
|
||||
hud = _step_to_hud(controller, command, state)
|
||||
self.assertEqual(hud['LKAS_Dash_State'], 1)
|
||||
|
||||
# steerRequired visual alert maps to Keep Hands On Wheel message (1) cleanly on 0x322.
|
||||
command.hudControl.visualAlert = structs.CarControl.HUDControl.VisualAlert.steerRequired
|
||||
command.hudControl.audibleAlert = structs.CarControl.HUDControl.AudibleAlert.none
|
||||
hud = _step_to_hud(controller, command, state)
|
||||
self.assertEqual(hud['LKAS_Alert_Msg'], 1)
|
||||
self.assertEqual(hud['LKAS_Alert'], 0)
|
||||
command.hudControl.visualAlert = structs.CarControl.HUDControl.VisualAlert.none
|
||||
hud = _step_to_hud(controller, command, state)
|
||||
self.assertEqual(hud['LKAS_Alert_Msg'], 0)
|
||||
self.assertEqual(hud['LKAS_Alert'], 0)
|
||||
|
||||
# Driving in AOL / full OP: active steering -> green (2), manual override -> white (1), resume -> green (2).
|
||||
state.lateral_off = False
|
||||
state.out.gearShifter = structs.CarState.GearShifter.drive
|
||||
state.out.vEgo = 20.0
|
||||
state.out.vEgoRaw = 20.0
|
||||
state.out.standstill = False
|
||||
command.enabled = True
|
||||
command.latActive = True
|
||||
command.hudControl.lanesVisible = True
|
||||
state.out.steeringTorque = 0.0
|
||||
state.out.steeringRateDeg = 0.0
|
||||
state.out.steeringPressed = False
|
||||
_, decoded = step(controller, command, state)
|
||||
self.assertEqual(decoded['LKAS_Request'], 1)
|
||||
hud = _step_to_hud(controller, command, state)
|
||||
self.assertEqual(hud['LKAS_Dash_State'], 2)
|
||||
|
||||
# Driver manually overrides steering -> wheel icon turns white (1).
|
||||
state.out.steeringTorque = 250.0
|
||||
state.out.steeringRateDeg = 30.0
|
||||
state.out.steeringPressed = True
|
||||
step(controller, command, state)
|
||||
_, decoded = step(controller, command, state)
|
||||
self.assertEqual(decoded['LKAS_Request'], 0)
|
||||
hud = _step_to_hud(controller, command, state)
|
||||
self.assertEqual(hud['LKAS_Dash_State'], 1)
|
||||
|
||||
# Driver releases wheel -> openpilot resumes control and wheel icon turns back to green (2).
|
||||
state.out.steeringTorque = 0.0
|
||||
state.out.steeringRateDeg = 0.0
|
||||
state.out.steeringPressed = False
|
||||
step(controller, command, state)
|
||||
_, decoded = step(controller, command, state)
|
||||
self.assertEqual(decoded['LKAS_Request'], 1)
|
||||
hud = _step_to_hud(controller, command, state)
|
||||
self.assertEqual(hud['LKAS_Dash_State'], 2)
|
||||
|
||||
# Stock EyeSight LDW / allowed alert takes priority over steerRequired alert.
|
||||
state.es_lkas_state_msg["LKAS_Alert"] = 12
|
||||
command.hudControl.visualAlert = structs.CarControl.HUDControl.VisualAlert.steerRequired
|
||||
hud = _step_to_hud(controller, command, state)
|
||||
self.assertEqual(hud['LKAS_Alert'], 12)
|
||||
self.assertEqual(hud['LKAS_Alert_Msg'], 0)
|
||||
|
||||
dbc = DBC[CAR.SUBARU_LEGACY_2025][Bus.pt]
|
||||
packer = CANPacker(dbc)
|
||||
info_parser = CANParser(dbc, [('ES_Infotainment', 0)], CanBus.main)
|
||||
info_msg = subarucan.create_es_infotainment(
|
||||
packer, 0, {'CHECKSUM': 0, 'LKAS_State_Infotainment': 1, 'LKAS_Blue_Lines': 0, 'Signal1': 0, 'Signal2': 0},
|
||||
structs.CarControl.HUDControl.VisualAlert.steerRequired,
|
||||
legacy_2025=True,
|
||||
)
|
||||
info_parser.update([(1, [info_msg])])
|
||||
self.assertEqual(info_parser.vl['ES_Infotainment']['LKAS_State_Infotainment'], 1)
|
||||
|
||||
for audible, expected in (
|
||||
(structs.CarControl.HUDControl.AudibleAlert.none, 3),
|
||||
(structs.CarControl.HUDControl.AudibleAlert.warningSoft, 3),
|
||||
(structs.CarControl.HUDControl.AudibleAlert.warningImmediate, 4),
|
||||
):
|
||||
info_msg = subarucan.create_es_infotainment(
|
||||
packer, 1, {'CHECKSUM': 0, 'LKAS_State_Infotainment': 0, 'LKAS_Blue_Lines': 0, 'Signal1': 0, 'Signal2': 0},
|
||||
structs.CarControl.HUDControl.VisualAlert.steerRequired,
|
||||
audible_alert=audible,
|
||||
legacy_2025=True,
|
||||
)
|
||||
info_parser.update([(2, [info_msg])])
|
||||
self.assertEqual(info_parser.vl['ES_Infotainment']['LKAS_State_Infotainment'], expected)
|
||||
|
||||
# Non-Legacy default (legacy_2025=False) preserves exact upstream 0x323 behavior.
|
||||
for stock_state in (0, 1):
|
||||
info_msg = subarucan.create_es_infotainment(
|
||||
packer, 2, {'CHECKSUM': 0, 'LKAS_State_Infotainment': stock_state, 'LKAS_Blue_Lines': 0, 'Signal1': 0, 'Signal2': 0},
|
||||
structs.CarControl.HUDControl.VisualAlert.steerRequired,
|
||||
audible_alert=structs.CarControl.HUDControl.AudibleAlert.warningImmediate,
|
||||
)
|
||||
info_parser.update([(3, [info_msg])])
|
||||
self.assertEqual(info_parser.vl['ES_Infotainment']['LKAS_State_Infotainment'], 3)
|
||||
|
||||
def test_carcontroller_aol_manumatic_and_unauthorized_gate(self):
|
||||
cp, _, command, state = setup_controller(CAR.SUBARU_LEGACY_2025)
|
||||
cp.alternativeExperience = 32
|
||||
controller = CarController(DBC[CAR.SUBARU_LEGACY_2025], cp)
|
||||
state.out.gearShifter = structs.CarState.GearShifter.manumatic
|
||||
state.lateral_off = False
|
||||
state.out.steeringAngleDeg = 0.0
|
||||
state.out.steeringRateDeg = 0.0
|
||||
state.out.steeringTorque = 0.0
|
||||
|
||||
# Active AOL in manumatic: angle requested, green wheel icon (2), visible left line (1).
|
||||
command.enabled = False
|
||||
command.latActive = True
|
||||
command.hudControl.lanesVisible = True
|
||||
command.hudControl.leftLaneVisible = True
|
||||
command.hudControl.rightLaneVisible = False
|
||||
command.actuators.steeringAngleDeg = -8.0
|
||||
_, decoded = step(controller, command, state)
|
||||
self.assertEqual(decoded['LKAS_Request'], 1)
|
||||
self.assertLess(decoded['LKAS_Output'], 0.0)
|
||||
hud = _step_to_hud(controller, command, state)
|
||||
self.assertEqual(hud['LKAS_Dash_State'], 2)
|
||||
self.assertEqual(hud['LKAS_Left_Line_Visible'], 1)
|
||||
|
||||
# Unauthorized gate: when controlsd keeps latActive=False, CarController must never request 0x124 torque/angle.
|
||||
command.latActive = False
|
||||
_, decoded = step(controller, command, state)
|
||||
self.assertEqual(decoded['LKAS_Request'], 0)
|
||||
_, decoded = step(controller, command, state)
|
||||
self.assertEqual(decoded['LKAS_Request'], 0)
|
||||
|
||||
def test_legacy_2025_manumatic_transition_and_between_detent_gears(self):
|
||||
cp = CarInterface.get_params(CAR.SUBARU_LEGACY_2025, {0: {}, 1: {}, 2: {}}, [], False, False, False)
|
||||
_, frames = pair.TestSubaruGen2AnglePair.sources(CAR.SUBARU_LEGACY_2025)
|
||||
packer = CANPacker(DBC[CAR.SUBARU_LEGACY_2025][Bus.pt])
|
||||
state = CarState(cp)
|
||||
parsers = state.get_can_parsers(cp)
|
||||
state.update(parsers)
|
||||
for parser in parsers.values():
|
||||
parser.update([(1_000_000_000, frames)])
|
||||
state.update(parsers)
|
||||
|
||||
Gear = structs.CarState.GearShifter
|
||||
for can_gear, expected_gear in ((121, Gear.drive), (129, Gear.manumatic), (177, Gear.manumatic), (0, Gear.neutral), (4, Gear.park)):
|
||||
msg = packer.make_can_msg('Transmission', 0, {'Gear': can_gear})
|
||||
parsers[Bus.pt].update([(1_020_000_000, [msg])])
|
||||
ret = state.update(parsers)
|
||||
self.assertEqual(ret.gearShifter, expected_gear, f'can_gear={can_gear}')
|
||||
|
||||
def test_legacy_2025_acc_lead_led_preserved_and_aol_line_visibility_passthrough(self):
|
||||
_, _, command, state = setup_controller(CAR.SUBARU_LEGACY_2025)
|
||||
cp = CarInterface.get_params(CAR.SUBARU_LEGACY_2025, {0: {}, 1: {}, 2: {0x3C4: 8}}, [], False, False, False)
|
||||
controller = CarController(DBC[CAR.SUBARU_LEGACY_2025], cp)
|
||||
state.out.cruiseState.available = True
|
||||
state.out.gearShifter = structs.CarState.GearShifter.drive
|
||||
state.out.vEgo = 20.0
|
||||
state.out.standstill = False
|
||||
|
||||
controller.angle_was_active = True
|
||||
command.enabled = command.latActive = True
|
||||
# Stock ACC active via Cruise_Activated_Dash + Car_Follow (not gasPressed) preserves dat[5]=0x01 when masking 000104000000.
|
||||
state.out.cruiseState.enabled = True
|
||||
state.out.gasPressed = False
|
||||
state.es_dashstatus_msg.update({'Cruise_Activated_Dash': 1, 'Cruise_State': 0, 'Car_Follow': 1})
|
||||
raw = bytearray(bytes.fromhex('0002000104000000'))
|
||||
raw[0] = (0xC4 + 3 + sum(raw[1:])) & 0xFF
|
||||
state.es_lkas_alert_dat = bytes(raw)
|
||||
msg = controller._ascent_lkas_alert(command.as_reader(), state)
|
||||
self.assertIsNotNone(msg)
|
||||
self.assertEqual(msg[1][2:], bytes.fromhex('000000010000'))
|
||||
|
||||
# Gas pedal override clears green lead LED (dat[5] = 0x00) even when cruiseState.enabled and Car_Follow remain set.
|
||||
for idx, override_fields in enumerate((
|
||||
{'gas': True, 'dash': 1, 'cstate': 0},
|
||||
{'gas': False, 'dash': 0, 'cstate': 2},
|
||||
)):
|
||||
state.out.gasPressed = override_fields['gas']
|
||||
state.es_dashstatus_msg.update({
|
||||
'Cruise_Activated_Dash': override_fields['dash'],
|
||||
'Cruise_State': override_fields['cstate'],
|
||||
'Car_Follow': 1,
|
||||
})
|
||||
raw[1] = 0x03 + idx
|
||||
raw[0] = (0xC4 + 3 + sum(raw[1:])) & 0xFF
|
||||
state.es_lkas_alert_dat = bytes(raw)
|
||||
msg = controller._ascent_lkas_alert(command.as_reader(), state)
|
||||
self.assertIsNotNone(msg)
|
||||
self.assertEqual(msg[1][2:], bytes.fromhex('000000000000'), override_fields)
|
||||
state.out.gasPressed = False
|
||||
state.es_dashstatus_msg.update({'Cruise_Activated_Dash': 1, 'Cruise_State': 0})
|
||||
|
||||
# Without Car_Follow, dat[5] stays 0x00 when masking the alert.
|
||||
state.es_dashstatus_msg.update({'Cruise_Activated_Dash': 1, 'Cruise_State': 0, 'Car_Follow': 0})
|
||||
raw[1] = 0x05
|
||||
raw[0] = (0xC4 + 3 + sum(raw[1:])) & 0xFF
|
||||
state.es_lkas_alert_dat = bytes(raw)
|
||||
msg = controller._ascent_lkas_alert(command.as_reader(), state)
|
||||
self.assertIsNotNone(msg)
|
||||
self.assertEqual(msg[1][2:], bytes.fromhex('000000000000'))
|
||||
|
||||
# A controller handoff restores the stock red HUD notification.
|
||||
controller.angle_was_active = False
|
||||
raw = bytearray(bytes.fromhex('00061e0030000000'))
|
||||
raw[0] = (0xC4 + 3 + sum(raw[1:])) & 0xFF
|
||||
state.es_lkas_alert_dat = bytes(raw)
|
||||
self.assertEqual(controller._ascent_lkas_alert(command.as_reader(), state)[1], raw)
|
||||
|
||||
# AOL mode passes debounced hudControl lane visibility directly through to cluster CAN.
|
||||
state.lateral_off = False
|
||||
command.enabled = False
|
||||
command.latActive = True
|
||||
command.hudControl.lanesVisible = True
|
||||
command.hudControl.leftLaneVisible = True
|
||||
command.hudControl.rightLaneVisible = True
|
||||
hud = _step_to_hud(controller, command, state)
|
||||
self.assertEqual(hud['LKAS_Left_Line_Visible'], 1)
|
||||
self.assertEqual(hud['LKAS_Right_Line_Visible'], 1)
|
||||
|
||||
command.hudControl.leftLaneVisible = False
|
||||
hud = _step_to_hud(controller, command, state)
|
||||
self.assertEqual(hud['LKAS_Left_Line_Visible'], 0)
|
||||
self.assertEqual(hud['LKAS_Right_Line_Visible'], 1)
|
||||
|
||||
command.hudControl.leftLaneVisible = True
|
||||
hud = _step_to_hud(controller, command, state)
|
||||
self.assertEqual(hud['LKAS_Left_Line_Visible'], 1)
|
||||
|
||||
def test_aol_wheel_icon_park_reverse_neutral_and_shift_debounce(self):
|
||||
_, controller, command, state = setup_controller(CAR.SUBARU_LEGACY_2025)
|
||||
state.out.cruiseState.available = True
|
||||
state.out.vEgo = 0.0
|
||||
state.out.vEgoRaw = 0.0
|
||||
state.out.standstill = True
|
||||
state.aol_enabled = True
|
||||
state.lateral_off = False
|
||||
command.enabled = False
|
||||
command.latActive = False
|
||||
command.hudControl.lanesVisible = True
|
||||
|
||||
# In Park: stays solid green even if steering wheel is moved slightly.
|
||||
state.out.gearShifter = structs.CarState.GearShifter.park
|
||||
state.out.steeringPressed = True
|
||||
self.assertEqual(_step_to_hud(controller, command, state)['LKAS_Dash_State'], 2)
|
||||
|
||||
# Fast Park -> Reverse -> Neutral -> Drive shift (< 0.8s) holds green without flashing white.
|
||||
state.out.steeringPressed = False
|
||||
for gear, steps in (
|
||||
(structs.CarState.GearShifter.reverse, 3),
|
||||
(structs.CarState.GearShifter.neutral, 3),
|
||||
):
|
||||
state.out.gearShifter = gear
|
||||
for _ in range(steps):
|
||||
self.assertEqual(_step_to_hud(controller, command, state)['LKAS_Dash_State'], 2)
|
||||
state.out.gearShifter = structs.CarState.GearShifter.drive
|
||||
self.assertEqual(_step_to_hud(controller, command, state)['LKAS_Dash_State'], 2)
|
||||
|
||||
# Settling in Reverse (>= 0.8s) switches to solid white regardless of steering input.
|
||||
state.out.gearShifter = structs.CarState.GearShifter.reverse
|
||||
for _ in range(9):
|
||||
hud = _step_to_hud(controller, command, state)
|
||||
self.assertEqual(hud['LKAS_Dash_State'], 1)
|
||||
state.out.steeringPressed = True
|
||||
self.assertEqual(_step_to_hud(controller, command, state)['LKAS_Dash_State'], 1)
|
||||
state.out.gearShifter = structs.CarState.GearShifter.neutral
|
||||
self.assertEqual(_step_to_hud(controller, command, state)['LKAS_Dash_State'], 1)
|
||||
|
||||
# Returning to Park restores solid green cleanly.
|
||||
state.out.gearShifter = structs.CarState.GearShifter.park
|
||||
self.assertEqual(_step_to_hud(controller, command, state)['LKAS_Dash_State'], 2)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -7,7 +7,7 @@ from opendbc.car import Bus, structs
|
||||
from opendbc.car.subaru import subarucan
|
||||
from opendbc.car.subaru.stock_aol import ANGLE_CARS, TORQUE_CARS
|
||||
from opendbc.car.subaru.tests.test_ascent_angle import setup_controller, step
|
||||
from opendbc.car.subaru.values import CAR, DBC, SubaruSafetyFlags
|
||||
from opendbc.car.subaru.values import CAR, DBC, FROGGER_ANGLE_SIBLINGS, SubaruSafetyFlags
|
||||
from opendbc.safety.tests import test_subaru_gen2_angle_pair as pair
|
||||
from opendbc.safety.tests.libsafety import libsafety_py
|
||||
|
||||
@@ -71,9 +71,16 @@ def test_dash_uses_current_request_without_mutating_physical_template(car, enabl
|
||||
if any(frame[0] == 0x322 for frame in sends):
|
||||
expected = controller.angle_was_active if car in ANGLE_CARS else (lat_active if marked else enabled)
|
||||
dash = decoder.vl['ES_LKAS_State']
|
||||
if car in ANGLE_CARS or marked or enabled:
|
||||
assert bool(dash['LKAS_ACTIVE']) == expected
|
||||
assert dash['LKAS_Dash_State'] == (2 if expected else 0)
|
||||
if car == CAR.SUBARU_LEGACY_2025:
|
||||
assert bool(dash['LKAS_ACTIVE'])
|
||||
assert dash['LKAS_Dash_State'] == (2 if expected else (1 if state.out.cruiseState.available else 0))
|
||||
elif car in FROGGER_ANGLE_SIBLINGS:
|
||||
assert bool(dash['LKAS_ACTIVE'])
|
||||
assert dash['LKAS_Dash_State'] == (2 if expected else (1 if marked and state.out.cruiseState.available else 0))
|
||||
else:
|
||||
if car in ANGLE_CARS or marked or enabled:
|
||||
assert bool(dash['LKAS_ACTIVE']) == expected
|
||||
assert dash['LKAS_Dash_State'] == (2 if expected else 0)
|
||||
assert state.es_lkas_state_msg == original
|
||||
checked += 1
|
||||
assert checked == 5
|
||||
|
||||
@@ -69,6 +69,19 @@ class TestSupportedSubaruFirmware(unittest.TestCase):
|
||||
self.assertTrue(cp.pcmCruise)
|
||||
self.assertEqual(cp.safetyConfigs[0].safetyParam, word)
|
||||
|
||||
def test_early_crosstrek_shares_firmware_but_has_distinct_vehicle_params(self):
|
||||
platform = CAR.SUBARU_CROSSTREK_2018
|
||||
self.assertNotIn(platform, FW_VERSIONS)
|
||||
shared = FW_VERSIONS[CAR.SUBARU_IMPREZA]
|
||||
live = {(address, sub): {versions[0]} for (_, address, sub), versions in shared.items()}
|
||||
self.assertEqual(match_fw_to_car_exact(live, match_brand='subaru', log=False), {CAR.SUBARU_IMPREZA})
|
||||
for release in (False, True):
|
||||
cp = CarInterface.get_params(platform, {0: {}, 1: {}, 2: {}}, [], False, release, False)
|
||||
self.assertEqual(cp.carFingerprint, platform)
|
||||
self.assertFalse(cp.dashcamOnly)
|
||||
self.assertTrue(cp.pcmCruise)
|
||||
self.assertFalse(cp.openpilotLongitudinalControl or cp.alphaLongitudinalAvailable)
|
||||
|
||||
def test_three_byte_diagnostic_response_is_not_a_camera_identity(self):
|
||||
for platform in (CAR.SUBARU_ASCENT_2023, CAR.SUBARU_LEGACY_2025):
|
||||
for versions in FW_VERSIONS[platform].values():
|
||||
|
||||
@@ -37,6 +37,8 @@ class CarControllerParams:
|
||||
self.STEER_MAX = 1000
|
||||
self.STEER_DELTA_UP = 40
|
||||
self.STEER_DELTA_DOWN = 40
|
||||
elif CP.carFingerprint in EARLY_GLOBAL_TORQUE_CARS:
|
||||
self.STEER_MAX = 3071
|
||||
elif CP.carFingerprint == CAR.SUBARU_IMPREZA_2020:
|
||||
self.STEER_DELTA_UP = 35
|
||||
self.STEER_MAX = 1439
|
||||
@@ -71,6 +73,8 @@ class SubaruSafetyFlags(IntFlag):
|
||||
GEN2 = 1
|
||||
LONG = 2
|
||||
PREGLOBAL_REVERSED_DRIVER_TORQUE = 4
|
||||
EARLY_GLOBAL_TORQUE = 8192
|
||||
PREGLOBAL_OUTBACK_STOCK_ACC = 8
|
||||
LKAS_ANGLE = 16
|
||||
D_PLATFORM = 64
|
||||
FIXED_ANGLE_LIMITS = 128
|
||||
@@ -167,6 +171,11 @@ class CAR(Platforms):
|
||||
SUBARU_IMPREZA = SubaruPlatformConfig(
|
||||
[
|
||||
SubaruCarDocs("Subaru Impreza 2017-19"),
|
||||
],
|
||||
CarSpecs(mass=1568, wheelbase=2.67, steerRatio=15),
|
||||
)
|
||||
SUBARU_CROSSTREK_2018 = SubaruPlatformConfig(
|
||||
[
|
||||
SubaruCarDocs("Subaru Crosstrek 2018-19", video="https://youtu.be/Agww7oE1k-s?t=26"),
|
||||
SubaruCarDocs("Subaru XV 2018-19", video="https://youtu.be/Agww7oE1k-s?t=26"),
|
||||
],
|
||||
@@ -268,6 +277,12 @@ SUBARU_ALT_VERSION_REQUEST = bytes([uds.SERVICE_TYPE.READ_DATA_BY_IDENTIFIER]) +
|
||||
SUBARU_ALT_VERSION_RESPONSE = bytes([uds.SERVICE_TYPE.READ_DATA_BY_IDENTIFIER + 0x40]) + \
|
||||
p16(0xf100)
|
||||
|
||||
EARLY_GLOBAL_TORQUE_CARS = frozenset((CAR.SUBARU_IMPREZA, CAR.SUBARU_CROSSTREK_2018))
|
||||
|
||||
|
||||
FROGGER_ANGLE_SIBLINGS = frozenset((CAR.SUBARU_IMPREZA_2025, CAR.SUBARU_CROSSTREK_2025))
|
||||
|
||||
|
||||
FW_QUERY_CONFIG = FwQueryConfig(
|
||||
validate_fw_match=validate_fw_match,
|
||||
fw_version_regex=br"(?:[\x00-\xff]{4,5}|[\x00-\xff]{8}|[\x00-\xff]{10})",
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import time
|
||||
import numpy as np
|
||||
from opendbc.car import ACCEL_MAX_TAKEOFF
|
||||
from opendbc.can import CANPacker
|
||||
@@ -10,6 +11,7 @@ from opendbc.car.tesla.hw1 import HW1CarController
|
||||
from opendbc.car.tesla.values import CAR, CarControllerParams, TeslaSafetyFlags
|
||||
from opendbc.car.tesla.coop_steering import CooperativeSteeringController
|
||||
from opendbc.car.vehicle_model import VehicleModel
|
||||
from opendbc.car.tesla.speed_sync import SpeedSynchronizer, selected as speed_sync_selected, sync_controller
|
||||
|
||||
|
||||
def get_safety_CP():
|
||||
@@ -22,6 +24,7 @@ def get_safety_CP():
|
||||
class CarController(CarControllerBase):
|
||||
def __init__(self, dbc_names, CP):
|
||||
super().__init__(dbc_names, CP)
|
||||
self.speed_sync = SpeedSynchronizer() if speed_sync_selected(CP) else None
|
||||
if CP.carFingerprint == CAR.TESLA_MODEL_S_PREAP:
|
||||
self.preap = PreAPStockCarController(dbc_names, CP)
|
||||
return
|
||||
@@ -91,6 +94,10 @@ class CarController(CarControllerBase):
|
||||
cntr = (CS.das_control["DAS_controlCounter"] + 1) % 8
|
||||
can_sends.append(self.tesla_can.create_longitudinal_command(13, 0, cntr, CS.out.vEgo, False))
|
||||
|
||||
# Speed sync: append-only mirror; never changes the selected target or actuators.
|
||||
if self.speed_sync is not None:
|
||||
can_sends.extend(sync_controller(self, CC, CS, time.clock_gettime_ns(time.CLOCK_BOOTTIME)))
|
||||
|
||||
# TODO: HUD control
|
||||
new_actuators = actuators.as_builder()
|
||||
new_actuators.steeringAngleDeg = getattr(self, "command_angle", self.apply_angle_last)
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
import copy
|
||||
from opendbc.car.dashboard_speed_limit import Tracker as LimitTracker
|
||||
from opendbc.car.tesla.speed_limit import update_dashboard_limit
|
||||
from opendbc.can import CANDefine, CANParser
|
||||
from opendbc.car import Bus, create_button_events, structs
|
||||
from opendbc.car.common.conversions import Conversions as CV
|
||||
@@ -32,6 +34,7 @@ class CarState(CarStateBase):
|
||||
self.hands_on_level = 0
|
||||
self.das_control = {}
|
||||
return
|
||||
self.dashboard_limit = LimitTracker()
|
||||
self.cooperative_steering = (CP.carFingerprint in (CAR.TESLA_MODEL_3, CAR.TESLA_MODEL_Y) and
|
||||
bool(CP.safetyConfigs[0].safetyParam & TeslaSafetyFlags.COOP_STEERING))
|
||||
self.can_define = CANDefine(DBC[CP.carFingerprint][Bus.party])
|
||||
@@ -160,6 +163,9 @@ class CarState(CarStateBase):
|
||||
|
||||
# Buttons # ToDo: add Gap adjust button
|
||||
|
||||
if self.CP.carFingerprint in (CAR.TESLA_MODEL_3, CAR.TESLA_MODEL_Y):
|
||||
update_dashboard_limit(self.dashboard_limit, cp_party, cp_ap_party, speed_units)
|
||||
|
||||
# Messages needed by carcontroller
|
||||
self.das_control = copy.copy(cp_ap_party.vl["DAS_control"])
|
||||
|
||||
|
||||
@@ -13,6 +13,11 @@ class CarInterface(CarInterfaceBase):
|
||||
CarController = CarController
|
||||
RadarInterface = RadarInterface
|
||||
|
||||
def update(self, can_packets):
|
||||
if self.CC is not None and self.CC.speed_sync is not None:
|
||||
self.CC.speed_sync.observe(can_packets)
|
||||
return super().update(can_packets)
|
||||
|
||||
@staticmethod
|
||||
def _get_params(ret: structs.CarParams, candidate, fingerprint, car_fw, alpha_long, is_release, docs) -> structs.CarParams:
|
||||
ret.brand = "tesla"
|
||||
|
||||
@@ -1,10 +1,20 @@
|
||||
"""Exact modern Tesla screen harness capability and frozen safety selection."""
|
||||
from opendbc.car.tesla.values import CAR, TeslaFlags
|
||||
from opendbc.car.tesla.values import CAR, TeslaFlags, TeslaSafetyFlags
|
||||
|
||||
SCREEN_WORDS = frozenset((512, 513, 1536, 1537, 768, 769, 1792, 1793))
|
||||
BASE_WORDS = frozenset((0, 1, 256, 257))
|
||||
ORDINARY_WORDS = frozenset((2048, 2049, 2304, 2305, 3072, 3073, 3328, 3329))
|
||||
AOL_WORDS = SCREEN_WORDS | ORDINARY_WORDS
|
||||
SPEED_SYNC = int(TeslaSafetyFlags.SCROLL_SPEED_SYNC)
|
||||
# Exact native tesla_sync_param_valid words: scroll speed sync (4096) on a word that carries LONG_CONTROL.
|
||||
SYNC_WORDS = frozenset(SPEED_SYNC | word for word in (1, 257, 513, 769, 1537, 1793, 2049, 2305, 3073, 3329))
|
||||
KNOWN_FLAGS = int(TeslaFlags.MISSING_DAS_SETTINGS | TeslaFlags.HAS_VEHICLE_BUS | TeslaFlags.AOL_SCREEN_BUTTON)
|
||||
|
||||
|
||||
def speed_sync_allowed(cp, word):
|
||||
return bool(word in SYNC_WORDS and cp.carFingerprint in (CAR.TESLA_MODEL_3, CAR.TESLA_MODEL_Y) and cp.openpilotLongitudinalControl and
|
||||
cp.flags & TeslaFlags.HAS_VEHICLE_BUS and not cp.flags & ~KNOWN_FLAGS and
|
||||
bool(word & 512) == bool(cp.flags & TeslaFlags.AOL_SCREEN_BUTTON))
|
||||
|
||||
|
||||
def modern_aol_supported(cp):
|
||||
@@ -12,9 +22,13 @@ def modern_aol_supported(cp):
|
||||
if (cp.brand != 'tesla' or cp.carFingerprint not in (CAR.TESLA_MODEL_3, CAR.TESLA_MODEL_Y) or
|
||||
cp.passive or cp.dashcamOnly or cp.notCar or cp.alternativeExperience not in (0, 32) or len(cp.safetyConfigs) != 1 or
|
||||
int(cp.safetyConfigs[0].safetyModel.raw) != 10 or
|
||||
cp.flags & ~int(TeslaFlags.MISSING_DAS_SETTINGS | TeslaFlags.HAS_VEHICLE_BUS | TeslaFlags.AOL_SCREEN_BUTTON)):
|
||||
cp.flags & ~KNOWN_FLAGS):
|
||||
return False
|
||||
word = int(cp.safetyConfigs[0].safetyParam)
|
||||
if word & SPEED_SYNC:
|
||||
if not speed_sync_allowed(cp, word):
|
||||
return False
|
||||
word &= ~SPEED_SYNC
|
||||
return (word in BASE_WORDS | AOL_WORDS and
|
||||
bool(word & 1) == bool(cp.openpilotLongitudinalControl) and
|
||||
bool(word & 512) == bool(cp.flags & TeslaFlags.AOL_SCREEN_BUTTON) and
|
||||
@@ -31,12 +45,12 @@ modern_screen_supported = screen_tap_supported
|
||||
|
||||
|
||||
def screen_qualified(cp, *, marked_only=False):
|
||||
return bool(screen_tap_supported(cp) and int(cp.safetyConfigs[0].safetyParam) in SCREEN_WORDS and
|
||||
return bool(screen_tap_supported(cp) and (int(cp.safetyConfigs[0].safetyParam) & ~SPEED_SYNC) in SCREEN_WORDS and
|
||||
cp.alternativeExperience in ((32,) if marked_only else (0, 32)))
|
||||
|
||||
|
||||
def modern_aol_qualified(cp, *, marked_only=False):
|
||||
return bool(modern_aol_supported(cp) and int(cp.safetyConfigs[0].safetyParam) in AOL_WORDS and
|
||||
return bool(modern_aol_supported(cp) and (int(cp.safetyConfigs[0].safetyParam) & ~SPEED_SYNC) in AOL_WORDS and
|
||||
cp.alternativeExperience in ((32,) if marked_only else (0, 32)))
|
||||
|
||||
|
||||
@@ -44,7 +58,7 @@ def apply_modern_aol(cp, requested, screen, brake_disengage):
|
||||
if not modern_aol_supported(cp):
|
||||
return
|
||||
use_screen = requested and screen and screen_tap_supported(cp)
|
||||
base = int(cp.safetyConfigs[0].safetyParam) & 257
|
||||
base = int(cp.safetyConfigs[0].safetyParam) & (257 | SPEED_SYNC) # scroll speed sync rides on top of any AOL word
|
||||
cp.flags &= ~int(TeslaFlags.AOL_SCREEN_BUTTON)
|
||||
cp.safetyConfigs[0].safetyParam = base
|
||||
if requested:
|
||||
@@ -56,7 +70,7 @@ def apply_modern_aol(cp, requested, screen, brake_disengage):
|
||||
def apply_screen_button(cp, requested, brake_disengage):
|
||||
if not screen_tap_supported(cp):
|
||||
return
|
||||
base = int(cp.safetyConfigs[0].safetyParam) & 257
|
||||
base = int(cp.safetyConfigs[0].safetyParam) & (257 | SPEED_SYNC)
|
||||
cp.flags &= ~int(TeslaFlags.AOL_SCREEN_BUTTON)
|
||||
cp.safetyConfigs[0].safetyParam = base
|
||||
if requested:
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
"""Tesla fused road-limit evidence for the 7.0 Dashboard producer."""
|
||||
import math
|
||||
from opendbc.car.dashboard_speed_limit import Status, parser_expiry
|
||||
|
||||
|
||||
def update_dashboard_limit(tracker, party, autopilot, speed_units):
|
||||
limit_ns, limit_expiry = parser_expiry(autopilot, 'DAS_status', 'DAS_fusedSpeedLimit')
|
||||
units_ns, units_expiry = parser_expiry(party, 'DI_state', 'DI_speedUnits')
|
||||
stamp = max(limit_ns, units_ns)
|
||||
if stamp <= tracker.observation.observed_ns:
|
||||
return
|
||||
status, speed = Status.UNKNOWN, 0.0
|
||||
expiry = min(limit_expiry, units_expiry)
|
||||
if (limit_ns > 0 and units_ns > 0 and expiry > stamp and party.can_valid and autopilot.can_valid
|
||||
and speed_units in ('MPH', 'KPH')):
|
||||
value = float(autopilot.vl['DAS_status']['DAS_fusedSpeedLimit'])
|
||||
# The DBC scales raw31/NONE to155; raw0 is UNKNOWN, never zero mph.
|
||||
if math.isfinite(value) and 0 < value <= 150:
|
||||
status, speed = Status.VALID, value * (0.44704 if speed_units == 'MPH' else 1 / 3.6)
|
||||
elif value == 155:
|
||||
status = Status.ABSENT
|
||||
tracker.update(stamp, status, speed, valid_until_ns=expiry)
|
||||
@@ -0,0 +1,730 @@
|
||||
"""Speed sync: one-way native selected-speed mirror for the Tesla Model 3/Y. Experimental.
|
||||
|
||||
No speed-control state is written here. Normal control packets are owned by the
|
||||
existing controller. Only a bounded relative wheel request can be returned.
|
||||
|
||||
Each request is one right-wheel frame: a single click (+-1 mph), or a fast flick
|
||||
(+-5 clicks) that moves the Tesla to the next multiple of 5. The Tesla only treats
|
||||
a flick as fast when it starts a new gesture: a scroll soon after the previous one
|
||||
moves the speed by 1. So fast steps are spaced, and the spacing
|
||||
is learned. The panda decides what may be sent. A request the panda does not transmit (no bus-129 return, or a
|
||||
bus-193 rejection) never reached the car, so it is cleared and retried later.
|
||||
"""
|
||||
from dataclasses import dataclass
|
||||
from collections import deque
|
||||
import math
|
||||
|
||||
from opendbc.car.tesla.values import TeslaFlags, TeslaSafetyFlags
|
||||
|
||||
SYNC_FLAG = int(TeslaSafetyFlags.SCROLL_SPEED_SYNC)
|
||||
MODELS = ("TESLA_MODEL_3", "TESLA_MODEL_Y")
|
||||
|
||||
|
||||
def eligible(cp):
|
||||
"""A Model 3/Y with StarPilot longitudinal control, its own cruise and the CAN add-on cable (Vehicle CAN)."""
|
||||
try:
|
||||
return bool(cp.brand == "tesla" and cp.carFingerprint in MODELS and cp.openpilotLongitudinalControl and cp.pcmCruise and
|
||||
not cp.passive and not cp.dashcamOnly and not cp.notCar and cp.flags & TeslaFlags.HAS_VEHICLE_BUS and
|
||||
len(cp.safetyConfigs) == 1 and cp.safetyConfigs[0].safetyParam & TeslaSafetyFlags.LONG_CONTROL)
|
||||
except (AttributeError, TypeError, ValueError, IndexError):
|
||||
return False
|
||||
|
||||
|
||||
def selected(cp):
|
||||
"""The car started with the scroll frame admitted, so the comma may own the set speed and scroll the Tesla's to match.
|
||||
Whether it does follows the saved switch (openpilot/starpilot/car/tesla/set_speed.py)."""
|
||||
try:
|
||||
return bool(eligible(cp) and cp.safetyConfigs[0].safetyParam & SYNC_FLAG)
|
||||
except (AttributeError, TypeError, ValueError, IndexError):
|
||||
return False
|
||||
|
||||
|
||||
def prepare(cp, requested):
|
||||
"""Admit the scroll frame in the car's parameters at startup (the panda sends it only with this bit)."""
|
||||
if eligible(cp):
|
||||
cp.safetyConfigs[0].safetyParam &= ~SYNC_FLAG
|
||||
if requested:
|
||||
cp.safetyConfigs[0].safetyParam |= SYNC_FLAG
|
||||
return cp
|
||||
|
||||
|
||||
NS = 1_000_000_000
|
||||
FRESH_NS = 250_000_000
|
||||
# No Tesla change by SETTLE_NS: the request went unanswered (the updated panda frees its own request after 0.8 s).
|
||||
SETTLE_NS = 1_000_000_000
|
||||
TOKENS_MAX = 30 # panda rate limit: burst of 30 requests...
|
||||
TOKEN_REFILL_NS = 1_050_000_000 # ...then one per second (a little slower here so the panda never refuses)
|
||||
FAST_PAUSE_NS = 2 * NS # after a refused fast step, single clicks for this long
|
||||
MANUAL_COMPLETION_NS = 2 * NS
|
||||
HANDOVER_NS = 100_000_000
|
||||
TEMPLATE_SEND_NS = 100_000_000 # one wheel-frame period (panda allows 250 ms)
|
||||
RETURN_NS = 100_000_000 # panda echoes a transmitted frame on bus 129 within ~5 ms
|
||||
BACKOFF_NS = 300_000_000 # wait after a request the panda refused,
|
||||
BACKOFF_MAX_NS = 2 * NS # doubling on each refusal in a row
|
||||
MANUAL_SETTLE_NS = 600_000_000 # let the Tesla apply the driver's own scroll first
|
||||
FAST_TICKS = 5
|
||||
# Fast-step spacing. Measured: a flick 0.1-0.24 s after the previous scroll moved
|
||||
# the Tesla by 1; the driver's own flicks 0.4 s apart all jumped 5. Start short and
|
||||
# lengthen on each fast step that lands as a single click; shorten again after a
|
||||
# run of good ones. Nothing here ever stops the sync.
|
||||
FAST_GAP_NS = 280_000_000
|
||||
FAST_GAP_STEP_NS = 100_000_000
|
||||
FAST_GAP_MAX_NS = 800_000_000
|
||||
FAST_GAP_RELAX = 30 # good fast steps in a row before trying a shorter gap
|
||||
FAST_RESPONSE_NS = 250_000_000 # Tesla applies a new gesture after ~0.23 s
|
||||
STREAM_STEP_NS = 100_000_000 # a click inside a gesture shows up at the next DI frame
|
||||
ENGAGE_DELAY_NS = 150_000_000 # pandad tells the panda about engagement at 10 Hz
|
||||
MAX_RETRIES = 3 # unanswered clicks retried at one speed before waiting
|
||||
|
||||
|
||||
def neutral_wheel(data):
|
||||
if len(data) != 8 or data[0] & 3 != 1:
|
||||
return False
|
||||
bits = int.from_bytes(data, "little")
|
||||
return (all((bits >> shift) & 3 == 1 for shift in (3, 5, 8, 10, 12, 14)) and
|
||||
data[2] & 63 == 0 and data[3] & 63 == 0 and data[4] & 15 == 0)
|
||||
|
||||
|
||||
def scroll_request(template, ticks):
|
||||
"""Copy a physical neutral frame and set only the right-wheel scroll count."""
|
||||
if not neutral_wheel(template) or ticks not in (-FAST_TICKS, -1, 1, FAST_TICKS):
|
||||
return None
|
||||
data = bytearray(template)
|
||||
data[3] = (data[3] & 0xC0) | (ticks & 0x3F)
|
||||
return (0x3C2, bytes(data), 1)
|
||||
|
||||
|
||||
def plan_step(native, target, allow_fast):
|
||||
"""Return (ticks, expected native) for the next step from native toward target.
|
||||
|
||||
A fast flick lands on the next multiple of 5 in that direction (measured: nearly
|
||||
every flick of 3+ clicks did this in one change). Use it only
|
||||
when that multiple does not pass the target and saves at least one click.
|
||||
"""
|
||||
sign = 1 if target > native else -1
|
||||
if allow_fast:
|
||||
nxt = (native // 5 + 1) * 5 if sign > 0 else ((native - 1) // 5) * 5
|
||||
if abs(nxt - native) >= 2 and (target - nxt) * sign >= 0:
|
||||
return sign * FAST_TICKS, nxt
|
||||
return sign, native + sign
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class SyncAuthority:
|
||||
observed_boot_ns: int
|
||||
target_kph: float
|
||||
is_metric: bool
|
||||
configuration_id: str
|
||||
software_owned: bool
|
||||
document_hash: str = ""
|
||||
vehicle_hash: str = ""
|
||||
drive_start_ns: int = 0
|
||||
manual_receipts: tuple = ()
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ManualReceipt:
|
||||
boot_ns: int
|
||||
frame_index: int
|
||||
name: str
|
||||
fast: bool
|
||||
worker_session: str
|
||||
sequence: int
|
||||
document_hash: str
|
||||
vehicle_hash: str
|
||||
drive_start_ns: int
|
||||
processed_boot_ns: int
|
||||
target_kph: float
|
||||
|
||||
|
||||
@dataclass
|
||||
class Pending:
|
||||
before: float
|
||||
direction: int
|
||||
units: int
|
||||
sent_ns: int
|
||||
data: bytes
|
||||
ticks: int = 0
|
||||
retry: bool = False
|
||||
returned: bool = False
|
||||
expected: int = 0
|
||||
gap_ns: int = 0 # time since the previous scroll when sent
|
||||
|
||||
|
||||
class SpeedSynchronizer:
|
||||
def __init__(self):
|
||||
self.template = None
|
||||
self.template_ns = 0
|
||||
self.driver_ns = 0
|
||||
self.native_ns = 0
|
||||
self.native = None
|
||||
self.units = None
|
||||
self.cruise_state = None
|
||||
self.autopark = None
|
||||
self.counter = None
|
||||
self.di_valid = False
|
||||
self.di_key = (0, -1)
|
||||
self.wheel_stamp = 0
|
||||
self.pending = None
|
||||
self.unanswered = None
|
||||
self.unanswered_count = 0
|
||||
self.last_sent = 0
|
||||
self.last_template_sent = 0
|
||||
self.last_update = 0
|
||||
self.backoff_until = 0
|
||||
self.target = None
|
||||
self.steps = 0
|
||||
self.blocked = None
|
||||
self.status = "idle"
|
||||
self.active = False
|
||||
self.authority_id = None
|
||||
self.manual_armed = False
|
||||
self.manual_active = None
|
||||
self.manual_queue = []
|
||||
self.manual_receipts = {}
|
||||
self.manual_receipt_acks = []
|
||||
self.manual_ack_key = (0, -1)
|
||||
self.wheel_key = (0, -1)
|
||||
self.wheel_held = False # the last wheel frame was a tilt or press without a scroll
|
||||
self.gas_was_pressed = False
|
||||
self.handover_until = 0
|
||||
self.response_ns = 0
|
||||
self.history = deque(maxlen=32)
|
||||
self.failure_logged = False
|
||||
# Nothing is switched off for good: a refusal only pauses that feature.
|
||||
self.fast_paused_until = 0
|
||||
self.retry_refused = False
|
||||
self.tokens = TOKENS_MAX
|
||||
self.refill_ns = 0
|
||||
self.last_scroll_ns = 0 # last scroll the Tesla saw: our sent request or the driver's
|
||||
self.fast_gap_ns = FAST_GAP_NS
|
||||
self.fast_streak = 0
|
||||
self.engaged_ns = 0
|
||||
self.refusals = 0
|
||||
self.notices = []
|
||||
self.noticed = set()
|
||||
|
||||
def observe(self, packets):
|
||||
"""Use original arrival timestamps; cached values never refresh freshness."""
|
||||
for stamp, frames in packets:
|
||||
if type(stamp) is not int or stamp <= 0:
|
||||
continue
|
||||
for frame_index, (address, data, bus) in enumerate(frames):
|
||||
if address == 0x3C2 and bus in (129, 193):
|
||||
# Panda echo of a frame we asked it to send: 129 = transmitted,
|
||||
# 193 = refused by safety. Exact bytes and clock must match.
|
||||
p = self.pending
|
||||
if p is not None and not p.returned and stamp >= p.sent_ns and bytes(data) == p.data:
|
||||
if bus == 129:
|
||||
p.returned = True
|
||||
self.last_scroll_ns = max(self.last_scroll_ns, p.sent_ns)
|
||||
self.refusals = 0
|
||||
self.steps += 1
|
||||
self.tokens = max(self.tokens - 1, 0)
|
||||
else:
|
||||
self._not_transmitted(p, "panda_rejected")
|
||||
continue
|
||||
if address == 0x3C2 and bus == 1:
|
||||
key = (stamp, frame_index)
|
||||
if key == self.wheel_key:
|
||||
continue
|
||||
if key < self.wheel_key:
|
||||
self.template = None
|
||||
self.blocked = "wheel_clock_reversal"
|
||||
continue
|
||||
self.wheel_key = key
|
||||
self.wheel_stamp = stamp
|
||||
if len(data) != 8:
|
||||
self.template = None
|
||||
if self.manual_active:
|
||||
self._pause_manual("ambiguous_manual_input")
|
||||
self.manual_armed = False
|
||||
continue
|
||||
mux = data[0] & 3
|
||||
if mux == 0:
|
||||
continue
|
||||
if mux != 1:
|
||||
self.template = None
|
||||
if self.manual_active:
|
||||
self._pause_manual("ambiguous_manual_input")
|
||||
self.manual_armed = False
|
||||
continue
|
||||
self._observe_manual(data, stamp, frame_index)
|
||||
if neutral_wheel(data):
|
||||
self.template, self.template_ns = bytes(data), stamp
|
||||
else:
|
||||
self.template = None
|
||||
self.driver_ns = stamp
|
||||
self.last_scroll_ns = max(self.last_scroll_ns, stamp)
|
||||
# Genuine controls take priority. The request stays outstanding
|
||||
# until the Tesla's speed changes; direction is then recomputed
|
||||
# from reality, so nothing is repeated blindly.
|
||||
if self.pending is not None:
|
||||
self._record("input_during_request", stamp)
|
||||
elif address == 0x286 and bus == 0:
|
||||
# Several DI frames can share one receive batch (same stamp), so
|
||||
# order by (stamp, index) like the wheel frames above.
|
||||
key = (stamp, frame_index)
|
||||
if key <= self.di_key:
|
||||
if key < self.di_key:
|
||||
self.blocked = "feedback_clock_reversal"
|
||||
self.native_ns = 0
|
||||
continue
|
||||
self.di_key = key
|
||||
if len(data) != 8 or data[0] != ((0x86 + 2 + sum(data[1:])) & 0xFF):
|
||||
self.di_valid = False
|
||||
continue
|
||||
counter = data[1] & 15
|
||||
advancing = self.counter is None or (counter - self.counter) % 16 == 1
|
||||
self.counter = counter
|
||||
# Same rule as the panda: a frame after a counter gap is not used,
|
||||
# and nothing may be sent until the next in-sequence frame.
|
||||
self.di_valid = advancing
|
||||
if not advancing:
|
||||
continue
|
||||
bits = int.from_bytes(data, "little")
|
||||
self.native = ((bits >> 15) & 511) * .5
|
||||
self.units = (bits >> 24) & 1 # 0 mph, 1 km/h
|
||||
self.cruise_state = (bits >> 12) & 7
|
||||
self.autopark = (bits >> 25) & 15
|
||||
self.native_ns = stamp
|
||||
|
||||
def _observe_manual(self, data, stamp, frame_index):
|
||||
right = data[3] & 63
|
||||
right = right - 64 if right >= 32 else right
|
||||
if right:
|
||||
released = bytearray(data)
|
||||
released[3] &= 0xC0
|
||||
name = "right_wheel_up" if right > 0 else "right_wheel_down"
|
||||
if self.manual_active is None and self.wheel_held and abs(right) == 1 and neutral_wheel(released):
|
||||
# A wheel tilted or pressed often clicks once as it springs back. That click ends the nudge and is not a
|
||||
# scroll: the comma does not act on it, so nothing waits for it, and the Tesla's change is corrected below.
|
||||
self._record("nudge_release_click", stamp)
|
||||
self.wheel_held = False
|
||||
self.manual_armed = False
|
||||
return
|
||||
if (not neutral_wheel(released) or
|
||||
self.manual_active is None and not (self.manual_armed and self.template is not None and
|
||||
0 < self.template_ns <= stamp <= self.template_ns + FRESH_NS) or
|
||||
self.manual_active is not None and self.manual_active[0] != name):
|
||||
self._pause_manual("ambiguous_manual_input")
|
||||
return
|
||||
peak = max(abs(right), self.manual_active[1] if self.manual_active else 0)
|
||||
self.manual_active = (name, peak)
|
||||
self.manual_armed = False
|
||||
self.wheel_held = False
|
||||
elif neutral_wheel(data):
|
||||
if self.manual_active:
|
||||
if len(self.manual_queue) >= 16:
|
||||
self._fail("manual_input_overflow")
|
||||
else:
|
||||
name, peak = self.manual_active
|
||||
self.manual_queue.append((stamp, frame_index, name, peak >= 2))
|
||||
self.manual_active = None
|
||||
self.manual_armed = True
|
||||
self.wheel_held = False
|
||||
else:
|
||||
if self.manual_active:
|
||||
self._pause_manual("ambiguous_manual_input")
|
||||
self.manual_active = None
|
||||
self.manual_armed = False
|
||||
self.wheel_held = True
|
||||
|
||||
def _pause_manual(self, reason):
|
||||
"""Wheel input that cannot be read as one clean scroll. The comma's own input reader ignores the same gesture, so
|
||||
nothing waits for it: sync carries on and, after the driver's settle time, puts the Tesla back on the comma's speed.
|
||||
Logged once per engagement."""
|
||||
self._notice(reason)
|
||||
self._record(reason, self.last_update)
|
||||
self.manual_active = None
|
||||
self.manual_armed = False
|
||||
|
||||
def accept_manual_receipts(self, authority, now_ns):
|
||||
# Metadata may arrive before Card sees the corresponding CAN batch. Cache
|
||||
# only bounded, validated receipts; never infer a gesture from the receipt.
|
||||
if type(authority.manual_receipts) is not tuple or len(authority.manual_receipts) > 16:
|
||||
self._fail("invalid_manual_receipts")
|
||||
return
|
||||
for receipt in authority.manual_receipts:
|
||||
if not isinstance(receipt, ManualReceipt):
|
||||
continue
|
||||
try:
|
||||
good = (
|
||||
type(receipt.boot_ns) is int and type(receipt.processed_boot_ns) is int and
|
||||
0 < receipt.boot_ns <= receipt.processed_boot_ns <= now_ns and
|
||||
type(receipt.frame_index) is int and 0 <= receipt.frame_index < 4096 and
|
||||
receipt.name in ("right_wheel_up", "right_wheel_down") and type(receipt.fast) is bool and
|
||||
type(receipt.worker_session) is str and len(receipt.worker_session) == 32 and
|
||||
all(c in "0123456789abcdef" for c in receipt.worker_session) and
|
||||
type(receipt.sequence) is int and receipt.sequence > 0 and
|
||||
receipt.document_hash == authority.document_hash and len(authority.document_hash) == 64 and
|
||||
receipt.vehicle_hash == authority.vehicle_hash and len(authority.vehicle_hash) == 64 and
|
||||
type(receipt.drive_start_ns) is int and receipt.drive_start_ns == authority.drive_start_ns > 0 and
|
||||
type(receipt.target_kph) in (int, float) and math.isfinite(receipt.target_kph) and
|
||||
0 < receipt.target_kph < 255)
|
||||
except (AttributeError, TypeError, ValueError):
|
||||
good = False
|
||||
if not good:
|
||||
continue
|
||||
if now_ns > receipt.boot_ns + MANUAL_COMPLETION_NS:
|
||||
# Validated but expired metadata cannot complete a gesture. Dispose of
|
||||
# it explicitly so it cannot occupy the producer queue indefinitely;
|
||||
# update() independently faults any unconfirmed observed gesture.
|
||||
self._ack_manual_receipt(receipt)
|
||||
continue
|
||||
key = (receipt.boot_ns, receipt.frame_index)
|
||||
if key <= self.manual_ack_key:
|
||||
self._ack_manual_receipt(receipt)
|
||||
continue
|
||||
if key not in self.manual_receipts and len(self.manual_receipts) >= 16:
|
||||
self._fail("manual_receipt_overflow")
|
||||
return
|
||||
if key in self.manual_receipts and self.manual_receipts[key] != receipt:
|
||||
self._fail("conflicting_manual_receipt")
|
||||
return
|
||||
self.manual_receipts[key] = receipt
|
||||
self._ack_manual_receipt(receipt)
|
||||
self.manual_receipts = {key: r for key, r in self.manual_receipts.items() if now_ns <= r.boot_ns + MANUAL_COMPLETION_NS}
|
||||
while self.manual_queue:
|
||||
stamp, index, name, fast = self.manual_queue[0]
|
||||
receipt = self.manual_receipts.get((stamp, index))
|
||||
if receipt is None:
|
||||
break
|
||||
if (receipt.name, receipt.fast) != (name, fast):
|
||||
self._fail("manual_receipt_mismatch")
|
||||
return
|
||||
self.manual_queue.pop(0)
|
||||
self.manual_receipts.pop((stamp, index))
|
||||
self.manual_ack_key = (stamp, index)
|
||||
self.target = None # Re-read the processed target; never write its owner.
|
||||
|
||||
def _ack_manual_receipt(self, receipt):
|
||||
# Acknowledge metadata custody only; this never acknowledges or repeats a
|
||||
# speed action. Card removes exactly these immutable receipts next frame.
|
||||
if receipt not in self.manual_receipt_acks:
|
||||
if len(self.manual_receipt_acks) >= 16:
|
||||
self._fail("manual_receipt_ack_overflow")
|
||||
else:
|
||||
self.manual_receipt_acks.append(receipt)
|
||||
|
||||
def take_manual_receipt_acks(self):
|
||||
result = tuple(self.manual_receipt_acks)
|
||||
self.manual_receipt_acks.clear()
|
||||
return result
|
||||
|
||||
def _fail(self, reason):
|
||||
if not self.blocked:
|
||||
self._record("fault", self.last_update, reason=reason)
|
||||
self.blocked = reason
|
||||
self.pending = None
|
||||
self.unanswered = None
|
||||
self._reset_handover()
|
||||
self.status = reason
|
||||
return None
|
||||
|
||||
def _notice(self, kind, **extra):
|
||||
# One log line per kind per engagement; these are recoverable pauses.
|
||||
if kind not in self.noticed:
|
||||
self.noticed.add(kind)
|
||||
self.notices.append(dict(kind=kind, native=self.native, target=self.target, **extra))
|
||||
|
||||
def _not_transmitted(self, p, reason):
|
||||
"""The panda never put this frame on the bus, so the car never saw it."""
|
||||
self.pending = None
|
||||
if abs(p.ticks) > 1:
|
||||
# Use single clicks for a while, then try fast steps again.
|
||||
self.fast_paused_until = self.last_update + FAST_PAUSE_NS
|
||||
self._notice("fast_step_refused", reason=reason)
|
||||
elif p.retry:
|
||||
# Wait for the Tesla's speed to change for this request only.
|
||||
self.retry_refused = True
|
||||
self._notice("retry_refused", reason=reason)
|
||||
else:
|
||||
self._notice("request_not_transmitted", reason=reason)
|
||||
self.backoff_until = self.last_update + min(BACKOFF_NS << min(self.refusals, 3), BACKOFF_MAX_NS)
|
||||
self.refusals += 1
|
||||
self._record("not_transmitted", self.last_update, reason=reason, ticks=p.ticks)
|
||||
|
||||
def _learn_fast_gap(self, p):
|
||||
landed = math.floor(self.native + .5)
|
||||
before = math.floor(p.before + .5)
|
||||
if landed == p.expected:
|
||||
self.fast_streak += 1
|
||||
if self.fast_streak >= FAST_GAP_RELAX and self.fast_gap_ns > FAST_GAP_NS:
|
||||
self.fast_gap_ns = max(self.fast_gap_ns - FAST_GAP_STEP_NS, FAST_GAP_NS)
|
||||
self.fast_streak = 0
|
||||
elif abs(landed - before) == 1 and abs(p.expected - before) >= 2:
|
||||
# The Tesla took it as part of the previous gesture: space them further.
|
||||
self.fast_streak = 0
|
||||
if p.gap_ns < FAST_GAP_MAX_NS:
|
||||
self.fast_gap_ns = min(max(self.fast_gap_ns, p.gap_ns) + FAST_GAP_STEP_NS, FAST_GAP_MAX_NS)
|
||||
self._notice("fast_step_landed_single", gap_ns=p.gap_ns, fast_gap_ns=self.fast_gap_ns)
|
||||
self._record("fast_landed_single", self.last_update, gap_ns=p.gap_ns, fast_gap_ns=self.fast_gap_ns)
|
||||
|
||||
def _reset_handover(self):
|
||||
self.gas_was_pressed = False
|
||||
self.handover_until = 0
|
||||
|
||||
def _record(self, event, now_ns, **extra):
|
||||
self.history.append(dict(event=event, boot_ns=now_ns, native=self.native,
|
||||
target=self.target, native_ns=self.native_ns,
|
||||
template_ns=self.template_ns, last_sent=self.last_sent,
|
||||
units=self.units, cruise_state=self.cruise_state, **extra))
|
||||
|
||||
def _resolve_pending(self, now_ns):
|
||||
"""Advance the outstanding request. Returns True while it still blocks sending."""
|
||||
p = self.pending
|
||||
if p is None:
|
||||
return False
|
||||
if self.units is not None and self.units != p.units:
|
||||
self._fail("units_changed_during_request")
|
||||
return True
|
||||
if not p.returned and now_ns - p.sent_ns >= RETURN_NS:
|
||||
self._not_transmitted(p, "no_bus_return")
|
||||
return True
|
||||
if self.native_ns > p.sent_ns and self.native != p.before:
|
||||
# Fresh selected-speed feedback releases one outstanding request.
|
||||
# This is not an acknowledgement of command delivery or input origin:
|
||||
# Tesla may change its selection independently. Recompute from reality.
|
||||
self.pending = None
|
||||
self.unanswered = None
|
||||
self.unanswered_count = 0
|
||||
self.retry_refused = False
|
||||
self.response_ns = self.native_ns
|
||||
if abs(p.ticks) == FAST_TICKS:
|
||||
self._learn_fast_gap(p)
|
||||
self._record("native_response", now_ns, before=p.before, sent_ns=p.sent_ns, ticks=p.ticks)
|
||||
self.status = "native_speed_changed"
|
||||
return False
|
||||
if now_ns - p.sent_ns >= SETTLE_NS:
|
||||
# Unanswered. The panda keeps its own request open until the speed
|
||||
# changes (or, with the updated firmware, until its 1 s timeout).
|
||||
self.pending = None
|
||||
self.unanswered = p
|
||||
self.unanswered_count += 1
|
||||
self._notice("no_native_response", before=p.before, ticks=p.ticks)
|
||||
self._record("unanswered", now_ns, before=p.before, ticks=p.ticks)
|
||||
return True
|
||||
self.status = "waiting_for_response"
|
||||
return True
|
||||
|
||||
def update(self, now_ns, *, target_kph, enabled, safe, longitudinal_active=True, gas_pressed=False):
|
||||
if not enabled:
|
||||
self.pending = None
|
||||
self.unanswered = None
|
||||
self.unanswered_count = 0
|
||||
self.retry_refused = False
|
||||
self.target = None
|
||||
self.steps = 0
|
||||
self.blocked = None
|
||||
self.active = False
|
||||
self.authority_id = None
|
||||
self._reset_handover()
|
||||
self.response_ns = 0
|
||||
self.backoff_until = 0
|
||||
self.engaged_ns = 0
|
||||
self.failure_logged = False
|
||||
self.noticed.clear()
|
||||
self.history.clear()
|
||||
self.manual_armed = bool(self.template is not None and
|
||||
0 < self.template_ns <= now_ns <= self.template_ns + FRESH_NS)
|
||||
self.manual_active = None
|
||||
self.manual_queue.clear()
|
||||
self.manual_receipts.clear()
|
||||
self.manual_receipt_acks.clear()
|
||||
self.manual_ack_key = self.wheel_key
|
||||
self.status = "inactive"
|
||||
self.last_update = now_ns
|
||||
return None
|
||||
if type(now_ns) is not int or now_ns <= 0 or (self.last_update and now_ns <= self.last_update):
|
||||
return self._fail("controller_clock_reversal")
|
||||
gap = bool(self.last_update and now_ns - self.last_update > FRESH_NS)
|
||||
self.last_update = now_ns
|
||||
self.active = True
|
||||
if not self.engaged_ns:
|
||||
self.engaged_ns = now_ns
|
||||
if self.blocked:
|
||||
self.status = self.blocked
|
||||
return None
|
||||
if self._resolve_pending(now_ns) and self.pending is not None:
|
||||
return None
|
||||
if self.blocked:
|
||||
return None
|
||||
if gap:
|
||||
# A late controller frame only pauses this frame; a request is never
|
||||
# sent on timing that has not been observed continuously.
|
||||
self._reset_handover()
|
||||
self.status = "controller_clock_gap"
|
||||
return None
|
||||
# Past this bound no matching receipt can pass accept_manual_receipts: the comma did not act on that scroll
|
||||
# (it refused it, or never saw it). Drop it and carry on; the Tesla's change is then corrected like any other
|
||||
# change of its own. Never infer completion or repeat the input.
|
||||
if self.manual_queue and now_ns > self.manual_queue[0][0] + MANUAL_COMPLETION_NS:
|
||||
dropped = [entry for entry in self.manual_queue if now_ns > entry[0] + MANUAL_COMPLETION_NS]
|
||||
self.manual_queue = [entry for entry in self.manual_queue if entry not in dropped]
|
||||
self.manual_ack_key = max(self.manual_ack_key, (dropped[-1][0], dropped[-1][1]))
|
||||
self._notice("manual_action_unconfirmed", dropped=len(dropped))
|
||||
self._record("manual_action_unconfirmed", now_ns, dropped=len(dropped))
|
||||
self.target = None
|
||||
if not safe:
|
||||
self._reset_handover()
|
||||
self.target = None
|
||||
self.status = "inhibited"
|
||||
return None
|
||||
if not (0 < self.native_ns <= now_ns <= self.native_ns + FRESH_NS and self.di_valid and
|
||||
self.native is not None and self.native > 0 and
|
||||
self.cruise_state in (2, 4) and self.autopark not in (3, 4, 9)):
|
||||
self._reset_handover()
|
||||
self.status = "waiting_for_native_speed"
|
||||
return None
|
||||
if not math.isfinite(target_kph) or not 0 < target_kph < 255:
|
||||
self._reset_handover()
|
||||
self.status = "invalid_target"
|
||||
return None
|
||||
# Match the displayed selected speed in Tesla's units, not actual vehicle
|
||||
# speed or a transient model/curve/lead slowdown.
|
||||
target = math.floor((target_kph if self.units else target_kph / 1.609344) + .5)
|
||||
if target <= 0:
|
||||
self.status = "invalid_target"
|
||||
return None
|
||||
target_key = (target, self.units)
|
||||
if self.target != target_key:
|
||||
self.target = target_key
|
||||
# Card and controls publish independently. A genuine pedal release may
|
||||
# precede longActive by a frame; never transmit while neither current
|
||||
# authority is present.
|
||||
if self.gas_was_pressed and not gas_pressed:
|
||||
self.handover_until = now_ns + HANDOVER_NS
|
||||
self.gas_was_pressed = bool(gas_pressed)
|
||||
authorized = bool(longitudinal_active or gas_pressed)
|
||||
if authorized:
|
||||
self.handover_until = 0
|
||||
elif not (self.handover_until and now_ns < self.handover_until):
|
||||
self._reset_handover()
|
||||
self.status = "inhibited"
|
||||
return None
|
||||
if self.manual_active is not None or self.manual_queue:
|
||||
self.status = "waiting_for_manual_processing"
|
||||
return None
|
||||
if not authorized:
|
||||
if self.status != "waiting_for_handover":
|
||||
self._record("handover_wait", now_ns, until_ns=self.handover_until)
|
||||
self.status = "waiting_for_handover"
|
||||
return None
|
||||
native = math.floor(self.native + .5)
|
||||
if native == target:
|
||||
self.unanswered = None
|
||||
self.unanswered_count = 0
|
||||
self.status = "matched"
|
||||
return None
|
||||
# The driver's own scroll takes 0.18-0.4 s to reach the Tesla's selected
|
||||
# speed (measured). A request in that window can cancel a fast flick, so
|
||||
# let the Tesla act on it first.
|
||||
if self.driver_ns and now_ns < self.driver_ns + MANUAL_SETTLE_NS:
|
||||
self.status = "waiting_for_driver_scroll"
|
||||
return None
|
||||
retry = False
|
||||
if self.unanswered is not None:
|
||||
u = self.unanswered
|
||||
# The Tesla moved, or the comma now wants the other way (the Tesla was at its own limit in the old direction):
|
||||
# the unanswered request says nothing about this one.
|
||||
if (self.native_ns > u.sent_ns and self.native != u.before) or u.direction != (1 if target > native else -1):
|
||||
self.unanswered = None
|
||||
self.unanswered_count = 0
|
||||
self.retry_refused = False
|
||||
elif self.retry_refused or self.unanswered_count > MAX_RETRIES:
|
||||
# e.g. the Tesla is at its own speed limit; don't keep scrolling.
|
||||
self.status = "waiting_for_native_change"
|
||||
return None
|
||||
else:
|
||||
retry = True
|
||||
if now_ns < self.backoff_until:
|
||||
self.status = "backoff"
|
||||
return None
|
||||
# The panda only learns that comma engaged from pandad's next heartbeat.
|
||||
if now_ns < self.engaged_ns + ENGAGE_DELAY_NS:
|
||||
self.status = "waiting_for_panda_engage"
|
||||
return None
|
||||
# Mirror the panda's rate limit so it never has to refuse a request.
|
||||
if self.refill_ns == 0:
|
||||
self.refill_ns = now_ns
|
||||
while self.tokens < TOKENS_MAX and now_ns - self.refill_ns >= TOKEN_REFILL_NS:
|
||||
self.tokens += 1
|
||||
self.refill_ns += TOKEN_REFILL_NS
|
||||
if self.tokens >= TOKENS_MAX:
|
||||
self.refill_ns = now_ns
|
||||
if self.tokens <= 0:
|
||||
self.status = "rate_limited"
|
||||
return None
|
||||
# Any physical neutral frame newer than the last one used, still current.
|
||||
if not (self.template is not None and 0 < self.template_ns <= now_ns <= self.template_ns + TEMPLATE_SEND_NS and
|
||||
self.template_ns > self.last_template_sent):
|
||||
self.status = "waiting_for_neutral_wheel"
|
||||
return None
|
||||
ticks, expected = plan_step(native, target, allow_fast=now_ns >= self.fast_paused_until and self.units == 0)
|
||||
gap_ns = now_ns - self.last_scroll_ns if self.last_scroll_ns else 10 * NS
|
||||
if abs(ticks) == FAST_TICKS and gap_ns < self.fast_gap_ns:
|
||||
# Too soon for the Tesla to start a new gesture. Clicks give 1 mph per
|
||||
# 0.1 s and each one restarts the gap, so while fast steps are quicker
|
||||
# overall (gap under 0.5 s) wait for them on any change of 5 or more.
|
||||
# For a short change, wait only if that beats clicking there.
|
||||
wait_ns = self.fast_gap_ns - gap_ns
|
||||
if ((self.fast_gap_ns < FAST_TICKS * STREAM_STEP_NS and abs(target - native) >= FAST_TICKS) or
|
||||
wait_ns + FAST_RESPONSE_NS <= abs(expected - native) * STREAM_STEP_NS):
|
||||
self.status = "waiting_for_fast_gap"
|
||||
return None
|
||||
ticks, expected = plan_step(native, target, allow_fast=False)
|
||||
message = scroll_request(self.template, ticks)
|
||||
if message is None:
|
||||
return self._fail("invalid_template")
|
||||
direction = 1 if ticks > 0 else -1
|
||||
self.pending = Pending(self.native, direction, self.units, now_ns, message[1], ticks=ticks, retry=retry,
|
||||
expected=expected, gap_ns=gap_ns)
|
||||
# A retry keeps the unanswered request on record until the speed changes,
|
||||
# so a refused retry falls back to waiting rather than retrying forever.
|
||||
self.last_sent = now_ns
|
||||
self.last_template_sent = self.template_ns
|
||||
self.status = "request_pending"
|
||||
self._record("request", now_ns, direction=direction, ticks=ticks, retry=retry, gap_ns=gap_ns)
|
||||
return message
|
||||
|
||||
|
||||
def sync_controller(controller, CC, CS, now_ns):
|
||||
"""Read-only mirror. now_ns is BOOTTIME, matching the CAN producer clock."""
|
||||
from opendbc.car.structs import CarState
|
||||
synchronizer = controller.speed_sync
|
||||
out = CS.out
|
||||
authority = getattr(controller, "speed_sync_authority", None)
|
||||
authority_valid = bool(
|
||||
isinstance(authority, SyncAuthority) and authority.software_owned is True and
|
||||
type(authority.observed_boot_ns) is int and
|
||||
0 < authority.observed_boot_ns <= now_ns <= authority.observed_boot_ns + 100_000_000 and
|
||||
type(authority.is_metric) is bool and synchronizer.units == int(authority.is_metric) and
|
||||
type(authority.target_kph) in (int, float) and math.isfinite(authority.target_kph) and authority.target_kph == float(out.vCruise) and
|
||||
type(authority.configuration_id) is str and len(authority.configuration_id) == 64 and all(c in "0123456789abcdef" for c in authority.configuration_id))
|
||||
if authority_valid and CC.enabled:
|
||||
if synchronizer.authority_id not in (None, authority.configuration_id):
|
||||
synchronizer._fail("configuration_changed")
|
||||
synchronizer.authority_id = authority.configuration_id
|
||||
synchronizer.accept_manual_receipts(authority, now_ns)
|
||||
safe = (authority_valid and out.canValid and not out.canTimeout and out.cruiseState.enabled and
|
||||
out.gearShifter == CarState.GearShifter.drive and
|
||||
not (out.standstill or out.brakePressed or out.accFaulted or out.stockAeb or out.stockFcw or
|
||||
out.espDisabled or out.espActive or out.vehicleSensorsInvalid or out.carNotReady or out.doorOpen or out.seatbeltUnlatched or
|
||||
out.steerFaultPermanent or out.steerFaultTemporary or out.stockLkas or
|
||||
out.invalidLkasSetting or CS.autopark))
|
||||
message = synchronizer.update(now_ns, target_kph=float(out.vCruise),
|
||||
enabled=bool(CC.enabled and not CC.cruiseControl.cancel), safe=bool(safe),
|
||||
longitudinal_active=bool(CC.longActive), gas_pressed=bool(out.gasPressed))
|
||||
if not authority_valid and CC.enabled and not synchronizer.blocked:
|
||||
synchronizer.status = "owner_or_config_ineligible"
|
||||
if synchronizer.notices or (synchronizer.blocked and not synchronizer.failure_logged):
|
||||
from opendbc.car.carlog import carlog
|
||||
for notice in synchronizer.notices:
|
||||
carlog.warning("speed sync paused: %s", dict(notice, boot_ns=now_ns, history=list(synchronizer.history)[-8:]))
|
||||
synchronizer.notices.clear()
|
||||
if synchronizer.blocked and not synchronizer.failure_logged:
|
||||
synchronizer.failure_logged = True
|
||||
carlog.warning("speed sync stopped: %s", {"reason": synchronizer.blocked, "boot_ns": now_ns,
|
||||
"native": synchronizer.native, "target": synchronizer.target, "history": list(synchronizer.history)})
|
||||
return [] if message is None else [message]
|
||||
@@ -0,0 +1,210 @@
|
||||
"""Startup preferences keep the exact speed-sync safety words: co-op steering and Always On Lateral compose with it."""
|
||||
from pathlib import Path
|
||||
import re
|
||||
|
||||
import pytest
|
||||
from opendbc.car import gen_empty_fingerprint
|
||||
from opendbc.car.structs import car
|
||||
from opendbc.car.tesla.interface import CarInterface
|
||||
from opendbc.car.tesla.carcontroller import CarController
|
||||
from opendbc.car.tesla.carstate import CarState
|
||||
from opendbc.car.tesla.screen_button import (SYNC_WORDS, apply_modern_aol, apply_screen_button, modern_aol_qualified, modern_aol_supported,
|
||||
screen_qualified, screen_tap_supported, speed_sync_allowed)
|
||||
from opendbc.car.tesla.speed_sync import SYNC_FLAG, prepare as apply_speed_sync, selected
|
||||
from opendbc.car.tesla.values import CAR, CANBUS, DBC, TeslaFlags
|
||||
from openpilot.starpilot.car.tesla.coop_preferences import prepare as apply_cooperative, supported
|
||||
|
||||
MODERN = (CAR.TESLA_MODEL_3, CAR.TESLA_MODEL_Y)
|
||||
# The words tesla_sync_param_valid accepts (safety/modes/tesla_speed_sync.h): 4096 on a word that carries LONG_CONTROL.
|
||||
NATIVE_SYNC_WORDS = frozenset(4096 | word for word in (1, 257, 513, 769, 1537, 1793, 2049, 2305, 3073, 3329))
|
||||
|
||||
|
||||
def sync_params(candidate=CAR.TESLA_MODEL_3, long=True):
|
||||
"""A Model 3/Y with the add-on cable, as it leaves startup with Comma can set speed on Tesla dashboard requested."""
|
||||
fingerprint = gen_empty_fingerprint()
|
||||
fingerprint[CANBUS.vehicle][0x3DF] = 8
|
||||
fingerprint[CANBUS.autopilot_party][0x489] = 8
|
||||
return apply_speed_sync(CarInterface.get_params(candidate, fingerprint, [], long, False, False), True)
|
||||
|
||||
|
||||
def raw(cp):
|
||||
return cp.as_reader().as_builder().to_bytes()
|
||||
|
||||
|
||||
def startup(cp, coop, screen=False, brake=False):
|
||||
apply_screen_button(cp, screen, brake)
|
||||
apply_cooperative(cp, coop)
|
||||
return cp
|
||||
|
||||
|
||||
def expected_word(coop, screen, brake):
|
||||
return 4097 | (256 if coop else 0) | ((512 | (1024 if brake else 0)) if screen else 0)
|
||||
|
||||
|
||||
def assert_rejected(cp):
|
||||
before = raw(cp)
|
||||
assert not supported(cp)
|
||||
assert not screen_tap_supported(cp)
|
||||
assert not screen_qualified(cp)
|
||||
assert not modern_aol_supported(cp)
|
||||
apply_cooperative(cp, True)
|
||||
apply_screen_button(cp, True, True)
|
||||
apply_modern_aol(cp, True, True, True)
|
||||
assert raw(cp) == before
|
||||
|
||||
|
||||
def test_python_words_mirror_the_native_list():
|
||||
assert SYNC_WORDS == NATIVE_SYNC_WORDS
|
||||
header = (Path(__file__).parents[3] / 'safety/modes/tesla_speed_sync.h').read_text()
|
||||
body = header[header.index('static bool tesla_sync_param_valid'):]
|
||||
assert frozenset(4096 | int(word) for word in re.findall(r'base == (\d+)U', body)) == SYNC_WORDS
|
||||
assert 'GET_FLAG(param, 4096U)' in body
|
||||
|
||||
|
||||
@pytest.mark.parametrize('candidate', MODERN)
|
||||
def test_selected_word_precondition(candidate):
|
||||
cp = sync_params(candidate)
|
||||
assert cp.safetyConfigs[0].safetyParam == 4097 and selected(cp)
|
||||
assert cp.openpilotLongitudinalControl
|
||||
assert cp.flags & TeslaFlags.HAS_VEHICLE_BUS
|
||||
assert speed_sync_allowed(cp, 4097)
|
||||
assert supported(cp) and screen_tap_supported(cp) and modern_aol_supported(cp) and not screen_qualified(cp)
|
||||
assert CarController(DBC[cp.carFingerprint], cp).speed_sync is not None
|
||||
|
||||
|
||||
@pytest.mark.parametrize('candidate', MODERN)
|
||||
@pytest.mark.parametrize('coop', (False, True))
|
||||
def test_cooperative_on_off_keeps_sync(candidate, coop):
|
||||
cp = startup(sync_params(candidate), coop)
|
||||
assert cp.safetyConfigs[0].safetyParam == (4353 if coop else 4097)
|
||||
apply_cooperative(cp, not coop)
|
||||
assert cp.safetyConfigs[0].safetyParam == (4097 if coop else 4353)
|
||||
assert selected(cp)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('candidate', MODERN)
|
||||
@pytest.mark.parametrize('coop', (False, True))
|
||||
@pytest.mark.parametrize('screen', (False, True))
|
||||
@pytest.mark.parametrize('brake', (False, True))
|
||||
def test_screen_brake_matrix_composes_native_words(candidate, coop, screen, brake):
|
||||
cp = startup(sync_params(candidate), coop, screen, brake)
|
||||
expected = expected_word(coop, screen, brake)
|
||||
assert expected in NATIVE_SYNC_WORDS
|
||||
assert cp.safetyConfigs[0].safetyParam == expected
|
||||
assert supported(cp) and screen_tap_supported(cp) and selected(cp)
|
||||
assert screen_qualified(cp) == screen
|
||||
assert bool(cp.flags & TeslaFlags.AOL_SCREEN_BUTTON) == screen
|
||||
apply_screen_button(cp, not screen, brake)
|
||||
assert cp.safetyConfigs[0].safetyParam == expected_word(coop, not screen, brake)
|
||||
assert screen_qualified(cp) == (not screen)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('candidate', MODERN)
|
||||
@pytest.mark.parametrize('coop', (False, True))
|
||||
@pytest.mark.parametrize('screen', (False, True))
|
||||
@pytest.mark.parametrize('brake', (False, True))
|
||||
def test_always_on_lateral_composes_native_words(candidate, coop, screen, brake):
|
||||
# Ordinary Always On Lateral is 2048 and the screen tap 512; either one keeps speed sync on top.
|
||||
cp = sync_params(candidate)
|
||||
apply_modern_aol(cp, True, screen, brake)
|
||||
apply_cooperative(cp, coop)
|
||||
expected = 4097 | (512 if screen else 2048) | (1024 if brake else 0) | (256 if coop else 0)
|
||||
assert cp.safetyConfigs[0].safetyParam == expected and expected in NATIVE_SYNC_WORDS
|
||||
assert selected(cp) and supported(cp) and modern_aol_supported(cp) and modern_aol_qualified(cp)
|
||||
apply_modern_aol(cp, False, screen, brake)
|
||||
assert cp.safetyConfigs[0].safetyParam == 4097 | (256 if coop else 0)
|
||||
assert selected(cp) and not modern_aol_qualified(cp)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('candidate', MODERN)
|
||||
@pytest.mark.parametrize('order', ('sync last', 'sync first', 'sync between'))
|
||||
@pytest.mark.parametrize('aol', (None, 'ordinary', 'screen'))
|
||||
def test_any_startup_order_gives_the_same_word(candidate, order, aol):
|
||||
cp = sync_params(candidate)
|
||||
apply_speed_sync(cp, False)
|
||||
steps = [lambda: apply_modern_aol(cp, aol is not None, aol == 'screen', True), lambda: apply_cooperative(cp, True)]
|
||||
steps.insert({'sync first': 0, 'sync between': 1, 'sync last': 2}[order], lambda: apply_speed_sync(cp, True))
|
||||
for _ in range(2): # prepare, then finalize on the same parameters
|
||||
for step in steps:
|
||||
step()
|
||||
expected = 4097 | 256 | {None: 0, 'ordinary': 2048 | 1024, 'screen': 512 | 1024}[aol]
|
||||
assert cp.safetyConfigs[0].safetyParam == expected and expected in NATIVE_SYNC_WORDS
|
||||
|
||||
|
||||
@pytest.mark.parametrize('coop_first', (False, True))
|
||||
@pytest.mark.parametrize('brake', (False, True))
|
||||
def test_repeated_startup_ordering_preserves_sync(coop_first, brake):
|
||||
cp = sync_params()
|
||||
expected = expected_word(True, True, brake)
|
||||
for _ in range(3):
|
||||
if coop_first:
|
||||
apply_cooperative(cp, True)
|
||||
apply_screen_button(cp, True, brake)
|
||||
else:
|
||||
apply_screen_button(cp, True, brake)
|
||||
apply_cooperative(cp, True)
|
||||
assert cp.safetyConfigs[0].safetyParam == expected
|
||||
assert screen_qualified(cp)
|
||||
apply_cooperative(cp, False)
|
||||
assert cp.safetyConfigs[0].safetyParam == expected & ~256
|
||||
apply_screen_button(cp, False, brake)
|
||||
assert cp.safetyConfigs[0].safetyParam == 4097
|
||||
apply_cooperative(cp, True)
|
||||
assert cp.safetyConfigs[0].safetyParam == 4353
|
||||
|
||||
|
||||
def test_sync_longitudinal_off_rejected():
|
||||
for word in (4096, 4097, 4352):
|
||||
cp = sync_params(long=False)
|
||||
assert not cp.safetyConfigs[0].safetyParam & SYNC_FLAG, 'never requested without longitudinal control'
|
||||
cp.safetyConfigs[0].safetyParam = word
|
||||
assert_rejected(cp)
|
||||
cp = sync_params()
|
||||
cp.openpilotLongitudinalControl = False
|
||||
assert_rejected(cp)
|
||||
|
||||
|
||||
def test_sync_without_vehicle_bus_or_with_unknown_flag_rejected():
|
||||
cp = sync_params()
|
||||
cp.flags &= ~int(TeslaFlags.HAS_VEHICLE_BUS)
|
||||
assert_rejected(cp)
|
||||
cp = sync_params()
|
||||
cp.flags |= 64
|
||||
assert_rejected(cp)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('word', (4097 | 2, 4097 | 4, 4097 | 16, 4097 | 8192, 4097 | 1024, 4353 | 8192, 4097 | 512 | 2048))
|
||||
def test_sync_with_unknown_safety_bit_rejected(word):
|
||||
cp = sync_params()
|
||||
cp.safetyConfigs[0].safetyParam = word
|
||||
assert_rejected(cp)
|
||||
|
||||
|
||||
def test_screen_word_must_match_the_screen_flag():
|
||||
cp = sync_params()
|
||||
cp.safetyConfigs[0].safetyParam = 4097 | 512 # the screen word without the screen flag in CarParams
|
||||
assert_rejected(cp)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('candidate', MODERN)
|
||||
def test_real_controller_and_carstate_cooperate_after_sync_startup(candidate):
|
||||
cp = startup(sync_params(candidate), True)
|
||||
assert cp.safetyConfigs[0].safetyParam == 4353
|
||||
cs = CarState(cp)
|
||||
cs.hands_on_level = 0
|
||||
cs.das_control = {'DAS_controlCounter': 0}
|
||||
cs.out.vEgo = cs.out.vEgoRaw = 20.
|
||||
cs.out.steeringAngleDeg = 0.
|
||||
cs.out.gasPressed = False
|
||||
controller = CarController(DBC[candidate], cp)
|
||||
assert controller.coop_enabled and controller.speed_sync is not None
|
||||
cc = car.CarControl.new_message(latActive=True)
|
||||
for tick in range(10):
|
||||
cs.out.steeringTorque, cs.out.steeringDisengage = 1., False
|
||||
_, sends = controller.update(cc.as_reader(), cs, 1_000_000_000 + tick * 10_000_000)
|
||||
assert not [message for message in sends if message[0] == 0x3C2], 'no scroll request without the comma set speed context'
|
||||
assert controller.steering_limit_info.get('valid', False)
|
||||
cs.out.steeringTorque, cs.out.steeringDisengage = 5.1, True
|
||||
controller.update(cc.as_reader(), cs, 1_100_000_000)
|
||||
assert not controller.steering_limit_info.get('valid', False)
|
||||
assert cp.safetyConfigs[0].safetyParam == 4353
|
||||
@@ -0,0 +1,138 @@
|
||||
"""The Tesla longitudinal command and the dashboard speed limit: the real formatter, CAN parser and car state; no
|
||||
vehicle output. The command is the stock one for every Tesla, pedal or not: nothing in it follows the set-speed work."""
|
||||
import inspect
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
from opendbc.can import CANPacker
|
||||
from opendbc.car import gen_empty_fingerprint
|
||||
from opendbc.car.structs import car
|
||||
from opendbc.car.tesla.interface import CarInterface
|
||||
from opendbc.car.tesla.carcontroller import CarController
|
||||
from opendbc.car.tesla.carstate import CarState
|
||||
from opendbc.car.tesla.speed_sync import prepare
|
||||
from opendbc.car.tesla.teslacan import TeslaCAN
|
||||
from opendbc.car.tesla.values import CAR, CANBUS, DBC, CarControllerParams
|
||||
from opendbc.car.dashboard_speed_limit import Status
|
||||
from openpilot.starpilot.speed_limits.runtime import dashboard_observation
|
||||
from openpilot.starpilot.speed_limits.acceptance import ObservationKind
|
||||
|
||||
MODERN = (CAR.TESLA_MODEL_3, CAR.TESLA_MODEL_Y)
|
||||
|
||||
|
||||
class Capture:
|
||||
"""Stands in for the CAN packer: returns the values the formatter chose."""
|
||||
def make_can_msg(self, name, bus, values):
|
||||
return name, bus, dict(values)
|
||||
|
||||
|
||||
def stock_command(acc_state, accel, counter, v_ego):
|
||||
"""The longitudinal command as the stock formatter builds it."""
|
||||
return {'DAS_setSpeed': min(max(v_ego + accel, 0) * 3.6, 400), 'DAS_accState': acc_state, 'DAS_aebEvent': 0,
|
||||
'DAS_jerkMin': -4.9, 'DAS_jerkMax': 4.9, 'DAS_accelMin': accel, 'DAS_accelMax': max(accel, 0),
|
||||
'DAS_controlCounter': counter}
|
||||
|
||||
|
||||
def test_the_formatter_takes_the_stock_arguments_and_keeps_no_state():
|
||||
parameters = list(inspect.signature(TeslaCAN.create_longitudinal_command).parameters.values())
|
||||
assert [(p.name, p.kind, p.default) for p in parameters] == [
|
||||
(name, inspect.Parameter.POSITIONAL_OR_KEYWORD, inspect.Parameter.empty)
|
||||
for name in ('self', 'acc_state', 'accel', 'counter', 'v_ego', 'active')]
|
||||
assert sorted(vars(TeslaCAN(None, Capture()))) == ['CP', 'packer']
|
||||
assert (CarControllerParams.JERK_LIMIT_MIN, CarControllerParams.JERK_LIMIT_MAX) == (-4.9, 4.9)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('acc_state', [4, 13])
|
||||
@pytest.mark.parametrize('accel', [-3.48, -.1, 0., .8, 2.])
|
||||
@pytest.mark.parametrize('v_ego', [0., 1.5, 20., 45., 120.])
|
||||
@pytest.mark.parametrize('active', [False, True])
|
||||
def test_the_command_is_the_stock_one(acc_state, accel, v_ego, active):
|
||||
codec = TeslaCAN(None, Capture())
|
||||
for counter in range(16):
|
||||
name, bus, values = codec.create_longitudinal_command(acc_state, accel, counter % 8, v_ego, active)
|
||||
assert (name, bus) == ('DAS_control', CANBUS.party)
|
||||
assert values == pytest.approx(stock_command(acc_state, accel, counter % 8, v_ego)), 'the same on every call'
|
||||
assert set(values) == set(stock_command(acc_state, accel, 0, v_ego))
|
||||
|
||||
|
||||
def controller(candidate, *, selected, long=True):
|
||||
fingerprint = gen_empty_fingerprint()
|
||||
fingerprint[CANBUS.autopilot_party][0x489] = 8
|
||||
fingerprint[CANBUS.vehicle][0x3DF] = 8
|
||||
cp = prepare(CarInterface.get_params(candidate, fingerprint, [], long, False, False), selected)
|
||||
cs = CarState(cp)
|
||||
cs.hands_on_level = 0
|
||||
cs.das_control = {'DAS_controlCounter': 3}
|
||||
cs.out = car.CarState.new_message(vEgo=20., vEgoRaw=20., canValid=True)
|
||||
unit = CarController(DBC[candidate], cp)
|
||||
unit.tesla_can = TeslaCAN(cp, Capture())
|
||||
return unit, cs
|
||||
|
||||
|
||||
def commands(sends):
|
||||
return [message[2] for message in sends if message[0] == 'DAS_control']
|
||||
|
||||
|
||||
@pytest.mark.parametrize('candidate', MODERN)
|
||||
@pytest.mark.parametrize('selected', [False, True])
|
||||
def test_the_real_controller_sends_the_stock_command_through_a_pedal_press_and_release(candidate, selected):
|
||||
unit, cs = controller(candidate, selected=selected)
|
||||
seen = []
|
||||
for frame in range(400):
|
||||
cs.out.gasPressed = 100 <= frame < 180
|
||||
cc = car.CarControl.new_message(enabled=True, longActive=not cs.out.gasPressed, actuators={'accel': .8})
|
||||
_, sends = unit.update(cc.as_reader(), cs, 1_000_000_000 + frame * 10_000_000)
|
||||
for values in commands(sends):
|
||||
assert values == pytest.approx(stock_command(4, .8, (frame // 4) % 8, 20.)), frame
|
||||
seen.append(frame)
|
||||
assert seen == list(range(0, 400, 4)), 'every fourth frame, pedal or not'
|
||||
|
||||
|
||||
@pytest.mark.parametrize('candidate', MODERN)
|
||||
def test_the_real_controller_cancels_with_the_stock_command_without_longitudinal_control(candidate):
|
||||
unit, cs = controller(candidate, selected=False, long=False)
|
||||
cc = car.CarControl.new_message(enabled=False, cruiseControl={'cancel': True})
|
||||
_, sends = unit.update(cc.as_reader(), cs, 1_000_000_000)
|
||||
assert commands(sends) == [pytest.approx(stock_command(13, 0, 4, 20.))], 'from the first frame, with the full jerk limits'
|
||||
_, sends = unit.update(car.CarControl.new_message().as_reader(), cs, 1_010_000_000)
|
||||
assert commands(sends) == []
|
||||
|
||||
|
||||
@pytest.mark.parametrize('candidate', MODERN)
|
||||
def test_the_car_state_and_controller_carry_nothing_for_a_pedal_hand_over(candidate):
|
||||
unit, cs = controller(candidate, selected=True)
|
||||
for holder in (unit, cs, unit.tesla_can):
|
||||
assert not [name for name in vars(holder) if 'handover' in name or 'gas_release' in name]
|
||||
with pytest.raises(ImportError):
|
||||
__import__('opendbc.car.tesla.pedal_handover')
|
||||
|
||||
|
||||
@pytest.mark.parametrize('candidate', [CAR.TESLA_MODEL_3, CAR.TESLA_MODEL_Y])
|
||||
@pytest.mark.parametrize('units,limit,expected', [(0, 30, 13.4112), (1, 50, 50 / 3.6), (0, 155, 0), (0, 0, 0)])
|
||||
def test_actual_carstate_publishes_fused_limit(candidate, units, limit, expected):
|
||||
cp = CarInterface.get_non_essential_params(candidate)
|
||||
state = CarState(cp)
|
||||
parsers = state.get_can_parsers(cp)
|
||||
state.update(parsers) # Register the production parser subscriptions.
|
||||
packers = {bus: CANPacker(parser.dbc.name) for bus, parser in parsers.items()}
|
||||
stamp = 0
|
||||
for i in range(30):
|
||||
stamp = 1_000_000_000 + i * 100_000_000
|
||||
for bus, parser in parsers.items():
|
||||
messages = []
|
||||
for address in sorted(parser.addresses):
|
||||
msg = parser.dbc.addr_to_msg[address].name
|
||||
values = {'DI_speedUnits': units} if msg == 'DI_state' else {'DAS_fusedSpeedLimit': limit} if msg == 'DAS_status' else {}
|
||||
messages.append(packers[bus].make_can_msg(msg, parser.bus, values))
|
||||
parser.update([stamp, messages])
|
||||
state.update(parsers)
|
||||
obs = state.dashboard_limit.observation
|
||||
assert obs.status == (Status.VALID if expected else Status.ABSENT if limit == 155 else Status.UNKNOWN)
|
||||
assert obs.speed_mps == pytest.approx(expected)
|
||||
evidence = SimpleNamespace(status=obs.status.value, speedMps=obs.speed_mps, observedMonoTime=obs.observed_ns,
|
||||
validUntilMonoTime=obs.valid_until_ns, episode=obs.episode, producerSessionId='real-parser')
|
||||
result = dashboard_observation(evidence, car_fingerprint=str(candidate), session_id='drive', now_ns=stamp)
|
||||
assert result.kind == (ObservationKind.VALID if expected else ObservationKind.ABSENT if limit == 155 else ObservationKind.UNKNOWN)
|
||||
if expected:
|
||||
stale = dashboard_observation(evidence, car_fingerprint=str(candidate), session_id='drive', now_ns=obs.valid_until_ns + 1)
|
||||
assert stale.kind is ObservationKind.STALE
|
||||
@@ -0,0 +1,331 @@
|
||||
"""Speed sync requests around the accelerator pedal, lost feedback and unanswered requests. Pure protocol: no device."""
|
||||
import pytest
|
||||
from opendbc.car.tesla.speed_sync import (ENGAGE_DELAY_NS, FAST_TICKS, FRESH_NS, HANDOVER_NS, MANUAL_COMPLETION_NS, MAX_RETRIES,
|
||||
TEMPLATE_SEND_NS, SpeedSynchronizer, neutral_wheel, plan_step, scroll_request)
|
||||
|
||||
NEUTRAL = bytes.fromhex('2955000000000040')
|
||||
|
||||
|
||||
def clicks(msg):
|
||||
"""The signed scroll count of a request."""
|
||||
ticks = msg[1][3] & 63
|
||||
return ticks - 64 if ticks >= 32 else ticks
|
||||
|
||||
|
||||
class Rig:
|
||||
def __init__(self, *, engaged=True):
|
||||
self.sync = SpeedSynchronizer()
|
||||
self.now = 1_000_000_000
|
||||
self.counter = 0
|
||||
self.speed, self.target, self.units = 45, 50, 1
|
||||
self.sent = []
|
||||
self.echo = True # the panda transmits each request and echoes it on bus 129
|
||||
self._echo = None
|
||||
if engaged:
|
||||
# Engaged without longitudinal authority for longer than the panda needs to hear about engagement.
|
||||
for _ in range(ENGAGE_DELAY_NS // 10_000_000 + 1):
|
||||
assert self.tick(long=False) is None
|
||||
|
||||
def tick(self, dt=10_000_000, *, long=True, gas=False, safe=True, enabled=True,
|
||||
feedback=True, wheel=NEUTRAL, wheel_bus=1):
|
||||
self.now += dt
|
||||
frames = []
|
||||
if self._echo is not None:
|
||||
frames.append((0x3c2, self._echo, 129))
|
||||
self._echo = None
|
||||
if feedback:
|
||||
self.counter = (self.counter + 1) % 16
|
||||
bits = (self.counter << 8) | (2 << 12) | (round(self.speed * 2) << 15) | (self.units << 24)
|
||||
di = bytearray(bits.to_bytes(8, 'little'))
|
||||
di[0] = (0x88 + sum(di[1:])) & 255
|
||||
frames.append((0x286, bytes(di), 0))
|
||||
if wheel is not None:
|
||||
frames.append((0x3c2, wheel, wheel_bus))
|
||||
self.sync.observe([(self.now, frames)])
|
||||
msg = self.sync.update(self.now, target_kph=self.target, enabled=enabled,
|
||||
safe=safe, longitudinal_active=long, gas_pressed=gas)
|
||||
if msg:
|
||||
self.sent.append((self.now, msg))
|
||||
if self.echo:
|
||||
self._echo = msg[1]
|
||||
return msg
|
||||
|
||||
|
||||
@pytest.mark.parametrize('before', [False, True])
|
||||
def test_pending_response_on_either_side_of_release(before):
|
||||
# A request sent under the pedal is answered before or after the release; nothing new is sent in the hand-over
|
||||
# window, and requests carry on once longitudinal control is back.
|
||||
r = Rig()
|
||||
assert r.tick(long=False, gas=True)
|
||||
if before:
|
||||
r.speed += 1
|
||||
assert r.tick(long=False) is None
|
||||
assert r.sync.blocked is None
|
||||
r.speed = 46
|
||||
for _ in range(15):
|
||||
msg = r.tick()
|
||||
if msg:
|
||||
break
|
||||
assert r.sync.blocked is None
|
||||
assert msg is not None and len(r.sent) == 2
|
||||
|
||||
|
||||
def test_no_initial_authority_and_held_pedal_engage():
|
||||
r = Rig()
|
||||
for _ in range(20):
|
||||
assert r.tick(long=False) is None
|
||||
assert not r.sent and r.sync.handover_until == 0
|
||||
assert r.tick(long=False, gas=True) is not None
|
||||
|
||||
|
||||
def test_no_new_command_during_handover_even_after_response():
|
||||
r = Rig()
|
||||
assert r.tick(long=False, gas=True)
|
||||
r.speed += 1
|
||||
for _ in range(8):
|
||||
assert r.tick(long=False) is None
|
||||
assert r.sync.pending is None and len(r.sent) == 1
|
||||
assert r.sync.status == 'waiting_for_handover'
|
||||
|
||||
|
||||
def test_grace_expires_once_not_renewed_by_false_samples():
|
||||
r = Rig()
|
||||
r.target = r.speed
|
||||
r.tick(long=False, gas=True)
|
||||
r.target = 50
|
||||
r.tick(long=False)
|
||||
deadline = r.sync.handover_until
|
||||
assert deadline == r.now + HANDOVER_NS
|
||||
for _ in range(9):
|
||||
assert r.tick(long=False) is None
|
||||
assert r.sync.handover_until == deadline and r.sync.status == 'waiting_for_handover'
|
||||
assert r.tick(long=False) is None
|
||||
assert r.now == deadline and r.sync.handover_until == 0 and r.sync.status == 'inhibited'
|
||||
for _ in range(20):
|
||||
assert r.tick(long=False) is None, 'no authority, no request'
|
||||
assert r.sync.blocked is None and not r.sent
|
||||
|
||||
|
||||
def test_release_with_a_request_open_sends_nothing_until_authority_returns():
|
||||
r = Rig()
|
||||
assert r.tick(long=False, gas=True)
|
||||
for _ in range(20):
|
||||
assert r.tick(long=False) is None
|
||||
r.speed += 1 # the Tesla answers after the release
|
||||
for _ in range(20):
|
||||
assert r.tick(long=False) is None
|
||||
assert r.sync.status == 'inhibited' and len(r.sent) == 1
|
||||
assert any(r.tick() for _ in range(5)), 'carries on with longitudinal control'
|
||||
|
||||
|
||||
def test_hard_failure_and_disengagement_clear_edge_history():
|
||||
r = Rig()
|
||||
r.target = r.speed
|
||||
r.tick(gas=True)
|
||||
r.tick(safe=False)
|
||||
r.target = 50
|
||||
assert r.tick(long=False) is None and r.sync.handover_until == 0
|
||||
r.tick(gas=True, enabled=False)
|
||||
assert r.tick(long=False) is None and r.sync.handover_until == 0
|
||||
|
||||
|
||||
def test_feedback_loss_pauses_until_fresh_feedback():
|
||||
r = Rig()
|
||||
r.target = r.speed
|
||||
for _ in range(30):
|
||||
assert r.tick(feedback=False) is None
|
||||
r.target = 50
|
||||
assert r.tick(feedback=False) is None
|
||||
assert r.sync.status == 'waiting_for_native_speed' and r.sync.blocked is None
|
||||
assert r.tick() is not None, 'carries on once the Tesla speed is fresh again'
|
||||
|
||||
|
||||
def test_units_change_inflight_is_not_handover():
|
||||
r = Rig()
|
||||
r.tick(gas=True)
|
||||
r.units = 0
|
||||
assert r.tick(long=False) is None
|
||||
assert r.sync.blocked == 'units_changed_during_request'
|
||||
|
||||
|
||||
def test_manual_input_during_a_request_wins():
|
||||
# The driver's own scroll is recorded and given time to land; the open request is not repeated.
|
||||
r = Rig()
|
||||
assert r.tick(gas=True)
|
||||
assert r.tick(long=False, wheel=scroll_request(NEUTRAL, -1)[1]) is None
|
||||
assert r.sync.blocked is None
|
||||
assert any(h['event'] == 'input_during_request' for h in r.sync.history)
|
||||
r.speed -= 1
|
||||
for _ in range(10):
|
||||
assert r.tick() is None
|
||||
assert r.sync.status == 'waiting_for_manual_processing', "waits for the comma to act on the driver's scroll"
|
||||
assert len(r.sent) == 1
|
||||
for _ in range(MANUAL_COMPLETION_NS // 10_000_000):
|
||||
r.tick()
|
||||
assert 'manual_action_unconfirmed' in r.sync.noticed and r.sync.blocked is None
|
||||
assert len(r.sent) > 1, "after the wait the Tesla is scrolled back to the comma's speed"
|
||||
|
||||
|
||||
def test_no_response_is_retried_a_few_times_then_waits_for_the_tesla():
|
||||
r = Rig()
|
||||
r.tick()
|
||||
for _ in range(100):
|
||||
r.tick(dt=100_000_000)
|
||||
assert r.sync.blocked is None and 'no_native_response' in r.sync.noticed
|
||||
assert r.sync.status == 'waiting_for_native_change'
|
||||
sent = len(r.sent)
|
||||
assert sent == MAX_RETRIES + 1, 'the first request and its retries'
|
||||
for _ in range(20):
|
||||
assert r.tick() is None
|
||||
r.speed += 1 # the Tesla moves: requests carry on
|
||||
assert any(r.tick() for _ in range(20))
|
||||
|
||||
|
||||
def test_an_unanswered_request_does_not_hold_back_the_other_direction():
|
||||
# The Tesla ignores scrolls one way (it is at its own lowest or highest set speed). A comma speed still on that side
|
||||
# keeps waiting; once it is on the other side of the Tesla's, sync carries on without the Tesla changing first.
|
||||
r = Rig()
|
||||
r.tick()
|
||||
for _ in range(100):
|
||||
r.tick(dt=100_000_000)
|
||||
assert r.sync.status == 'waiting_for_native_change'
|
||||
sent = len(r.sent)
|
||||
r.target = 55 # further the same way (the Tesla shows 45)
|
||||
for _ in range(20):
|
||||
assert r.tick() is None
|
||||
assert r.sync.status == 'waiting_for_native_change'
|
||||
r.target = 40 # now below the Tesla's
|
||||
assert any(r.tick() for _ in range(20))
|
||||
assert len(r.sent) == sent + 1 and clicks(r.sent[-1][1]) == -1
|
||||
r.speed -= 1 # the Tesla follows: nothing is left of the old wait
|
||||
assert any(r.tick() for _ in range(20)) and r.sync.unanswered is None
|
||||
|
||||
|
||||
def test_request_needs_a_new_physical_neutral_frame():
|
||||
r = Rig()
|
||||
r.tick()
|
||||
r.speed += 1
|
||||
assert r.tick(wheel=None) is None, 'no neutral frame newer than the one the last request copied'
|
||||
assert r.tick(wheel=NEUTRAL, wheel_bus=129) is None, "a bus-129 echo is not the driver's wheel"
|
||||
assert r.sync.status == 'waiting_for_neutral_wheel'
|
||||
assert r.tick() is not None
|
||||
|
||||
|
||||
def test_request_not_echoed_by_the_panda_is_not_transmitted():
|
||||
r = Rig()
|
||||
r.echo = False
|
||||
assert r.tick()
|
||||
for _ in range(9):
|
||||
assert r.tick() is None
|
||||
r.tick()
|
||||
assert any(h['event'] == 'not_transmitted' and h['reason'] == 'no_bus_return' for h in r.sync.history)
|
||||
assert r.sync.pending is None and r.sync.blocked is None
|
||||
|
||||
|
||||
def test_template_age_is_tighter_than_receive_freshness():
|
||||
r = Rig()
|
||||
r.target = r.speed
|
||||
r.tick()
|
||||
r.target = 50
|
||||
assert r.tick(dt=TEMPLATE_SEND_NS + 1, wheel=None) is None
|
||||
assert r.sync.status == 'waiting_for_neutral_wheel'
|
||||
assert r.tick() is not None
|
||||
|
||||
|
||||
@pytest.mark.parametrize('direction', [-1, 1])
|
||||
def test_convergence_one_request_per_tesla_change(direction):
|
||||
r = Rig()
|
||||
r.target = r.speed + 10 * direction
|
||||
waiting = None
|
||||
for _ in range(400):
|
||||
msg = r.tick()
|
||||
if msg:
|
||||
assert waiting is None, 'never two requests open at once'
|
||||
waiting = r.speed
|
||||
elif waiting is not None and r.sync.pending is not None and r.now - r.sync.pending.sent_ns >= 30_000_000:
|
||||
r.speed += direction # the Tesla answers about 30 ms later
|
||||
waiting = None
|
||||
if r.sync.status == 'matched':
|
||||
break
|
||||
assert r.speed == r.target and len(r.sent) == 10
|
||||
assert len(r.sync.history) <= 32
|
||||
|
||||
|
||||
def test_same_rounded_target_never_sends():
|
||||
r = Rig()
|
||||
r.speed = 45.5
|
||||
r.target = 46
|
||||
for _ in range(10):
|
||||
assert r.tick() is None
|
||||
assert r.sync.status == 'matched'
|
||||
|
||||
|
||||
def test_controller_clock_gap_pauses_one_frame():
|
||||
r = Rig()
|
||||
r.tick(gas=True)
|
||||
r.speed += 1
|
||||
assert r.tick(dt=FRESH_NS + 1, long=False) is None
|
||||
assert r.sync.status == 'controller_clock_gap' and r.sync.blocked is None and r.sync.handover_until == 0
|
||||
|
||||
|
||||
def test_disengaging_clears_the_engagement():
|
||||
r = Rig()
|
||||
assert r.tick()
|
||||
assert r.tick(enabled=False) is None
|
||||
assert r.sync.status == 'inactive' and r.sync.pending is None and r.sync.target is None and not r.sync.active
|
||||
assert not r.sync.history and not r.sync.noticed
|
||||
|
||||
|
||||
@pytest.mark.parametrize('native,target,fast,expected', [
|
||||
(50, 51, True, (1, 51)), (50, 49, True, (-1, 49)),
|
||||
(50, 55, True, (FAST_TICKS, 55)), (50, 45, True, (-FAST_TICKS, 45)),
|
||||
(52, 60, True, (FAST_TICKS, 55)), (52, 44, True, (-FAST_TICKS, 50)),
|
||||
(52, 54, True, (1, 53)), (53, 51, True, (-1, 52)), # the next multiple of five would pass the target
|
||||
(54, 60, True, (1, 55)), (56, 50, True, (-1, 55)), # one away from the multiple: a click is as quick
|
||||
(50, 60, False, (1, 51)), (50, 40, False, (-1, 49)), # fast steps paused, or km/h
|
||||
])
|
||||
def test_next_step_toward_the_target(native, target, fast, expected):
|
||||
assert plan_step(native, target, fast) == expected
|
||||
|
||||
|
||||
@pytest.mark.parametrize('ticks', [-FAST_TICKS, -1, 1, FAST_TICKS])
|
||||
def test_a_request_is_the_neutral_frame_with_only_the_scroll_count_set(ticks):
|
||||
address, data, bus = scroll_request(NEUTRAL, ticks)
|
||||
assert (address, bus) == (0x3C2, 1) and len(data) == 8
|
||||
assert data[3] == (NEUTRAL[3] & 0xC0) | (ticks & 0x3F)
|
||||
assert data[:3] == NEUTRAL[:3] and data[4:] == NEUTRAL[4:]
|
||||
assert not neutral_wheel(data), 'a scroll is not a template for the next request'
|
||||
|
||||
|
||||
@pytest.mark.parametrize('ticks', [0, 2, 3, 4, 6, -2, -6, 31, -32])
|
||||
def test_only_one_click_or_one_fast_flick_is_ever_requested(ticks):
|
||||
assert scroll_request(NEUTRAL, ticks) is None
|
||||
|
||||
|
||||
def test_no_request_is_built_from_a_frame_that_is_not_neutral():
|
||||
assert neutral_wheel(NEUTRAL)
|
||||
pressed = bytearray(NEUTRAL)
|
||||
pressed[1] = (pressed[1] & ~0x03) | 0x02 # right wheel tilted left
|
||||
for frame in (bytes(pressed), scroll_request(NEUTRAL, 1)[1], NEUTRAL[:7], bytes(8)):
|
||||
assert not neutral_wheel(frame)
|
||||
assert scroll_request(frame, 1) is None
|
||||
|
||||
|
||||
@pytest.mark.parametrize('direction', [-1, 1])
|
||||
def test_mph_convergence_uses_fast_steps_and_lands_on_the_target(direction):
|
||||
r = Rig(engaged=False)
|
||||
r.units, r.speed = 0, 52
|
||||
r.target = (52 + 14 * direction) * 1.609344
|
||||
for _ in range(ENGAGE_DELAY_NS // 10_000_000 + 1):
|
||||
assert r.tick(long=False) is None
|
||||
for _ in range(2000):
|
||||
r.tick()
|
||||
p = r.sync.pending
|
||||
if p is not None and p.returned and r.now - p.sent_ns >= 30_000_000:
|
||||
r.speed = p.expected # the Tesla answers about 30 ms later
|
||||
if r.sync.status == 'matched':
|
||||
break
|
||||
assert r.speed == 52 + 14 * direction and r.sync.blocked is None
|
||||
sizes = [abs(clicks(msg)) for _, msg in r.sent]
|
||||
assert FAST_TICKS in sizes and 1 in sizes
|
||||
assert len(r.sent) <= 5, 'far fewer requests than fourteen single clicks'
|
||||
@@ -0,0 +1,341 @@
|
||||
"""The driver's own scroll and speed sync. Wheel input that cannot be read as one clean scroll pauses sync; it never
|
||||
stops it until disengaging.
|
||||
|
||||
A right-wheel nudge that springs back with one scroll click is taken by the Tesla and not by the comma, so sync
|
||||
scrolls the Tesla back. A clean scroll waits for the comma: card's receipt for the step it applied releases it at
|
||||
once, and without one it is dropped after its window and corrected the same way.
|
||||
"""
|
||||
from dataclasses import replace
|
||||
|
||||
import pytest
|
||||
|
||||
from opendbc.car.tesla.speed_sync import MANUAL_COMPLETION_NS, MANUAL_SETTLE_NS, ManualReceipt, SpeedSynchronizer, SyncAuthority
|
||||
|
||||
MPH = 1.609344
|
||||
DOCUMENT, VEHICLE, SESSION, DRIVE = 'd' * 64, 'e' * 64, '0123456789abcdef' * 2, 100_000_000
|
||||
|
||||
NEUTRAL = bytes.fromhex('2955000000000040')
|
||||
TICK = 50_000_000
|
||||
|
||||
|
||||
def wheel(right_left=1, right_scroll=0):
|
||||
bits = int.from_bytes(NEUTRAL, 'little')
|
||||
bits = (bits & ~(3 << 8)) | (right_left << 8)
|
||||
bits = (bits & ~(63 << 24)) | ((right_scroll & 63) << 24)
|
||||
return bits.to_bytes(8, 'little')
|
||||
|
||||
|
||||
class Rig:
|
||||
"""The Tesla in mph at 77, the comma's set speed 77; nothing answers requests unless a test moves `speed`."""
|
||||
def __init__(self):
|
||||
self.sync = SpeedSynchronizer()
|
||||
self.now = 1_000_000_000
|
||||
self.counter = 0
|
||||
self.speed = self.target = 77
|
||||
self.sent = []
|
||||
|
||||
def tick(self, data=NEUTRAL):
|
||||
self.now += TICK
|
||||
self.counter = (self.counter + 1) % 16
|
||||
bits = (self.counter << 8) | (2 << 12) | (round(self.speed * 2) << 15)
|
||||
di = bytearray(bits.to_bytes(8, 'little'))
|
||||
di[0] = (0x88 + sum(di[1:])) & 255
|
||||
self.sync.observe([(self.now, [(0x286, bytes(di), 0), (0x3c2, data, 1)])])
|
||||
msg = self.sync.update(self.now, target_kph=self.target * 1.609344, enabled=True, safe=True, longitudinal_active=True)
|
||||
if msg:
|
||||
self.sent.append((self.now, msg))
|
||||
return msg
|
||||
|
||||
def settle(self, seconds):
|
||||
return [m for m in (self.tick() for _ in range(round(seconds * 1e9 / TICK))) if m]
|
||||
|
||||
|
||||
def clicks(msg):
|
||||
ticks = msg[1][3] & 63
|
||||
return ticks - 64 if ticks >= 32 else ticks
|
||||
|
||||
|
||||
def test_nudge_release_click_is_corrected_not_a_stop():
|
||||
r = Rig()
|
||||
assert not r.settle(1)
|
||||
r.tick(wheel(right_left=2))
|
||||
r.tick(wheel(right_left=2))
|
||||
r.tick(wheel(right_scroll=1)) # springs back with one click
|
||||
r.speed = 78 # the Tesla took it; the comma stays at 77
|
||||
sent = r.settle(1.5)
|
||||
assert r.sync.blocked is None
|
||||
assert 'ambiguous_manual_input' not in r.sync.noticed
|
||||
assert sent and clicks(sent[0]) == -1, 'sync puts the Tesla back on the comma speed'
|
||||
assert any(h['event'] == 'nudge_release_click' for h in r.sync.history)
|
||||
|
||||
|
||||
def test_unclear_scroll_pauses_and_sync_carries_on():
|
||||
r = Rig()
|
||||
r.settle(1)
|
||||
r.tick(wheel(right_left=2))
|
||||
r.tick(wheel(right_left=2, right_scroll=1)) # a scroll while the wheel is still tilted
|
||||
assert r.sync.blocked is None and 'ambiguous_manual_input' in r.sync.noticed
|
||||
r.tick()
|
||||
r.speed = 78
|
||||
sent = r.settle(1.5)
|
||||
assert r.sync.blocked is None and sent and clicks(sent[0]) == -1
|
||||
|
||||
|
||||
def test_a_driver_scroll_waits_its_window_and_is_then_dropped_with_a_notice():
|
||||
r = Rig()
|
||||
r.settle(1)
|
||||
r.tick(wheel(right_scroll=1)) # a clean scroll; the comma's own speed does not follow it here
|
||||
r.tick()
|
||||
r.speed = 78
|
||||
assert not r.settle(MANUAL_COMPLETION_NS / 1e9 - 0.2), "nothing is sent while the comma may still act on the driver's scroll"
|
||||
assert r.sync.status == 'waiting_for_manual_processing'
|
||||
sent = r.settle(1)
|
||||
assert r.sync.blocked is None and 'manual_action_unconfirmed' in r.sync.noticed
|
||||
assert any(h['event'] == 'manual_action_unconfirmed' and h['dropped'] == 1 for h in r.sync.history)
|
||||
assert not r.sync.manual_queue
|
||||
assert sent and clicks(sent[0]) == -1, "then the Tesla is put back on the comma's speed"
|
||||
|
||||
|
||||
def test_a_driver_scroll_the_comma_followed_needs_no_correction():
|
||||
r = Rig()
|
||||
r.settle(1)
|
||||
r.tick(wheel(right_scroll=1))
|
||||
r.tick()
|
||||
r.speed = r.target = 78 # the Tesla and the comma both took the scroll
|
||||
assert not r.settle(MANUAL_COMPLETION_NS / 1e9 + 1)
|
||||
assert r.sync.status == 'matched' and r.sync.blocked is None
|
||||
assert 'manual_action_unconfirmed' in r.sync.noticed, 'the wait always ends with the same notice'
|
||||
|
||||
|
||||
def test_a_fast_driver_scroll_is_one_gesture_and_one_notice_per_engagement():
|
||||
r = Rig()
|
||||
r.settle(1)
|
||||
for _ in range(2):
|
||||
r.tick(wheel(right_scroll=3))
|
||||
r.tick(wheel(right_scroll=2)) # the same flick, still turning
|
||||
r.tick()
|
||||
assert len(r.sync.manual_queue) == 1 and r.sync.manual_queue[0][2:] == ('right_wheel_up', True)
|
||||
r.settle(MANUAL_COMPLETION_NS / 1e9 + 0.2)
|
||||
assert not r.sync.manual_queue
|
||||
assert len([h for h in r.sync.history if h['event'] == 'manual_action_unconfirmed']) == 2
|
||||
assert [n['kind'] for n in r.sync.notices].count('manual_action_unconfirmed') == 1
|
||||
|
||||
|
||||
def test_nothing_is_sent_right_after_a_driver_scroll_that_was_never_queued():
|
||||
r = Rig()
|
||||
r.settle(1)
|
||||
r.tick(wheel(right_left=2, right_scroll=1)) # unclear input: paused, not queued
|
||||
r.tick()
|
||||
r.speed = 78
|
||||
assert not r.settle(MANUAL_SETTLE_NS / 1e9 - 0.15), "the Tesla gets time to apply the driver's own scroll first"
|
||||
assert r.sync.status == 'waiting_for_driver_scroll'
|
||||
assert r.settle(0.5)
|
||||
|
||||
|
||||
def test_clock_faults_still_stop():
|
||||
r = Rig()
|
||||
r.settle(0.5)
|
||||
r.sync.observe([(r.now - TICK, [(0x3c2, NEUTRAL, 1)])])
|
||||
assert r.sync.blocked == 'wheel_clock_reversal'
|
||||
|
||||
|
||||
# Card's receipts for the driver's own scrolls.
|
||||
|
||||
def scrolled(r, ticks=1):
|
||||
"""The driver scrolls once; returns the engine's record of it: (stamp, frame index, name, fast)."""
|
||||
r.settle(1)
|
||||
r.tick(wheel(right_scroll=ticks))
|
||||
r.tick()
|
||||
entry, = r.sync.manual_queue
|
||||
return entry
|
||||
|
||||
|
||||
def receipt_for(entry, **changes):
|
||||
"""What card records when it applies the comma step for that scroll, in the frame the scroll was seen."""
|
||||
stamp, index, name, fast = entry
|
||||
values = dict(boot_ns=stamp, frame_index=index, name=name, fast=fast, worker_session=SESSION, sequence=1,
|
||||
document_hash=DOCUMENT, vehicle_hash=VEHICLE, drive_start_ns=DRIVE, processed_boot_ns=stamp,
|
||||
target_kph=78 * MPH)
|
||||
values.update(changes)
|
||||
return ManualReceipt(**values)
|
||||
|
||||
|
||||
def authority(r, *receipts, **changes):
|
||||
values = dict(observed_boot_ns=r.now, target_kph=r.target * MPH, is_metric=False, configuration_id='a' * 64, software_owned=True,
|
||||
document_hash=DOCUMENT, vehicle_hash=VEHICLE, drive_start_ns=DRIVE, manual_receipts=tuple(receipts))
|
||||
values.update(changes)
|
||||
return SyncAuthority(**values)
|
||||
|
||||
|
||||
def test_a_receipt_releases_the_drivers_scroll_at_once():
|
||||
r = Rig()
|
||||
entry = scrolled(r)
|
||||
assert entry[1:] == (1, 'right_wheel_up', False) and r.sync.status == 'waiting_for_manual_processing'
|
||||
receipt = receipt_for(entry)
|
||||
r.speed = r.target = 78 # the Tesla and the comma both took it
|
||||
r.sync.target = ('stale',)
|
||||
r.sync.accept_manual_receipts(authority(r, receipt), r.now)
|
||||
assert not r.sync.manual_queue and r.sync.target is None, 'the comma target is read again'
|
||||
assert r.sync.take_manual_receipt_acks() == (receipt,) and r.sync.take_manual_receipt_acks() == ()
|
||||
r.tick()
|
||||
assert r.sync.status == 'matched' and r.sync.blocked is None
|
||||
assert not r.settle(MANUAL_COMPLETION_NS / 1e9 + .5)
|
||||
assert 'manual_action_unconfirmed' not in r.sync.noticed
|
||||
|
||||
|
||||
def test_with_a_receipt_a_difference_is_corrected_without_waiting_out_the_window():
|
||||
r = Rig()
|
||||
receipt = receipt_for(scrolled(r))
|
||||
r.speed, r.target = 79, 78 # the Tesla moved further than the comma did
|
||||
r.sync.accept_manual_receipts(authority(r, receipt), r.now)
|
||||
sent = r.settle(MANUAL_SETTLE_NS / 1e9 + .2)
|
||||
assert sent and clicks(sent[0]) == -1, "corrected as soon as the Tesla has applied the driver's own scroll"
|
||||
assert r.sent[0][0] - receipt.boot_ns < MANUAL_COMPLETION_NS // 2
|
||||
waiting = Rig()
|
||||
scrolled(waiting)
|
||||
waiting.speed, waiting.target = 79, 78
|
||||
assert not waiting.settle(MANUAL_SETTLE_NS / 1e9 + .2), 'without a receipt the scroll still waits'
|
||||
|
||||
|
||||
def test_a_receipt_may_arrive_before_the_scroll_is_seen_on_the_bus():
|
||||
r = Rig()
|
||||
r.settle(1)
|
||||
r.tick(wheel(right_scroll=3))
|
||||
early = receipt_for((r.now + TICK, 1, 'right_wheel_up', True), processed_boot_ns=r.now + TICK)
|
||||
r.now += TICK # card applied the step in the frame the release arrives in; speed sync sees that frame next
|
||||
r.sync.accept_manual_receipts(authority(r, early), r.now)
|
||||
assert r.sync.manual_receipts == {(early.boot_ns, 1): early} and r.sync.take_manual_receipt_acks() == (early,)
|
||||
r.now -= TICK
|
||||
r.tick()
|
||||
assert r.sync.manual_queue == [(early.boot_ns, 1, 'right_wheel_up', True)]
|
||||
r.sync.accept_manual_receipts(authority(r), r.now)
|
||||
assert not r.sync.manual_queue and not r.sync.manual_receipts and r.sync.blocked is None
|
||||
|
||||
|
||||
@pytest.mark.parametrize('changes', [dict(name='right_wheel_down'), dict(fast=True)])
|
||||
def test_a_receipt_for_a_different_scroll_at_the_same_frame_stops_sync(changes):
|
||||
r = Rig()
|
||||
receipt = receipt_for(scrolled(r), **changes)
|
||||
r.sync.accept_manual_receipts(authority(r, receipt), r.now)
|
||||
assert r.sync.blocked == 'manual_receipt_mismatch'
|
||||
assert not r.settle(3), 'stopped until disengaging'
|
||||
|
||||
|
||||
@pytest.mark.parametrize('changes', [
|
||||
dict(document_hash='f' * 64), dict(vehicle_hash='f' * 64), dict(drive_start_ns=DRIVE + 1), dict(drive_start_ns=0),
|
||||
dict(worker_session='x' * 32), dict(worker_session='0' * 31), dict(sequence=0), dict(sequence=1.0),
|
||||
dict(name='right_wheel_left'), dict(name='left_wheel_up'), dict(fast=1),
|
||||
dict(frame_index=-1), dict(frame_index=4096), dict(frame_index=1.0),
|
||||
dict(target_kph=0), dict(target_kph=255), dict(target_kph=float('nan')), dict(target_kph='125'),
|
||||
dict(processed_boot_ns=0), dict(boot_ns=0), dict(boot_ns=1.5),
|
||||
])
|
||||
def test_a_receipt_that_fails_any_check_is_ignored_and_the_scroll_waits_out_its_window(changes):
|
||||
r = Rig()
|
||||
entry = scrolled(r)
|
||||
receipt = receipt_for(entry, **changes)
|
||||
r.sync.accept_manual_receipts(authority(r, receipt), r.now)
|
||||
assert r.sync.manual_queue == [entry] and r.sync.blocked is None
|
||||
assert r.sync.take_manual_receipt_acks() == (), 'never taken into custody'
|
||||
r.settle(MANUAL_COMPLETION_NS / 1e9 + .2)
|
||||
assert 'manual_action_unconfirmed' in r.sync.noticed and not r.sync.manual_queue
|
||||
|
||||
|
||||
def test_a_receipt_processed_in_the_future_or_before_its_scroll_is_ignored():
|
||||
r = Rig()
|
||||
entry = scrolled(r)
|
||||
for changes in (dict(processed_boot_ns=r.now + 1), dict(processed_boot_ns=entry[0] - 1)):
|
||||
r.sync.accept_manual_receipts(authority(r, receipt_for(entry, **changes)), r.now)
|
||||
assert r.sync.manual_queue == [entry] and r.sync.take_manual_receipt_acks() == ()
|
||||
|
||||
|
||||
@pytest.mark.parametrize('changes', [dict(document_hash=''), dict(vehicle_hash=''), dict(document_hash='d' * 63)])
|
||||
def test_receipts_need_an_admission_that_names_the_assignments_and_the_car(changes):
|
||||
r = Rig()
|
||||
entry = scrolled(r)
|
||||
receipt = receipt_for(entry, **changes)
|
||||
r.sync.accept_manual_receipts(authority(r, receipt, **changes), r.now)
|
||||
assert r.sync.manual_queue == [entry] and r.sync.take_manual_receipt_acks() == ()
|
||||
|
||||
|
||||
def test_an_expired_receipt_is_disposed_of_and_completes_nothing():
|
||||
r = Rig()
|
||||
entry = scrolled(r)
|
||||
receipt = receipt_for(entry)
|
||||
r.now = entry[0] + MANUAL_COMPLETION_NS + 1
|
||||
r.sync.accept_manual_receipts(authority(r, receipt), r.now)
|
||||
assert r.sync.manual_queue == [entry] and not r.sync.manual_receipts
|
||||
assert r.sync.take_manual_receipt_acks() == (receipt,), 'handed back so card drops it'
|
||||
r.now = entry[0] + MANUAL_COMPLETION_NS
|
||||
r.sync.accept_manual_receipts(authority(r, receipt), r.now)
|
||||
assert not r.sync.manual_queue, 'exactly at the end of the window still counts'
|
||||
|
||||
|
||||
def test_a_receipt_for_a_scroll_already_dealt_with_is_handed_back():
|
||||
r = Rig()
|
||||
entry = scrolled(r)
|
||||
receipt = receipt_for(entry)
|
||||
r.sync.accept_manual_receipts(authority(r, receipt), r.now)
|
||||
r.sync.take_manual_receipt_acks()
|
||||
r.sync.accept_manual_receipts(authority(r, receipt), r.now) # card had not yet seen the acknowledgment
|
||||
assert r.sync.take_manual_receipt_acks() == (receipt,) and not r.sync.manual_receipts and r.sync.blocked is None
|
||||
|
||||
|
||||
def test_a_cached_receipt_expires_with_its_window():
|
||||
r = Rig()
|
||||
r.settle(1)
|
||||
early = receipt_for((r.now, 1, 'right_wheel_up', False), processed_boot_ns=r.now)
|
||||
r.sync.accept_manual_receipts(authority(r, early), r.now)
|
||||
assert r.sync.manual_receipts
|
||||
r.settle(MANUAL_COMPLETION_NS / 1e9 + .1)
|
||||
r.sync.accept_manual_receipts(authority(r), r.now)
|
||||
assert not r.sync.manual_receipts and r.sync.blocked is None
|
||||
|
||||
|
||||
def test_more_receipts_than_card_ever_holds_stop_sync():
|
||||
r = Rig()
|
||||
entry = scrolled(r)
|
||||
many = tuple(receipt_for(entry, sequence=index + 1) for index in range(17))
|
||||
r.sync.accept_manual_receipts(authority(r, *many), r.now)
|
||||
assert r.sync.blocked == 'invalid_manual_receipts'
|
||||
r = Rig()
|
||||
scrolled(r)
|
||||
r.sync.accept_manual_receipts(replace(authority(r), manual_receipts=[]), r.now)
|
||||
assert r.sync.blocked == 'invalid_manual_receipts', 'only a tuple, as card builds it'
|
||||
|
||||
|
||||
def test_sixteen_receipts_are_accepted():
|
||||
r = Rig()
|
||||
r.settle(1)
|
||||
receipts = tuple(receipt_for((r.now - index, index, 'right_wheel_up', False), processed_boot_ns=r.now, sequence=index + 1)
|
||||
for index in range(16))
|
||||
r.sync.accept_manual_receipts(authority(r, *receipts), r.now)
|
||||
assert r.sync.blocked is None and len(r.sync.manual_receipts) == 16
|
||||
assert r.sync.take_manual_receipt_acks() == receipts
|
||||
|
||||
|
||||
def test_two_different_receipts_for_one_scroll_stop_sync():
|
||||
r = Rig()
|
||||
r.settle(1)
|
||||
first = receipt_for((r.now, 1, 'right_wheel_up', False), processed_boot_ns=r.now)
|
||||
r.sync.accept_manual_receipts(authority(r, first), r.now)
|
||||
r.sync.accept_manual_receipts(authority(r, replace(first, sequence=2)), r.now)
|
||||
assert r.sync.blocked == 'conflicting_manual_receipt'
|
||||
|
||||
|
||||
def test_anything_that_is_not_a_receipt_is_skipped():
|
||||
r = Rig()
|
||||
entry = scrolled(r)
|
||||
receipt = receipt_for(entry)
|
||||
r.sync.accept_manual_receipts(authority(r, None, 'receipt', (1, 2), receipt), r.now)
|
||||
assert not r.sync.manual_queue and r.sync.take_manual_receipt_acks() == (receipt,)
|
||||
|
||||
|
||||
def test_disengaging_forgets_receipts_and_acknowledgments():
|
||||
r = Rig()
|
||||
r.settle(1)
|
||||
early = receipt_for((r.now, 1, 'right_wheel_up', False), processed_boot_ns=r.now)
|
||||
r.sync.accept_manual_receipts(authority(r, early), r.now)
|
||||
assert r.sync.manual_receipts and r.sync.manual_receipt_acks
|
||||
r.now += TICK
|
||||
r.sync.update(r.now, target_kph=77 * MPH, enabled=False, safe=True)
|
||||
assert not r.sync.manual_receipts and not r.sync.manual_receipt_acks and r.sync.take_manual_receipt_acks() == ()
|
||||
@@ -0,0 +1,161 @@
|
||||
"""Comma can set speed on Tesla dashboard: which cars can have it, and how the startup choice lands in CarParams."""
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
from opendbc.car import gen_empty_fingerprint, get_safety_config, structs
|
||||
from opendbc.car.tesla.carcontroller import CarController
|
||||
from opendbc.car.tesla.interface import CarInterface
|
||||
from opendbc.car.tesla.speed_sync import MODELS, SYNC_FLAG, SpeedSynchronizer, eligible, prepare, selected
|
||||
from opendbc.car.tesla.values import CAR, CANBUS, DBC, TeslaFlags, TeslaSafetyFlags
|
||||
|
||||
MODERN = (CAR.TESLA_MODEL_3, CAR.TESLA_MODEL_Y)
|
||||
|
||||
|
||||
def tesla(candidate=CAR.TESLA_MODEL_3, *, cable=True, long=True):
|
||||
fingerprint = gen_empty_fingerprint()
|
||||
fingerprint[CANBUS.autopilot_party][0x489] = 8
|
||||
if cable:
|
||||
fingerprint[CANBUS.vehicle][0x3DF] = 8
|
||||
return CarInterface.get_params(candidate, fingerprint, [], long, False, False)
|
||||
|
||||
|
||||
def word(cp):
|
||||
return int(cp.safetyConfigs[0].safetyParam)
|
||||
|
||||
|
||||
def raw(cp):
|
||||
"""The whole CarParams as bytes, from a copy so the builder can be written again."""
|
||||
return cp.as_reader().as_builder().to_bytes()
|
||||
|
||||
|
||||
def two_configs(cp):
|
||||
cp.safetyConfigs = [get_safety_config(structs.CarParams.SafetyModel.tesla, 1 | SYNC_FLAG),
|
||||
get_safety_config(structs.CarParams.SafetyModel.tesla, 1 | SYNC_FLAG)]
|
||||
|
||||
|
||||
def no_configs(cp):
|
||||
cp.safetyConfigs = []
|
||||
|
||||
|
||||
# Each one alone takes the feature away from an otherwise eligible Model 3.
|
||||
MISSING = {
|
||||
'other brand': lambda cp: setattr(cp, 'brand', 'hyundai'),
|
||||
'model x': lambda cp: setattr(cp, 'carFingerprint', str(CAR.TESLA_MODEL_X)),
|
||||
'model s hw1': lambda cp: setattr(cp, 'carFingerprint', str(CAR.TESLA_MODEL_S_HW1)),
|
||||
'model s pre-ap': lambda cp: setattr(cp, 'carFingerprint', str(CAR.TESLA_MODEL_S_PREAP)),
|
||||
'unknown fingerprint': lambda cp: setattr(cp, 'carFingerprint', 'MOCK'),
|
||||
'stock longitudinal': lambda cp: setattr(cp, 'openpilotLongitudinalControl', False),
|
||||
'no car cruise': lambda cp: setattr(cp, 'pcmCruise', False),
|
||||
'passive': lambda cp: setattr(cp, 'passive', True),
|
||||
'dashcam': lambda cp: setattr(cp, 'dashcamOnly', True),
|
||||
'not a car': lambda cp: setattr(cp, 'notCar', True),
|
||||
'no cable': lambda cp: setattr(cp, 'flags', int(cp.flags) & ~int(TeslaFlags.HAS_VEHICLE_BUS)),
|
||||
'no safety config': no_configs,
|
||||
'two safety configs': two_configs,
|
||||
'safety word without longitudinal': lambda cp: setattr(cp.safetyConfigs[0], 'safetyParam', word(cp) & ~1),
|
||||
}
|
||||
|
||||
|
||||
def test_the_flag_is_its_own_bit():
|
||||
assert SYNC_FLAG == 4096 == int(TeslaSafetyFlags.SCROLL_SPEED_SYNC)
|
||||
others = [flag for flag in TeslaSafetyFlags if flag is not TeslaSafetyFlags.SCROLL_SPEED_SYNC]
|
||||
assert not any(SYNC_FLAG & int(flag) for flag in others)
|
||||
assert not SYNC_FLAG & 2048, 'ordinary Always On Lateral keeps 2048'
|
||||
assert MODELS == tuple(str(model) for model in MODERN)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('candidate', MODERN)
|
||||
def test_model_3_and_y_with_cable_and_longitudinal_are_eligible_and_start_unselected(candidate):
|
||||
cp = tesla(candidate)
|
||||
assert eligible(cp)
|
||||
assert word(cp) == 1 and not selected(cp), 'the car interface never selects it; startup preferences do'
|
||||
|
||||
|
||||
@pytest.mark.parametrize('candidate', MODERN)
|
||||
@pytest.mark.parametrize('cable,long', [(False, True), (True, False), (False, False)])
|
||||
def test_cable_and_longitudinal_are_both_needed(candidate, cable, long):
|
||||
cp = tesla(candidate, cable=cable, long=long)
|
||||
before = raw(cp)
|
||||
assert not eligible(cp) and not selected(cp)
|
||||
assert prepare(cp, True) is cp and raw(cp) == before
|
||||
|
||||
|
||||
@pytest.mark.parametrize('reason', MISSING)
|
||||
def test_every_condition_is_required(reason):
|
||||
cp = tesla()
|
||||
prepare(cp, True)
|
||||
assert selected(cp)
|
||||
MISSING[reason](cp)
|
||||
assert not eligible(cp), reason
|
||||
assert not selected(cp), 'a set bit alone selects nothing'
|
||||
|
||||
|
||||
@pytest.mark.parametrize('reason', MISSING)
|
||||
@pytest.mark.parametrize('requested', (False, True))
|
||||
def test_prepare_never_touches_a_car_that_is_not_eligible(reason, requested):
|
||||
cp = tesla()
|
||||
if reason not in ('no safety config', 'two safety configs'):
|
||||
cp.safetyConfigs[0].safetyParam = word(cp) | SYNC_FLAG # even a stale bit is left for the car's own code
|
||||
MISSING[reason](cp)
|
||||
before = raw(cp)
|
||||
assert prepare(cp, requested) is cp
|
||||
assert raw(cp) == before
|
||||
|
||||
|
||||
@pytest.mark.parametrize('candidate', MODERN)
|
||||
@pytest.mark.parametrize('base', (1, 257, 513, 769, 1537, 1793, 2049, 2305, 3073, 3329))
|
||||
def test_prepare_sets_and_clears_only_its_own_bit(candidate, base):
|
||||
cp = tesla(candidate)
|
||||
cp.safetyConfigs[0].safetyParam = base
|
||||
rest = raw(cp)
|
||||
for _ in range(2):
|
||||
assert prepare(cp, True) is cp
|
||||
assert word(cp) == base | SYNC_FLAG and selected(cp)
|
||||
for _ in range(2):
|
||||
assert prepare(cp, False) is cp
|
||||
assert word(cp) == base and not selected(cp) and eligible(cp)
|
||||
assert raw(cp) == rest, 'nothing else in CarParams moved'
|
||||
|
||||
|
||||
def test_prepare_clears_a_stale_selection():
|
||||
cp = tesla()
|
||||
cp.safetyConfigs[0].safetyParam = 4097
|
||||
prepare(cp, False)
|
||||
assert word(cp) == 1 and not selected(cp)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('cp', [None, object(), SimpleNamespace(), SimpleNamespace(brand='tesla'),
|
||||
SimpleNamespace(brand='tesla', carFingerprint='TESLA_MODEL_3', openpilotLongitudinalControl=True,
|
||||
pcmCruise=True, passive=False, dashcamOnly=False, notCar=False, flags=None,
|
||||
safetyConfigs=[])])
|
||||
def test_missing_or_malformed_car_parameters_are_not_eligible(cp):
|
||||
assert eligible(cp) is False and selected(cp) is False
|
||||
assert prepare(cp, True) is cp
|
||||
|
||||
|
||||
def test_a_reader_is_judged_like_its_builder():
|
||||
cp = tesla()
|
||||
assert eligible(cp.as_reader()) and not selected(cp.as_reader())
|
||||
prepare(cp, True)
|
||||
assert selected(cp.as_reader())
|
||||
|
||||
|
||||
@pytest.mark.parametrize('candidate', MODERN)
|
||||
def test_the_controller_builds_a_synchronizer_only_when_selected(candidate):
|
||||
cp = tesla(candidate)
|
||||
assert CarController(DBC[candidate], cp).speed_sync is None
|
||||
prepare(cp, True)
|
||||
assert isinstance(CarController(DBC[candidate], cp).speed_sync, SpeedSynchronizer)
|
||||
prepare(cp, False)
|
||||
assert CarController(DBC[candidate], cp).speed_sync is None
|
||||
|
||||
|
||||
@pytest.mark.parametrize('candidate', (CAR.TESLA_MODEL_X, CAR.TESLA_MODEL_S_HW1, CAR.TESLA_MODEL_S_PREAP))
|
||||
def test_other_teslas_never_get_a_synchronizer(candidate):
|
||||
cp = tesla(candidate)
|
||||
before = raw(cp)
|
||||
assert not eligible(cp) and not selected(cp)
|
||||
prepare(cp, True)
|
||||
assert raw(cp) == before
|
||||
assert CarController(DBC[candidate], cp).speed_sync is None
|
||||
@@ -132,6 +132,7 @@ class CarControllerParams:
|
||||
class TeslaSafetyFlags(IntFlag):
|
||||
LONG_CONTROL = 1
|
||||
HW1 = 16
|
||||
SCROLL_SPEED_SYNC = 4096 # 2048 is the ordinary AOL word
|
||||
COOP_STEERING = 256
|
||||
AOL_SCREEN_BUTTON = 512
|
||||
AOL_SCREEN_DISENGAGE_ON_BRAKE = 1024
|
||||
|
||||
@@ -22,6 +22,7 @@ from opendbc.car.mg.values import CAR as MG
|
||||
|
||||
# Configurations with source tests but no matching recorded route.
|
||||
unrecorded_route_gaps = {
|
||||
SUBARU.SUBARU_CROSSTREK_2018: "subaru/tests/test_supported_firmware.py",
|
||||
GM.CHEVROLET_VOLT_CC: "gm/tests/test_volt_cc_gas.py",
|
||||
GM.CHEVROLET_MALIBU_HYBRID_CC: "gm/tests/test_ordinary_cc.py",
|
||||
TOYOTA.TOYOTA_PRIUS_RETROFIT: "toyota/tests/test_retrofit.py",
|
||||
@@ -29,6 +30,7 @@ unrecorded_route_gaps = {
|
||||
VOLVO.VOLVO_XC40_RECHARGE: "volvo/tests/test_cma.py",
|
||||
VOLVO.VOLVO_S60_RECHARGE: "volvo/tests/test_cma.py",
|
||||
VOLVO.POLESTAR_2: "volvo/tests/test_cma.py",
|
||||
VOLVO.VOLVO_V60: "volvo/tests/test_eucd.py",
|
||||
}
|
||||
|
||||
# FIXME: add routes for these cars
|
||||
|
||||
@@ -9,6 +9,8 @@ from opendbc.car.interfaces import CarInterfaceBase, get_interface_attr
|
||||
from opendbc.car.values import PLATFORMS
|
||||
from opendbc.car.volvo.cma_carcontroller import CarControllerCMA
|
||||
from opendbc.car.volvo.cma_carstate import CarStateCMA
|
||||
from opendbc.car.volvo.eucd_carcontroller import CarControllerEUCD
|
||||
from opendbc.car.volvo.eucd_carstate import CarStateEUCD
|
||||
from opendbc.car.volvo.values import CAR as VOLVO
|
||||
from opendbc.testing import Fuzzy, fuzzy_test
|
||||
|
||||
@@ -118,6 +120,9 @@ def _make_optional_hardware_test(car_name):
|
||||
if car_name in (VOLVO.VOLVO_XC40_RECHARGE, VOLVO.VOLVO_S60_RECHARGE, VOLVO.POLESTAR_2):
|
||||
self.assertIsInstance(interface.CS, CarStateCMA)
|
||||
self.assertIsInstance(interface.CC, CarControllerCMA)
|
||||
elif car_name == VOLVO.VOLVO_V60:
|
||||
self.assertIsInstance(interface.CS, CarStateEUCD)
|
||||
self.assertIsInstance(interface.CC, CarControllerEUCD)
|
||||
else:
|
||||
self.assertIsInstance(interface.CS, interface_type.CarState)
|
||||
self.assertIsInstance(interface.CC, interface_type.CarController)
|
||||
|
||||
@@ -337,7 +337,7 @@ class TestFwFingerprintTiming(unittest.TestCase):
|
||||
assert first.whitelist_ecus == second.whitelist_ecus
|
||||
|
||||
def test_fw_query_timing(self):
|
||||
total_ref_time = 8.4
|
||||
total_ref_time = 8.5
|
||||
brand_ref_times = {
|
||||
'gm': 1.0,
|
||||
'body': 0.1,
|
||||
@@ -355,7 +355,7 @@ class TestFwFingerprintTiming(unittest.TestCase):
|
||||
'rivian': 0.3,
|
||||
'psa': 0.1,
|
||||
'mg': 0.1,
|
||||
'volvo': 0.0, # Current Volvo FwQueryConfig has no requests.
|
||||
'volvo': 0.1,
|
||||
}
|
||||
|
||||
total_times = 0.0
|
||||
|
||||
@@ -4,6 +4,7 @@ from pathlib import Path
|
||||
from opendbc.car.values import PLATFORMS
|
||||
from opendbc.car.tests.routes import non_tested_cars, routes, unrecorded_route_gaps
|
||||
from opendbc.car.gm.values import CAR as GM
|
||||
from opendbc.car.subaru.values import CAR as SUBARU
|
||||
from opendbc.car.tesla.values import CAR as TESLA
|
||||
from opendbc.car.toyota.values import CAR as TOYOTA
|
||||
from opendbc.car.volvo.values import CAR as VOLVO
|
||||
@@ -20,7 +21,7 @@ class TestRoutes(unittest.TestCase):
|
||||
def test_explicit_unrecorded_configuration_gaps(self):
|
||||
self.assertEqual(set(unrecorded_route_gaps), {
|
||||
GM.CHEVROLET_VOLT_CC, GM.CHEVROLET_MALIBU_HYBRID_CC, TOYOTA.TOYOTA_PRIUS_RETROFIT, TESLA.TESLA_MODEL_S_HW1,
|
||||
VOLVO.VOLVO_XC40_RECHARGE, VOLVO.VOLVO_S60_RECHARGE, VOLVO.POLESTAR_2,
|
||||
SUBARU.SUBARU_CROSSTREK_2018, VOLVO.VOLVO_XC40_RECHARGE, VOLVO.VOLVO_S60_RECHARGE, VOLVO.POLESTAR_2, VOLVO.VOLVO_V60,
|
||||
})
|
||||
self.assertFalse(set(unrecorded_route_gaps) & {route.car_model for route in routes})
|
||||
self.assertTrue(set(unrecorded_route_gaps) <= set(non_tested_cars))
|
||||
|
||||
@@ -169,6 +169,7 @@ legend = ["LAT_ACCEL_FACTOR", "MAX_LAT_ACCEL_MEASURED", "FRICTION"]
|
||||
"TESLA_MODEL_S_HW1" = [nan, 2.5, nan]
|
||||
|
||||
"VOLVO_V40" = [1.5, 1.5, 0.1]
|
||||
"VOLVO_V60" = [1.5, 1.5, 0.1]
|
||||
|
||||
"CHEVROLET_SUBURBAN" = [1.2, 2.5, 0.26]
|
||||
"CHEVROLET_MALIBU_CC" = [1.85, 1.85, 0.075]
|
||||
|
||||
@@ -111,6 +111,7 @@ legend = ["LAT_ACCEL_FACTOR", "MAX_LAT_ACCEL_MEASURED", "FRICTION"]
|
||||
"SEAT_ATECA_MK1" = "VOLKSWAGEN_GOLF_MK7"
|
||||
"VOLKSWAGEN_JETTA_MK6" = "VOLKSWAGEN_PASSAT_NMS"
|
||||
|
||||
"SUBARU_CROSSTREK_2018" = "SUBARU_IMPREZA"
|
||||
"SUBARU_CROSSTREK_HYBRID" = "SUBARU_IMPREZA_2020"
|
||||
"SUBARU_FORESTER_HYBRID" = "SUBARU_IMPREZA_2020"
|
||||
"SUBARU_LEGACY" = "SUBARU_OUTBACK"
|
||||
|
||||
@@ -11,7 +11,7 @@ from opendbc.car.interfaces import CarControllerBase
|
||||
from opendbc.car.toyota import toyotacan
|
||||
from opendbc.car.toyota import (dom_defaults, prius_longitudinal, rav4h_filter, pedal, eps8_sdsu, legacy_sdsu,
|
||||
advert_filter, legacy_stop_timer, legacy_advert_filter)
|
||||
from opendbc.car.toyota import pedal_composite, camera_2aa_filter, prius_sdsu, prius_advert_filter
|
||||
from opendbc.car.toyota import pedal_composite, camera_2aa_filter, prius_sdsu, prius_advert_filter, radar_filter
|
||||
from opendbc.car.toyota.door_locks import DoorLocks
|
||||
from opendbc.car.toyota.values import CAR, CarControllerParams, ToyotaFlags, TOYOTA_AUTO_HOLD_CARS, uses_toyota_auto_hold_aeb
|
||||
from opendbc.can import CANPacker
|
||||
@@ -58,7 +58,10 @@ def supports_toyota_auto_hold(CP):
|
||||
|
||||
def get_long_tune(CP, params):
|
||||
prius = prius_longitudinal.enabled(CP)
|
||||
if prius or CP.flags & ToyotaFlags.TSS2 or dom_defaults.camry_hybrid(CP) or dom_defaults.rav4h_sdsu(CP):
|
||||
# The generic integral gain amplifies small acceleration requests on the four-byte Sienna filter.
|
||||
sienna_filter = (CP.carFingerprint == CAR.TOYOTA_SIENNA and not CP.flags & ToyotaFlags.GAS_INTERCEPTOR and
|
||||
legacy_advert_filter.enabled(CP))
|
||||
if prius or sienna_filter or CP.flags & ToyotaFlags.TSS2 or dom_defaults.camry_hybrid(CP) or dom_defaults.rav4h_sdsu(CP):
|
||||
kiBP = [2., 5.]
|
||||
kiV = [0.5, 0.25]
|
||||
else:
|
||||
@@ -93,6 +96,7 @@ class CarController(CarControllerBase):
|
||||
self.legacy_stop_timer = legacy_stop_timer.enabled(CP)
|
||||
self.legacy_advert_filter = legacy_advert_filter.configured(CP)
|
||||
self.camera_twoaa_filter = camera_2aa_filter.configured(CP)
|
||||
self.camry_se_idle_contract = radar_filter.camry_se_idle_contract(CP)
|
||||
self.permit_braking = True
|
||||
self.steer_rate_counter = 0
|
||||
self.distance_button = 0
|
||||
@@ -464,10 +468,21 @@ class CarController(CarControllerBase):
|
||||
not (self.brake_hold_active and not uses_toyota_auto_hold_aeb(self.CP))):
|
||||
pcm_accel_cmd = 0.
|
||||
main_accel_cmd = 0. if self.CP.flags & ToyotaFlags.SECOC.value else pcm_accel_cmd
|
||||
can_sends.append(toyotacan.create_accel_command(self.packer, main_accel_cmd, pcm_cancel_cmd, self.permit_braking, self.standstill_req, lead,
|
||||
CS.acc_type, fcw_alert, self.distance_button,
|
||||
reverse_cruise=bool(self.CP.pcmCruise and self.reverse_cruise_input is not None and
|
||||
self.reverse_cruise_input.update())))
|
||||
if (self.camry_se_idle_contract and CS.out.canValid and not CS.out.canTimeout and
|
||||
not CS.out.accFaulted and not CS.out.stockAeb and CS.pcm_acc_status == 0 and not CS.out.cruiseState.enabled and
|
||||
not CC.enabled and not CC.longActive and not pcm_cancel_cmd and not fcw_alert):
|
||||
# Match the filter's observed neutral frame until the PCM accepts SET.
|
||||
self.prev_accel = pcm_accel_cmd = 0.
|
||||
can_sends.append(self.packer.make_can_msg("ACC_CONTROL", 0, {
|
||||
"ACC_TYPE": 1,
|
||||
"ALLOW_LONG_PRESS": 3,
|
||||
"PERMIT_BRAKING": 1,
|
||||
}))
|
||||
else:
|
||||
can_sends.append(toyotacan.create_accel_command(self.packer, main_accel_cmd, pcm_cancel_cmd, self.permit_braking, self.standstill_req, lead,
|
||||
CS.acc_type, fcw_alert, self.distance_button,
|
||||
reverse_cruise=bool(self.CP.pcmCruise and self.reverse_cruise_input is not None and
|
||||
self.reverse_cruise_input.update())))
|
||||
if self.CP.flags & ToyotaFlags.SECOC.value:
|
||||
acc_cmd_2 = toyotacan.create_accel_command_2(self.packer, pcm_accel_cmd)
|
||||
acc_cmd_2 = add_mac(self.secoc_key,
|
||||
|
||||
@@ -31,6 +31,11 @@ TEMP_STEER_FAULTS = (0, 9, 11, 21, 25)
|
||||
PERM_STEER_FAULTS = (3, 17)
|
||||
|
||||
|
||||
def has_optional_prius_gap_button(CP):
|
||||
return (CP.carFingerprint == CAR.TOYOTA_PRIUS and not CP.openpilotLongitudinalControl and
|
||||
not CP.flags & (ToyotaFlags.LONG_FILTER | ToyotaFlags.FILTER_BUTTONS))
|
||||
|
||||
|
||||
class CarState(CarStateBase):
|
||||
def __init__(self, CP):
|
||||
super().__init__(CP)
|
||||
@@ -266,6 +271,10 @@ class CarState(CarStateBase):
|
||||
if self.CP.flags & ToyotaFlags.FILTER_BUTTONS or advert_filter.configured(self.CP) or prius_advert_filter.configured(self.CP):
|
||||
fresh = cp.advert_button_ns > 0 and 0 <= cp._last_update_nanos - cp.advert_button_ns <= 200_000_000
|
||||
self.distance_button = cp.advert_distance_button if fresh else 0
|
||||
elif not bypass and has_optional_prius_gap_button(self.CP):
|
||||
self.distance_button = cp_acc.vl["ACC_CONTROL"]["DISTANCE"]
|
||||
# A live gesture needs its source until the physical release arrives.
|
||||
cp_acc.message_states[0x343].ignore_alive = not self.distance_button
|
||||
else:
|
||||
self.distance_button = (cp.vl["SDSU"]["FD_BUTTON"] if self.CP.flags & ToyotaFlags.LONG_FILTER
|
||||
else cp_acc.vl["ACC_CONTROL"]["DISTANCE"])
|
||||
@@ -361,6 +370,10 @@ class CarState(CarStateBase):
|
||||
("BLINKERS_STATE", float('nan')),
|
||||
]
|
||||
|
||||
if has_optional_prius_gap_button(CP):
|
||||
# Factory cruise state and AEB are received on separate messages.
|
||||
pt_messages.append(("ACC_CONTROL", math.nan))
|
||||
|
||||
if CP.carFingerprint == CAR.TOYOTA_SIENNA_4TH_GEN:
|
||||
pt_messages.append(("PCM_CRUISE_4", 1))
|
||||
from opendbc.car.toyota import camera_2aa_filter
|
||||
|
||||
@@ -12,6 +12,36 @@ from opendbc.safety import ALTERNATIVE_EXPERIENCE
|
||||
SteerControlType = structs.CarParams.SteerControlType
|
||||
|
||||
|
||||
CAMERA_TORQUE_CARS = frozenset((
|
||||
CAR.TOYOTA_ALPHARD_TSS2, CAR.TOYOTA_AVALON_TSS2, CAR.TOYOTA_CAMRY_TSS2, CAR.TOYOTA_COROLLA_TSS2,
|
||||
CAR.TOYOTA_HIGHLANDER_TSS2, CAR.TOYOTA_PRIUS_TSS2, CAR.TOYOTA_RAV4_TSS2, CAR.TOYOTA_MIRAI,
|
||||
CAR.LEXUS_ES_TSS2, CAR.LEXUS_NX_TSS2, CAR.LEXUS_LC_TSS2, CAR.LEXUS_RX_TSS2,
|
||||
CAR.LEXUS_IS_TSS2, CAR.LEXUS_RC_TSS2,
|
||||
))
|
||||
|
||||
|
||||
def camera_stock_acc_supported(cp) -> bool:
|
||||
required = ToyotaFlags.TSS2 | ToyotaFlags.NO_DSU | ToyotaFlags.RAISED_ACCEL_LIMIT
|
||||
allowed = required | ToyotaFlags.HYBRID | ToyotaFlags.HAS_BSM
|
||||
if (cp is None or cp.brand != "toyota" or cp.carFingerprint not in CAMERA_TORQUE_CARS or
|
||||
cp.notCar or cp.passive or cp.dashcamOnly or cp.secOcRequired or cp.alphaLongitudinalAvailable or not cp.pcmCruise or
|
||||
cp.steerControlType != SteerControlType.torque or len(cp.safetyConfigs) != 1 or
|
||||
cp.flags & required != required or int(cp.flags) & ~int(allowed)):
|
||||
return False
|
||||
config = cp.safetyConfigs[0]
|
||||
expected = EPS_SCALE[cp.carFingerprint]
|
||||
if not cp.openpilotLongitudinalControl:
|
||||
expected |= int(ToyotaSafetyFlags.STOCK_LONGITUDINAL)
|
||||
return config.safetyModel == structs.CarParams.SafetyModel.toyota and config.safetyParam == expected
|
||||
|
||||
|
||||
def prepare_camera_stock_acc(cp, requested: bool) -> None:
|
||||
if requested and camera_stock_acc_supported(cp):
|
||||
cp.openpilotLongitudinalControl = False
|
||||
cp.autoResumeSng = False
|
||||
cp.safetyConfigs[0].safetyParam |= int(ToyotaSafetyFlags.STOCK_LONGITUDINAL)
|
||||
|
||||
|
||||
def toyota_auto_hold_supported(CP) -> bool:
|
||||
from opendbc.car.toyota import pedal, pedal_composite
|
||||
if not (CP.brand == "toyota" and CP.carFingerprint in TOYOTA_AUTO_HOLD_CARS and
|
||||
@@ -242,7 +272,8 @@ class CarInterface(CarInterfaceBase):
|
||||
|
||||
# min speed to enable ACC. if car can do stop and go, then set enabling speed
|
||||
# to a negative value, so it won't matter.
|
||||
ret.minEnableSpeed = -1. if stop_and_go else MIN_ACC_SPEED
|
||||
highlander_sdsu = candidate == CAR.TOYOTA_HIGHLANDER and (rav4h_sdsu or legacy_advert)
|
||||
ret.minEnableSpeed = -1. if stop_and_go or highlander_sdsu else MIN_ACC_SPEED
|
||||
|
||||
if ret.flags & ToyotaFlags.TSS2 or ret.flags & ToyotaFlags.LONG_FILTER and not (rav4h_sdsu or eps8_filter or legacy_filter):
|
||||
ret.flags |= ToyotaFlags.RAISED_ACCEL_LIMIT.value
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
from opendbc.can import CANParser
|
||||
from opendbc.car import structs
|
||||
from opendbc.car.toyota import legacy_sdsu, rav4h_filter
|
||||
from opendbc.car.toyota.values import CAR, ToyotaFlags
|
||||
from opendbc.car.toyota.values import CAR, MIN_ACC_SPEED, ToyotaFlags
|
||||
from opendbc.car.toyota.toyotacan import toyota_checksum
|
||||
|
||||
PROFILES = dict.fromkeys(rav4h_filter.EPS5_SDSU_CARS, (0x9449, 0x9649))
|
||||
@@ -78,6 +78,8 @@ def prepare_stock(cp):
|
||||
if not configured(cp):
|
||||
return False
|
||||
cp.openpilotLongitudinalControl = False
|
||||
if cp.carFingerprint == CAR.TOYOTA_HIGHLANDER:
|
||||
cp.minEnableSpeed = MIN_ACC_SPEED
|
||||
cp.safetyConfigs[0].safetyParam = PROFILES[cp.carFingerprint][1]
|
||||
cp.autoResumeSng = False
|
||||
return True
|
||||
|
||||
@@ -49,6 +49,17 @@ def configured(cp):
|
||||
cp.safetyConfigs[0].safetyParam == (profile[1] if cp.openpilotLongitudinalControl else profile[2]))
|
||||
|
||||
|
||||
def camry_se_idle_contract(cp):
|
||||
if (cp.carFingerprint != CAR.TOYOTA_CAMRY or not cp.openpilotLongitudinalControl or
|
||||
not cp.pcmCruise or cp.passive or cp.dashcamOnly or cp.notCar or
|
||||
not cp.flags & ToyotaFlags.FILTER_BUTTONS or cp.flags & (ToyotaFlags.HYBRID | ToyotaFlags.GAS_INTERCEPTOR) or
|
||||
not configured(cp)):
|
||||
return False
|
||||
firmware = {(str(fw.ecu), fw.address, bytes(fw.fwVersion)) for fw in cp.carFw}
|
||||
return {("engine", 0x700, b"\x018966333P4700\x00\x00\x00\x00"),
|
||||
("dsu", 0x791, b"8821F0601300 ")} <= firmware
|
||||
|
||||
|
||||
def prepare_stock(cp):
|
||||
from opendbc.car.toyota import pedal_composite
|
||||
if pedal_composite.marked(cp):
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
from opendbc.can import CANParser
|
||||
from opendbc.car import structs
|
||||
from opendbc.car.config_cache import cached_config
|
||||
from opendbc.car.toyota.values import CAR, ToyotaFlags
|
||||
from opendbc.car.toyota.values import CAR, MIN_ACC_SPEED, ToyotaFlags
|
||||
|
||||
# Bit15 is a distinct exact-profile marker; reserve Dom bit14 for Lexus ALT_CRUISE.
|
||||
EPS5_SDSU_CARS = frozenset((
|
||||
@@ -76,6 +76,8 @@ def prepare_stock(cp):
|
||||
cp.flags &= ~int(ToyotaFlags.AUTO_BRAKE_HOLD)
|
||||
cp.alternativeExperience &= ~(128 | 256)
|
||||
cp.openpilotLongitudinalControl = False
|
||||
if cp.carFingerprint == CAR.TOYOTA_HIGHLANDER:
|
||||
cp.minEnableSpeed = MIN_ACC_SPEED
|
||||
cp.safetyConfigs[0].safetyParam = STOCK_WORD
|
||||
cp.autoResumeSng = False
|
||||
return True
|
||||
|
||||
@@ -20,9 +20,26 @@ WORDS = frozenset(PROFILES.values())
|
||||
|
||||
|
||||
def hardware_supported(candidate, fingerprint):
|
||||
return (candidate in PROFILES and
|
||||
not any(address in frames for frames in fingerprint.values() for address in (0x201, 0x2FF, 0x2AA)) and
|
||||
not any(address in fingerprint.get(2, {}) for address in (0x343, 0x4CB)))
|
||||
if candidate not in PROFILES:
|
||||
return False
|
||||
from opendbc.car.toyota.radar_filter import _cluster_radar_bus
|
||||
|
||||
for bus, frames in fingerprint.items():
|
||||
if 0x201 in frames or 0x2AA in frames:
|
||||
return False
|
||||
if 0x2FF in frames and not (candidate == CAR.TOYOTA_CAMRY and _cluster_radar_bus(candidate, bus, frames)):
|
||||
return False
|
||||
camera = fingerprint.get(2, {})
|
||||
if 0x4CB in camera:
|
||||
return False
|
||||
if 0x343 not in camera:
|
||||
return True
|
||||
|
||||
# The stock Camry can mirror its powertrain bus at startup, including ACC_CONTROL.
|
||||
# An independent camera fingerprint is still treated as possible takeover hardware.
|
||||
pt = fingerprint.get(0, {})
|
||||
return (candidate == CAR.TOYOTA_CAMRY and pt == camera and
|
||||
all(pt.get(address) == 8 for address in (0xAA, 0x262, 0x343)))
|
||||
|
||||
|
||||
def apply(cp):
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
import pytest
|
||||
|
||||
from opendbc.can import CANPacker
|
||||
from opendbc.car import Bus, gen_empty_fingerprint, structs
|
||||
from opendbc.car.toyota.carstate import CarState
|
||||
from opendbc.car.toyota.interface import CarInterface
|
||||
from opendbc.car.toyota.values import CAR, DBC
|
||||
|
||||
|
||||
@pytest.mark.parametrize('stock_aol', (True, False))
|
||||
def test_prius_gap_button_requires_the_source_only_during_a_press(stock_aol):
|
||||
fp = gen_empty_fingerprint()
|
||||
if not stock_aol:
|
||||
fp[2][0x343] = 8
|
||||
cp = CarInterface.get_params(CAR.TOYOTA_PRIUS, fp, [], False, False, False)
|
||||
assert not cp.openpilotLongitudinalControl
|
||||
assert cp.safetyConfigs[0].safetyParam == (0x6242 if stock_aol else 0x242)
|
||||
state = CarState(cp)
|
||||
parsers = state.get_can_parsers(cp)
|
||||
packer = CANPacker(DBC[CAR.TOYOTA_PRIUS][Bus.pt])
|
||||
gap = structs.CarState.ButtonEvent.Type.gapAdjustCruise
|
||||
|
||||
def edges(stamp, value=None):
|
||||
frames = [] if value is None else [packer.make_can_msg('ACC_CONTROL', 0, {'DISTANCE': value})]
|
||||
for parser in parsers.values():
|
||||
parser.update([(stamp, frames)])
|
||||
return [event.pressed for event in state.update(parsers).buttonEvents if event.type == gap]
|
||||
|
||||
assert edges(1_000_000_000) == []
|
||||
assert parsers[Bus.pt].message_states[0x343].ignore_alive
|
||||
assert not parsers[Bus.pt].message_states[0x1D3].ignore_alive
|
||||
assert not parsers[Bus.pt].message_states[0x262].ignore_alive
|
||||
assert edges(1_030_000_000, 1) == [True]
|
||||
gap_message = parsers[Bus.pt].message_states[0x343]
|
||||
assert not gap_message.ignore_alive
|
||||
assert edges(12_000_000_000) == []
|
||||
assert not gap_message.valid(12_000_000_000, False)
|
||||
assert edges(12_030_000_000, 0) == [False]
|
||||
assert gap_message.ignore_alive
|
||||
assert gap_message.valid(23_000_000_000, False)
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user